@constellationdev/cli 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +92 -92
  2. package/package.json +3 -4
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 c from'ansi-colors';import*as Ce from'os';import Ce__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 b from'path';import b__default,{dirname,join}from'path';import*as Ot from'fs';import {readFileSync,existsSync}from'fs';import {fileURLToPath,pathToFileURL}from'url';import*as U from'fs/promises';import U__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import ci from'tree-sitter-javascript';import pi from'tree-sitter-python';import gi from'tree-sitter-typescript';import ui from'tree-sitter';import fn from'ignore';import {z as z$1}from'zod';import Gt 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 _o=Object.defineProperty;var m=(s,e)=>()=>(s&&(e=s(s=0)),e);var Tr=(s,e)=>{for(var t in e)_o(s,t,{get:e[t],enumerable:true});};var Ge,kt=m(()=>{Ge=["help","--help","-h","--version","-V","-v"];});function Nr(s){return base32.encode(Buffer.from(s))}var Ar=m(()=>{});function Lr(s,e,t){let r=`${s}:${e}${t?`:${t}`:""}`;return Nr(r)}var jr=m(()=>{Ar();});var We,Or=m(()=>{We=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let r=JSON.stringify(e)+`
3
- `,n=Buffer.from(r,"utf8");if(!this.push(n))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),r=>t(e||r)):t(e);}};});function Po(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Ce.platform()==="win32"?!!(process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"||process.env.TERM_PROGRAM==="Hyper"||process.env.TERM&&process.env.TERM!=="cygwin"&&process.env.TERM!=="dumb"):true}var xo,Io,Ro,$o,To,ko,No,Ao,Lo,jo,_e,w,S,C,y,Y,D=m(()=>{xo="\u2714",Io="\u2717",Ro="\u26A0",$o="\u2139",To="\u26A1",ko="[OK]",No="[ERR]",Ao="[WARN]",Lo="[INFO]",jo="[>>]",_e=Po(),w=c.green(_e?xo:ko),S=c.red(_e?Io:No),C=c.yellow(_e?Ro:Ao),y=c.blue(_e?$o:Lo),Y=c.yellow(_e?To:jo);});var ze,Je,$,q,M,ce,X,Ve=m(()=>{jr();Or();D();ze=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 r of t.split(",")){let[n,o]=r.split("=");n&&o!==void 0&&(this.features[n]=o==="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(),r=t?.code;switch(r){case "PROJECT_NOT_REGISTERED":throw new M(t?.message||"Project not registered",r,this.config.projectId);case "PROJECT_INACTIVE":throw new M(t?.message||"Project is inactive",r,this.config.projectId);case "INVALID_PROJECT_ID":throw new M(t?.message||"Invalid project ID format",r,this.config.projectId);case "PROJECT_NOT_FOUND":throw new q("Project not found - no previous index exists");default:throw e.status===404?new q("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof M||t instanceof q?t:e.status===404?new q("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let r=new URLSearchParams({branch:e});t&&r.set("commit",t);let n=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${r.toString()}`;try{let o=await this.sendRequest(n,null,"GET");return !o||!o.ok?null:await o.json()}catch(o){if(o instanceof $)throw o;return null}}async claimAstLock(e,t,r,n){let o=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":r?"incremental":"full",...n&&{"x-commit-hash":n}});if(!o)throw new Error("Failed to claim indexing lock: no response");if(o.status===409)throw await this.parseIndexingConflict(o);if(o.status===401)throw new $("Authentication failed");if(!o.ok)throw new Error(`Failed to claim indexing lock: ${o.status}`);return await o.json()}async pollIndexStatus(e,t,r,n=300*1e3){let o=Date.now(),i=2e3,a=3e4;for(;Date.now()-o<n;){try{let l=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(r)}`,null,"GET");if(!l)continue;if(l.status===401)throw new $("Authentication failed during index status polling");if(l.status===403||l.status===404)return !1;if(l.ok){let d=await l.json();if(d.status==="current")return !0;if(d.status==="stale"||d.status==="failed")return !1}}catch(l){if(l instanceof $)throw l}await new Promise(l=>setTimeout(l,i)),i=Math.min(i*2,a);}return false}async uploadEnrichment(e,t,r,n){let o=[5e3,1e4,2e4];for(let i=0;i<=o.length;i++)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":r,"x-commit-hash":n},body:e,dispatcher:new Agent({headersTimeout:0,bodyTimeout:0})});if(a.status===401)throw new $("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(i<o.length){await new Promise(d=>setTimeout(d,o[i]));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 $)throw a;if(i<o.length){console.warn(`Enrichment upload network error (attempt ${i+1}/${o.length+1}): ${a instanceof Error?a.message:String(a)}`),await new Promise(l=>setTimeout(l,o[i]));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 r=Lr(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${r}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",r;try{let n=await e.json();t=n?.message||t,r=n?.details?.branchName;}catch{}return new ce(t,r)}async streamToApi(e,t,r,n,o,i,a){try{let{Readable:l}=await import('stream'),d=new We(e),g=l.toWeb(d),p=new Agent({headersTimeout:0,bodyTimeout:0}),u=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":r,"x-branch-name":n,"x-constellation-index":o?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...i&&{"x-commit-hash":i},...a&&{"x-attempt-id":a}},body:g,duplex:"half",dispatcher:p});if(!u.ok&&typeof d.destroy=="function"&&d.destroy(),u.status===401)throw new $("Authentication failed");if(u.status===409)throw await this.parseIndexingConflict(u);if(u.status===200)try{let h=await u.json();if(h?.status==="current")return console.log(`${w} Index already up to date for ${n} at commit ${h.commitHash||"unknown"}`),!0}catch{}if(u.ok||u.status===202)return !0;let f=`Server returned ${u.status}`;try{let h=await u.json();h?.message&&(f=Array.isArray(h.message)?h.message.join("; "):h.message);}catch{}throw new Error(f)}catch(l){if(l instanceof $||l instanceof ce)throw l;let d=l instanceof Error?l:new Error(String(l)),g="";if(d.message==="fetch failed"||l.code){let u=[],f=l.code||l.cause?.code;if(l.code&&u.push(`Error Code: ${l.code}`),l.cause){let h=l.cause;h.code&&u.push(`Cause Code: ${h.code}`),h.errno&&u.push(`Errno: ${h.errno}`),h.syscall&&u.push(`System Call: ${h.syscall}`),h.address&&u.push(`Address: ${h.address}`),h.port&&u.push(`Port: ${h.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",u.length>0&&(g+=` (${u.join(", ")})`);}else g=d.message;let p=new Error(`Failed to upload data to Constellation Service: ${g}`);throw p.cause=d,p.stack=`${p.stack}
4
- Caused by: ${d.stack}`,p}}async sendRequest(e,t,r,n={},o=0,i=3,a=1e3,l=250){for(let d=1;d<=i;d++){let g;try{let p=new AbortController;o>0&&(g=setTimeout(()=>p.abort(),o));let u={...n,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},f=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:r,headers:u,body:t?JSON.stringify(t):void 0,signal:p.signal});if(g&&clearTimeout(g),f.status===401)throw new $("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new Je(`${f.statusText} (${f.status})`);return f}catch(p){if(g&&clearTimeout(g),!(p instanceof $)){let u=p instanceof Error?`${p.message}${p.cause?` (Cause: ${p.cause})`:""}`:String(p);console.log(`HTTP request attempt ${d}/${i} failed: ${u}`);}if(d<i&&p instanceof Je){let u=a+Math.floor(Math.random()*l);await new Promise(f=>setTimeout(f,u));}else throw p}}}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},r=await this.sendRequest(e,void 0,"DELETE",t);if(r&&!r.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Je=class extends Error{constructor(e){super(e),this.name="RetryableError";}},$=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},q=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},M=class extends Error{constructor(t,r,n){super(t);this.code=r;this.projectId=n;this.name="ProjectValidationError";}},ce=class extends Error{constructor(t,r){super(t);this.branchName=r;this.name="IndexingInProgressError";}},X=class extends Error{constructor(t,r){super(t);this.errorCode=r;this.name="GitValidationError";}};});var N,Ke=m(()=>{N={prefix:{idle:c.blue("\u25C6"),done:c.green("\u2714")},style:{highlight:s=>c.blue(s),answer:s=>c.green(s),error:s=>c.red(`\u2716 ${s}`),help:s=>c.gray(s)},icon:{checked:c.green("\u25FC"),unchecked:c.gray("\u25FB"),cursor:c.blue("\u276F")}};});async function Ur(s){if(!s.startsWith("http://")&&!s.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await Nt("open",[s]),!0;case "linux":return await Nt("xdg-open",[s]),!0;case "win32":return await Nt("cmd",["/c","start","",s]),!0;default:return !1}}catch{return false}}var Nt,Br=m(()=>{Nt=promisify(execFile);});function Hr(){return new Promise((s,e)=>{let t=createServer(),r,n=false;t.listen(0,"127.0.0.1",()=>{let o=t.address();if(!o||typeof o=="string"){t.close(),e(new Error("Failed to bind callback server"));return}s({port:o.port,close(){r&&(clearTimeout(r),r=void 0),t.close(),t.closeAllConnections();},waitForCallback(i,a=3e5){return new Promise((l,d)=>{r=setTimeout(()=>{r=void 0,n=true,t.close(),t.closeAllConnections(),d(new Error("Authentication timed out"));},a),t.on("request",(g,p)=>{let u=new URL(g.url??"/",`http://127.0.0.1:${o.port}`);if(u.pathname!=="/callback"){p.writeHead(404,{"Content-Type":"text/plain"}),p.end("Not found");return}let f=u.searchParams.get("key");if(u.searchParams.get("state")!==i){p.writeHead(400,{"Content-Type":"text/plain"}),p.end("Invalid state parameter");return}if(!f||!Mo.test(f)){p.writeHead(400,{"Content-Type":"text/plain"}),p.end("Invalid key format");return}if(n)return;n=true;let _=u.searchParams.get("return_url");_?(p.writeHead(302,{Location:_}),p.end()):(p.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),p.end(Uo)),r&&(clearTimeout(r),r=void 0),t.close(),t.closeAllConnections(),l(f);});})}});}),t.on("error",o=>{e(o);});})}var Mo,Uo,Gr=m(()=>{Mo=/^ak:[0-9a-f]{32}$/i,Uo=`<!DOCTYPE html>
2
+ import {base32}from'@scure/base';import {Readable}from'stream';import p from'ansi-colors';import*as xe from'os';import xe__default from'os';import*as qt from'fs';import {readFileSync,existsSync}from'fs';import {pipeline}from'stream/promises';import*as ln from'zlib';import ln__default from'zlib';import {fetch as fetch$1,Agent}from'undici';import {execFile,execFileSync,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import {confirm,password,input,select,checkbox}from'@inquirer/prompts';import*as P from'path';import P__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as B from'fs/promises';import B__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import {z}from'zod';import Qs from'tree-sitter-javascript';import Zs from'tree-sitter-python';import ea from'tree-sitter-typescript';import Ka from'tree-sitter';import ei from'ignore';import {performance}from'perf_hooks';import {parseDocument,isMap,isSeq}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var ao=Object.defineProperty;var f=(i,e)=>()=>(i&&(e=i(i=0)),e);var Vn=(i,e)=>{for(var t in e)ao(i,t,{get:e[t],enumerable:true});};var et,Wt=f(()=>{et=["help","--help","-h","--version","-V","-v"];});function qn(i){return base32.encode(Buffer.from(i))}var Xn=f(()=>{});function Qn(i,e,t){let r=`${i}:${e}${t?`:${t}`:""}`;return qn(r)}var Zn=f(()=>{Xn();});var tt,er=f(()=>{tt=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let r=JSON.stringify(e)+`
3
+ `,o=Buffer.from(r,"utf8");if(!this.push(o))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),r=>t(e||r)):t(e);}};});function uo(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:xe.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 go,mo,fo,ho,yo,bo,vo,Co,_o,So,Ie,C,E,b,v,Q,D=f(()=>{go="\u2714",mo="\u2717",fo="\u26A0",ho="\u2139",yo="\u26A1",bo="[OK]",vo="[ERR]",Co="[WARN]",_o="[INFO]",So="[>>]",Ie=uo(),C=p.green(Ie?go:bo),E=p.red(Ie?mo:vo),b=p.yellow(Ie?fo:Co),v=p.blue(Ie?ho:_o),Q=p.yellow(Ie?yo:So);});var nt,rt,$,Z,U,de,ee,it=f(()=>{Zn();er();D();nt=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 r of t.split(",")){let[o,s]=r.split("=");o&&s!==void 0&&(this.features[o]=s==="true");}}async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),this.parseFeatureHeader(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),r=t?.code;switch(r){case "PROJECT_NOT_REGISTERED":throw new U(t?.message||"Project not registered",r,this.config.projectId);case "PROJECT_INACTIVE":throw new U(t?.message||"Project is inactive",r,this.config.projectId);case "INVALID_PROJECT_ID":throw new U(t?.message||"Invalid project ID format",r,this.config.projectId);case "PROJECT_NOT_FOUND":throw new Z("Project not found - no previous index exists");default:throw e.status===404?new Z("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof U||t instanceof Z?t:e.status===404?new Z("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let r=new URLSearchParams({branch:e});t&&r.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${r.toString()}`;try{let s=await this.sendRequest(o,null,"GET");return !s||!s.ok?null:await s.json()}catch(s){if(s instanceof $)throw s;return null}}async claimAstLock(e,t,r,o){let s=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":r?"incremental":"full",...o&&{"x-commit-hash":o}});if(!s)throw new Error("Failed to claim indexing lock: no response");if(s.status===409)throw await this.parseIndexingConflict(s);if(s.status===401)throw new $("Authentication failed");if(!s.ok)throw new Error(`Failed to claim indexing lock: ${s.status}`);return await s.json()}async pollIndexStatus(e,t,r,o=300*1e3){let s=Date.now(),a=2e3,l=3e4;for(;Date.now()-s<o;){try{let c=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(r)}`,null,"GET");if(!c)continue;if(c.status===401)throw new $("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let u=await c.json();if(u.status==="current")return !0;if(u.status==="stale"||u.status==="failed")return !1}}catch(c){if(c instanceof $)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadEnrichment(e,t,r,o){let s=[5e3,1e4,2e4];for(let a=0;a<=s.length;a++)try{let l=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":t,"x-branch-name":r,"x-commit-hash":o},body:e,dispatcher:new Agent({headersTimeout:0,bodyTimeout:0})});if(l.status===401)throw new $("Authentication failed during enrichment upload");if(l.status===409){if((await l.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return console.warn("Enrichment skipped: index state changed since AST upload"),!1;if(a<s.length){await new Promise(u=>setTimeout(u,s[a]));continue}return console.warn("Enrichment skipped: indexing still in progress after retries"),!1}return l.ok||l.status===202?!0:(console.warn(`Enrichment upload failed with status ${l.status}`),!1)}catch(l){if(l instanceof $)throw l;if(a<s.length){console.warn(`Enrichment upload network error (attempt ${a+1}/${s.length+1}): ${l instanceof Error?l.message:String(l)}`),await new Promise(c=>setTimeout(c,s[a]));continue}return console.warn(`Enrichment upload error: ${l instanceof Error?l.message:String(l)}`),false}return false}async deleteFiles(e){for(let t of e){let r=Qn(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${r}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",r;try{let o=await e.json();t=o?.message||t,r=o?.details?.branchName;}catch{}return new de(t,r)}async streamToApi(e,t,r,o,s,a,l){try{let{Readable:c}=await import('stream'),u=new tt(e),g=process.env.CAPTURE_PAYLOAD_PATH,d=null,m=c.toWeb(u);if(g){let[y,S]=m.tee(),x=qt.createWriteStream(g);d=pipeline(c.fromWeb(S),ln.createGzip(),x).catch(w=>{console.warn(`[constellation] capture tap failed: ${w instanceof Error?w.message:String(w)}`);}),m=y;}let h=new Agent({headersTimeout:0,bodyTimeout:0});try{let y=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":r,"x-branch-name":o,"x-constellation-index":s?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...a&&{"x-commit-hash":a},...l&&{"x-attempt-id":l}},body:m,duplex:"half",dispatcher:h});if(!y.ok&&typeof u.destroy=="function"&&u.destroy(),y.status===401)throw new $("Authentication failed");if(y.status===409)throw await this.parseIndexingConflict(y);if(y.status===200)try{let x=await y.json();if(x?.status==="current")return console.log(`${C} Index already up to date for ${o} at commit ${x.commitHash||"unknown"}`),!0}catch{}if(y.ok||y.status===202)return !0;let S=`Server returned ${y.status}`;try{let x=await y.json();x?.message&&(S=Array.isArray(x.message)?x.message.join("; "):x.message);}catch{}throw new Error(S)}finally{d&&await d;}}catch(c){if(c instanceof $||c instanceof de)throw c;let u=c instanceof Error?c:new Error(String(c)),g="";if(u.message==="fetch failed"||c.code){let m=[],h=c.code||c.cause?.code;if(c.code&&m.push(`Error Code: ${c.code}`),c.cause){let y=c.cause;y.code&&m.push(`Cause Code: ${y.code}`),y.errno&&m.push(`Errno: ${y.errno}`),y.syscall&&m.push(`System Call: ${y.syscall}`),y.address&&m.push(`Address: ${y.address}`),y.port&&m.push(`Port: ${y.port}`);}h==="ERR_INVALID_ARG_VALUE"?g="Invalid argument value - check stream/body format and duplex option":h==="ECONNREFUSED"?g="Connection refused - service may be down or unreachable":h==="ENOTFOUND"?g="DNS lookup failed - check service URL":h==="ETIMEDOUT"?g="Connection timeout - service not responding":h==="ECONNRESET"?g="Connection reset by server":h==="EHOSTUNREACH"?g="Host unreachable - check network connectivity":g="Network failure",m.length>0&&(g+=` (${m.join(", ")})`);}else g=u.message;let d=new Error(`Failed to upload data to Constellation Service: ${g}`);throw d.cause=u,d.stack=`${d.stack}
4
+ Caused by: ${u.stack}`,d}}async sendRequest(e,t,r,o={},s=0,a=3,l=1e3,c=250){for(let u=1;u<=a;u++){let g;try{let d=new AbortController;s>0&&(g=setTimeout(()=>d.abort(),s));let m={...o,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},h=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:r,headers:m,body:t?JSON.stringify(t):void 0,signal:d.signal});if(g&&clearTimeout(g),h.status===401)throw new $("Authentication failed");if(!h.ok&&this.retryableStatusCodes.includes(h.status))throw new rt(`${h.statusText} (${h.status})`);return h}catch(d){if(g&&clearTimeout(g),!(d instanceof $)){let m=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);console.log(`HTTP request attempt ${u}/${a} failed: ${m}`);}if(u<a&&d instanceof rt){let m=l+Math.floor(Math.random()*c);await new Promise(h=>setTimeout(h,m));}else throw d}}}async reportErrors(e){try{let t=await this.sendRequest("error-reports",e,"POST",{"x-project-id":this.config.projectId,"x-branch-name":this.config.branch},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},r=await this.sendRequest(e,void 0,"DELETE",t);if(r&&!r.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},rt=class extends Error{constructor(e){super(e),this.name="RetryableError";}},$=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},Z=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},U=class extends Error{constructor(t,r,o){super(t);this.code=r;this.projectId=o;this.name="ProjectValidationError";}},de=class extends Error{constructor(t,r){super(t);this.branchName=r;this.name="IndexingInProgressError";}},ee=class extends Error{constructor(t,r){super(t);this.errorCode=r;this.name="GitValidationError";}};});var A,ot=f(()=>{A={prefix:{idle:p.blue("\u25C6"),done:p.green("\u2714")},style:{highlight:i=>p.blue(i),answer:i=>p.green(i),error:i=>p.red(`\u2716 ${i}`),help:i=>p.gray(i)},icon:{checked:p.green("\u25FC"),unchecked:p.gray("\u25FB"),cursor:p.blue("\u276F")}};});async function sr(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await zt("open",[i]),!0;case "linux":return await zt("xdg-open",[i]),!0;case "win32":return await zt("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var zt,ar=f(()=>{zt=promisify(execFile);});function lr(){return new Promise((i,e)=>{let t=createServer(),r,o=false;t.listen(0,"127.0.0.1",()=>{let s=t.address();if(!s||typeof s=="string"){t.close(),e(new Error("Failed to bind callback server"));return}i({port:s.port,close(){r&&(clearTimeout(r),r=void 0),t.close(),t.closeAllConnections();},waitForCallback(a,l=3e5){return new Promise((c,u)=>{r=setTimeout(()=>{r=void 0,o=true,t.close(),t.closeAllConnections(),u(new Error("Authentication timed out"));},l),t.on("request",(g,d)=>{let m=new URL(g.url??"/",`http://127.0.0.1:${s.port}`);if(m.pathname!=="/callback"){d.writeHead(404,{"Content-Type":"text/plain"}),d.end("Not found");return}let h=m.searchParams.get("key");if(m.searchParams.get("state")!==a){d.writeHead(400,{"Content-Type":"text/plain"}),d.end("Invalid state parameter");return}if(!h||!Io.test(h)){d.writeHead(400,{"Content-Type":"text/plain"}),d.end("Invalid key format");return}if(o)return;o=true;let S=m.searchParams.get("return_url");S?(d.writeHead(302,{Location:S}),d.end()):(d.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),d.end(No)),r&&(clearTimeout(r),r=void 0),t.close(),t.closeAllConnections(),c(h);});})}});}),t.on("error",s=>{e(s);});})}var Io,No,cr=f(()=>{Io=/^ak:[0-9a-f]{32}$/i,No=`<!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 At(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 ${c.gray("'")} ${c.blueBright(".")} ${c.dim("`")} ${c.yellowBright("'")} ${c.blueBright("+")} ${c.whiteBright(".")} ${c.gray(".")} ${c.yellowBright("'")} ${c.yellowBright("*")} ${c.whiteBright("'")} ${c.blueBright("+")} ${c.gray(".")} ${c.yellowBright("*")} ${c.whiteBright(",")} ${c.gray.dim(".")}\u2502
8
- \u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
9
- \u2502 ${c.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${c.gray(".")} ${c.yellowBright("'")} ${c.gray("+")} ${c.gray("\\")} ${c.gray("`")} \u2502
10
- \u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${c.gray("'")} ${c.blueBright("o")}${c.gray("\u2014\u2014\u2014\u2014")}${c.yellowBright("o")} ${c.whiteBright("o")} ${c.whiteBright(".")} \u2502
11
- \u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${c.gray(".")} ${c.whiteBright("*")} ${c.gray(" \\ \\ ")}${c.gray("/")} \u2502
12
- \u2502 ${c.whiteBright("'")} ${c.blueBright(".")} ${c.gray("'")} ${c.whiteBright(".")} ${c.blueBright(".")} ${c.gray(".")} ${c.yellowBright("*")} ${c.blueBright.dim("+")} ${c.whiteBright("o o")}${c.gray("\u2014")}${c.blueBright("o")} ${c.yellowBright("*")} \u2502
13
- \u2502${c.yellowBright("'")} ${c.whiteBright("*")} ${c.blueBright("+")} ${c.yellowBright("*")} ${c.gray(",")} ${c.whiteBright("'")} + ${c.whiteBright("constellationdev.io")} ${c.whiteBright("' .")} ${c.gray(",")} ${c.blueBright("*")} ${c.yellowBright(".")} ${c.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 ${c.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 Q,Wr,Ye=m(()=>{`
6
+ <body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function Kt(i){console.log(`\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
7
+ \u2502 ${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`),i&&i.length>0?console.log(`\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u252C${"\u2500".repeat(59-i.length)}\u256F
14
+ \u2502 ${p.bold(`constellation \u203A ${i}`)} \u2502
15
+ \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u256F
16
+ `):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var te,pr,st=f(()=>{`
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 ${c.gray("'")} ${c.blueBright(".")} ${c.dim("`")} ${c.yellowBright("'")} ${c.blueBright("+")} ${c.whiteBright(".")} ${c.gray(".")} ${c.yellowBright("'")} ${c.yellowBright("*")} ${c.whiteBright("'")} ${c.blueBright("+")} ${c.gray(".")} ${c.yellowBright("*")} ${c.whiteBright(",")} ${c.gray.dim(".")}\u2502
19
- \u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
20
- \u2502 ${c.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${c.gray(".")} ${c.yellowBright("'")} ${c.gray("+")} ${c.gray("\\")} ${c.gray("`")} \u2502
21
- \u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${c.gray("'")} ${c.blueBright("o")}${c.gray("\u2014\u2014\u2014\u2014")}${c.yellowBright("o")} ${c.whiteBright("o")} ${c.whiteBright(".")} \u2502
22
- \u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${c.gray(".")} ${c.whiteBright("*")} ${c.gray(" \\ \\ ")}${c.gray("/")} \u2502
23
- \u2502 ${c.whiteBright("'")} ${c.blueBright(".")} ${c.gray("'")} ${c.whiteBright(".")} ${c.blueBright(".")} ${c.gray(".")} ${c.yellowBright("*")} ${c.blueBright.dim("+")} ${c.whiteBright("o o")}${c.gray("\u2014")}${c.blueBright("o")} ${c.yellowBright("*")} \u2502
24
- \u2502${c.yellowBright("'")} ${c.whiteBright("*")} ${c.blueBright("+")} ${c.yellowBright("*")} ${c.gray(",")} ${c.whiteBright("'")} + ${c.whiteBright("constellationdev.io")} ${c.whiteBright("' .")} ${c.gray(",")} ${c.blueBright("*")} ${c.yellowBright(".")} ${c.whiteBright("+")} \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
- ${c.yellowBright(" o")}
28
- ${c.gray(" \\")}
29
- ${c.blueBright(" o")}${c.blueBright("----")}${c.yellowBright("o")} ${c.gray("o")}
30
- ${c.gray(" \\ \\ ")}${c.blueBright("/")}
31
- ${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
32
- `,Q="CONSTELLATION_ACCESS_KEY",Wr="CONSTELLATION_WEB_URL";});var Z,qe=m(()=>{Z=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};});function zo(s){return Wo.test(s)}function Jo(s){return s.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Wo,Ee,zr=m(()=>{Ke();Br();Gr();Ye();D();qe();Wo=/^ak:[0-9a-f]{32}$/i;Ee=class extends Z{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${Y}Configuring access key authentication...
33
- `),this.env.isCI()){console.error(`${S} Cannot configure authentication in CI/CD environments
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
+ `,te="CONSTELLATION_ACCESS_KEY",pr="CONSTELLATION_WEB_URL";});var ne,at=f(()=>{ne=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};});function jo(i){return ko.test(i)}function Ao(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var ko,Ne,ur=f(()=>{ot();ar();cr();st();D();at();ko=/^ak:[0-9a-f]{32}$/i;Ne=class extends ne{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${Q}Configuring access key authentication...
33
+ `),this.env.isCI()){console.error(`${E} Cannot configure authentication in CI/CD environments
34
34
 
35
- The ${Q} environment variable must be configured
35
+ The ${te} 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,51 +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(Q)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:N})){console.log(`${w} Keeping existing Constellation access key`);return}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let r=t.message??"An unexpected error occurred",n=Jo(r);console.error(`${S} Failed to store Constellation access key
44
- ${n}`);}}async manualAuthFlow(){let e,t=0,r=3;for(;t<r;){if(e=(await password({message:"Constellation Access Key:",theme:N})).trim(),!e){console.log(`${C} Access key cannot be empty.
45
- `),t++;continue}if(!zo(e)){if(t++,t<r)console.log(`${C} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
43
+ `);return}if(await this.env.getKey(te)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:A})){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 r=t.message??"An unexpected error occurred",o=Ao(r);console.error(`${E} Failed to store Constellation access key
44
+ ${o}`);}}async manualAuthFlow(){let e,t=0,r=3;for(;t<r;){if(e=(await password({message:"Constellation Access Key:",theme:A})).trim(),!e){console.log(`${b} Access key cannot be empty.
45
+ `),t++;continue}if(!jo(e)){if(t++,t<r)console.log(`${b} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
46
46
  Attempts remaining: ${r-t}
47
- `);else {console.error(`${S} Invalid access key format after ${r} 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:r}=await Hr(),o=`${process.env[Wr]||"https://app.constellationdev.io"}/auth/cli?callback_port=${t}&state=${e}`;console.log(`${y} Opening browser for authentication...`),await Ur(o)||console.log(`${C} Could not open browser automatically.
47
+ `);else {console.error(`${E} Invalid access key format after ${r} 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:r}=await lr(),s=`${process.env[pr]||"https://app.constellationdev.io"}/auth/cli?callback_port=${t}&state=${e}`;console.log(`${v} Opening browser for authentication...`),await sr(s)||console.log(`${b} Could not open browser automatically.
49
49
  Please open this URL manually:
50
50
 
51
- ${o}
52
- `),console.log(`${y} Waiting for authentication... (press Ctrl+C to cancel)
53
- `);try{let a=await r(e);await this.storeKey(a);}catch{console.error(`${S} Authentication timed out.
54
- Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(Q,e),console.log(`${w} Stored access key in ${Q} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${y} To activate in this session, run:
51
+ ${s}
52
+ `),console.log(`${v} Waiting for authentication... (press Ctrl+C to cancel)
53
+ `);try{let l=await r(e);await this.storeKey(l);}catch{console.error(`${E} Authentication timed out.
54
+ Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(te,e),console.log(`${C} Stored access key in ${te} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${v} To activate in this session, run:
55
55
 
56
56
  source ${t}
57
57
 
58
- New terminal sessions will load it automatically.`);}};});function Jr(s){return s.replace(/\\/g,"/")}function Xe(s){return Jr(s).replace(/^\.?\//,"")}function O(s,e){return Jr(b.relative(s,e))}var ne=m(()=>{});var Ko,Yo,Qe,qo,Vr,Kr,Ze,Yr=m(()=>{D();ne();Ko={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}},Yo={hover:true,definition:true,references:true,callHierarchy:false},Qe=1e4,qo=300*1e3,Vr=50,Kr={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},Ze=class{constructor(e){this.projectRoot=e;}async enrich(e,t,r){let n=[],o=Date.now(),i={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 d=r.get(a);if(!d)continue;let g=0,p=l.length;for(let u of l){if(Date.now()-o>qo)return console.log(`${y} Enrichment timeout reached. Uploading partial results.`),this.logDiagnostics(i),n;let f=t.get(u)||[];if(f.length===0){let _=b.resolve(this.projectRoot,u),I=pathToFileURL(_).href,P;try{P=Ot.readFileSync(_,"utf-8");}catch(E){i.filesUnreadable++,i.firstFileError||(i.firstFileError=`${u}: ${E instanceof Error?E.message:String(E)}`);continue}try{d.sendNotification("textDocument/didOpen",{textDocument:{uri:I,languageId:this.getLanguageId(u),version:1,text:P}});}catch(E){i.filesOpenFailed++,i.firstOpenError||(i.firstOpenError=`${u}: ${E instanceof Error?E.message:String(E)}`);continue}if(f=await this.discoverSymbols(d,u,i),f.length===0){i.filesNoSymbols++;try{d.sendNotification("textDocument/didClose",{textDocument:{uri:I}});}catch{}continue}let j=await this.enrichFile(d,u,f,i,P);if(j.length>0&&n.push({filePath:u,language:a,symbols:j}),g++,g%Vr===0){let E=Math.round(g/p*100);console.log(`${y} ${Kr[a]??a} index enrichment: ${E}% (${g}/${p} files)`);}continue}let h=await this.enrichFile(d,u,f,i);if(h.length>0&&n.push({filePath:u,language:a,symbols:h}),g++,g%Vr===0){let _=Math.round(g/p*100);console.log(`${y} ${Kr[a]??a} index enrichment: ${_}% (${g}/${p} files)`);}}}return this.logDiagnostics(i),n}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(`${C} Enrichment issues: ${t.join(", ")}`),e.firstFileError&&console.log(`${C} First file read error: ${e.firstFileError}`),e.firstOpenError&&console.log(`${C} First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&console.log(`${C} First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&console.log(`${C} First symbol query error: ${e.firstSymbolError}`));}async enrichFile(e,t,r,n,o){let i=b.resolve(this.projectRoot,t),a=pathToFileURL(i).href;if(!(o!==void 0)){let g;try{g=Ot.readFileSync(i,"utf-8");}catch(p){return n.filesUnreadable++,n.firstFileError||(n.firstFileError=`${t}: ${p instanceof Error?p.message:String(p)}`),[]}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(t),version:1,text:g}});}catch(p){return n.filesOpenFailed++,n.firstOpenError||(n.firstOpenError=`${t}: ${p instanceof Error?p.message:String(p)}`),[]}}let d=[];for(let g of r)try{let p=await this.querySymbol(e,a,g,n);p&&d.push(p);}catch(p){n.symbolQueryErrors++,n.firstSymbolError||(n.firstSymbolError=`${g.name} in ${t}: ${p instanceof Error?p.message:String(p)}`);}try{e.sendNotification("textDocument/didClose",{textDocument:{uri:a}});}catch{}return d}async querySymbol(e,t,r,n){let o=Ko[r.kind.toLowerCase()]||Yo,i={line:r.line-1,character:r.column},a={textDocument:{uri:t},position:i},l={name:r.name,line:r.line,column:r.column,kind:r.kind},d=false,[g,p,u]=await Promise.allSettled([o.hover?e.sendRequest("textDocument/hover",a,Qe):null,o.definition?e.sendRequest("textDocument/definition",a,Qe):null,o.references?e.sendRequest("textDocument/references",{...a,context:{includeDeclaration:false}},Qe):null]);for(let f of [g,p,u])f.status==="rejected"&&n.queryRejections++;if(g.status==="fulfilled"&&g.value?.contents){let f=g.value,h=typeof f.contents=="string"?f.contents:f.contents.value||"";h&&(l.typeInfo={resolvedType:h},d=true);}if(p.status==="fulfilled"&&p.value){let f=p.value,h=Array.isArray(f)?f[0]:f;if(h?.uri||h?.targetUri){let _=h.targetUri||h.uri,I=h.targetRange||h.range,P=this.uriToPath(_),j=O(this.projectRoot,P),E=j.startsWith("..");l.definition={filePath:j,line:(I?.start?.line??0)+1,column:I?.start?.character??0,isExternal:E},d=true;}}if(u.status==="fulfilled"&&u.value){let f=u.value;if(f.length>0){let h=f.slice(0,100).map(_=>({filePath:O(this.projectRoot,this.uriToPath(_.uri||"")),line:(_.range?.start?.line??0)+1,column:_.range?.start?.character??0}));l.references={count:f.length,locations:h},d=true;}}if(o.callHierarchy)try{let f=await e.sendRequest("textDocument/prepareCallHierarchy",a,Qe);if(f&&f.length>0){let h=f[0],[_,I]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:h}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:h}).catch(()=>[])]),P=(_||[]).slice(0,200).map(E=>({name:E.from?.name||"",filePath:O(this.projectRoot,this.uriToPath(E.from?.uri||"")),line:(E.from?.range?.start?.line??0)+1,column:E.from?.selectionRange?.start?.character??E.from?.range?.start?.character??0})),j=(I||[]).slice(0,200).map(E=>({name:E.to?.name||"",filePath:O(this.projectRoot,this.uriToPath(E.to?.uri||"")),line:(E.to?.range?.start?.line??0)+1,column:E.to?.selectionRange?.start?.character??E.to?.range?.start?.character??0}));(P.length>0||j.length>0)&&(l.callHierarchy={incomingCalls:P,outgoingCalls:j},d=!0);}}catch{n.queryRejections++;}return d?l:null}async discoverSymbols(e,t,r){let n=b.resolve(this.projectRoot,t),o=pathToFileURL(n).href;try{let i=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:o}});return !i||!Array.isArray(i)?[]:this.flattenDocumentSymbols(i)}catch(i){return r.discoveryErrors++,r.firstDiscoveryError||(r.firstDiscoveryError=`${t}: ${i instanceof Error?i.message:String(i)}`),[]}}flattenDocumentSymbols(e){let t=[],r={1:"file",2:"module",3:"namespace",4:"package",5:"class",6:"method",7:"property",8:"field",9:"constructor",10:"enum",11:"interface",12:"function",13:"variable",14:"constant",15:"string",16:"number",17:"boolean",18:"array",19:"object",20:"key",21:"null",22:"enumMember",23:"struct",24:"event",25:"operator",26:"typeParameter"};for(let n of e){let o=r[n.kind]||"variable",i=n.selectionRange||n.range||n.location?.range;i&&t.push({name:n.name,line:(i.start?.line??0)+1,column:i.start?.character??0,kind:o}),n.children&&Array.isArray(n.children)&&t.push(...this.flattenDocumentSymbols(n.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=b.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function qr(s){return s.map(e=>JSON.stringify(e)).join(`
58
+ New terminal sessions will load it automatically.`);}};});function dr(i){return i.replace(/\\/g,"/")}function lt(i){return dr(i).replace(/^\.?\//,"")}function M(i,e){return dr(P.relative(i,e))}var ae=f(()=>{});var Fo,Oo,Yt,Do,gr,mr,ct,fr=f(()=>{D();ae();Fo={function:{hover:true,references:true,callHierarchy:true},method:{hover:true,references:true,callHierarchy:true},class:{hover:false,references:true,callHierarchy:false},interface:{hover:false,references:true,callHierarchy:false},variable:{hover:true,references:true,callHierarchy:false},property:{hover:true,references:true,callHierarchy:false},import:{hover:true,references:false,callHierarchy:false}},Oo={hover:true,references:true,callHierarchy:false},Yt=1e4,Do=300*1e3,gr=50,mr={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},ct=class{constructor(e){this.projectRoot=e;}async enrich(e,t,r){let o=[],s=Date.now(),a={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null};for(let[l,c]of e){let u=r.get(l);if(!u)continue;let g=0,d=c.length;for(let m of c){if(Date.now()-s>Do)return console.log(`${v} Enrichment timeout reached. Uploading partial results.`),this.logDiagnostics(a),o;let h=t.get(m)||[];if(h.length===0){let S=P.resolve(this.projectRoot,m),x=pathToFileURL(S).href,w;try{w=qt.readFileSync(S,"utf-8");}catch(L){a.filesUnreadable++,a.firstFileError||(a.firstFileError=`${m}: ${L instanceof Error?L.message:String(L)}`);continue}try{u.sendNotification("textDocument/didOpen",{textDocument:{uri:x,languageId:this.getLanguageId(m),version:1,text:w}});}catch(L){a.filesOpenFailed++,a.firstOpenError||(a.firstOpenError=`${m}: ${L instanceof Error?L.message:String(L)}`);continue}if(h=await this.discoverSymbols(u,m,a),h.length===0){a.filesNoSymbols++;try{u.sendNotification("textDocument/didClose",{textDocument:{uri:x}});}catch{}continue}let R=await this.enrichFile(u,m,h,a,w);if(R.length>0&&o.push({filePath:m,language:l,symbols:R}),g++,g%gr===0){let L=Math.round(g/d*100);console.log(`${v} ${mr[l]??l} index enrichment: ${L}% (${g}/${d} files)`);}continue}let y=await this.enrichFile(u,m,h,a);if(y.length>0&&o.push({filePath:m,language:l,symbols:y}),g++,g%gr===0){let S=Math.round(g/d*100);console.log(`${v} ${mr[l]??l} index enrichment: ${S}% (${g}/${d} files)`);}}}return this.logDiagnostics(a),o}logDiagnostics(e){let t=[];e.filesUnreadable>0&&t.push(`${e.filesUnreadable} files unreadable`),e.filesOpenFailed>0&&t.push(`${e.filesOpenFailed} files failed to open in language server`),e.discoveryErrors>0&&t.push(`${e.discoveryErrors} symbol discovery failures`),e.symbolQueryErrors>0&&t.push(`${e.symbolQueryErrors} symbol query failures`),e.queryRejections>0&&t.push(`${e.queryRejections} individual LSP query rejections`);let r=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(r.length>0){let o=r.reduce((a,[,l])=>a+l,0),s=r.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(console.log(`${b} Enrichment issues: ${t.join(", ")}`),e.firstFileError&&console.log(`${b} First file read error: ${e.firstFileError}`),e.firstOpenError&&console.log(`${b} First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&console.log(`${b} First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&console.log(`${b} First symbol query error: ${e.firstSymbolError}`));}async enrichFile(e,t,r,o,s){let a=P.resolve(this.projectRoot,t),l=pathToFileURL(a).href;if(!(s!==void 0)){let g;try{g=qt.readFileSync(a,"utf-8");}catch(d){return o.filesUnreadable++,o.firstFileError||(o.firstFileError=`${t}: ${d instanceof Error?d.message:String(d)}`),[]}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:l,languageId:this.getLanguageId(t),version:1,text:g}});}catch(d){return o.filesOpenFailed++,o.firstOpenError||(o.firstOpenError=`${t}: ${d instanceof Error?d.message:String(d)}`),[]}}let u=[];for(let g of r)try{let d=await this.querySymbol(e,l,g,o);d&&u.push(d);}catch(d){o.symbolQueryErrors++,o.firstSymbolError||(o.firstSymbolError=`${g.name} in ${t}: ${d instanceof Error?d.message:String(d)}`);}try{e.sendNotification("textDocument/didClose",{textDocument:{uri:l}});}catch{}return u}async querySymbol(e,t,r,o){let s=Fo[r.kind.toLowerCase()]||Oo,a={line:r.line-1,character:r.column},l={textDocument:{uri:t},position:a},c={name:r.name,line:r.line,column:r.column,kind:r.kind},u=false,[g,d]=await Promise.allSettled([s.hover?e.sendRequest("textDocument/hover",l,Yt):null,s.references?e.sendRequest("textDocument/references",{...l,context:{includeDeclaration:false}},Yt):null]);for(let m of [g,d])m.status==="rejected"&&o.queryRejections++;if(g.status==="fulfilled"&&g.value?.contents){let m=g.value,h=typeof m.contents=="string"?m.contents:m.contents.value||"";h&&(c.typeInfo={resolvedType:h},u=true);}if(d.status==="fulfilled"&&d.value){let m=d.value;if(m.length>0){let h=m.slice(0,100).map(y=>({filePath:M(this.projectRoot,this.uriToPath(y.uri||"")),line:(y.range?.start?.line??0)+1,column:y.range?.start?.character??0}));c.references={count:m.length,locations:h},u=true;}}if(s.callHierarchy)try{let m=await e.sendRequest("textDocument/prepareCallHierarchy",l,Yt);if(m&&m.length>0){let h=m[0],[y,S]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:h}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:h}).catch(()=>[])]),x=(y||[]).slice(0,200).map(R=>({name:R.from?.name||"",filePath:M(this.projectRoot,this.uriToPath(R.from?.uri||"")),line:(R.from?.range?.start?.line??0)+1,column:R.from?.selectionRange?.start?.character??R.from?.range?.start?.character??0})),w=(S||[]).slice(0,200).map(R=>({name:R.to?.name||"",filePath:M(this.projectRoot,this.uriToPath(R.to?.uri||"")),line:(R.to?.range?.start?.line??0)+1,column:R.to?.selectionRange?.start?.character??R.to?.range?.start?.character??0}));(x.length>0||w.length>0)&&(c.callHierarchy={incomingCalls:x,outgoingCalls:w},u=!0);}}catch{o.queryRejections++;}if(!u){let m=r.kind.toLowerCase();o.symbolsWithNoEnrichment[m]=(o.symbolsWithNoEnrichment[m]??0)+1;}return u?c:null}async discoverSymbols(e,t,r){let o=P.resolve(this.projectRoot,t),s=pathToFileURL(o).href;try{let a=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:s}});return !a||!Array.isArray(a)?[]:this.flattenDocumentSymbols(a)}catch(a){return r.discoveryErrors++,r.firstDiscoveryError||(r.firstDiscoveryError=`${t}: ${a instanceof Error?a.message:String(a)}`),[]}}flattenDocumentSymbols(e){let t=[],r={1:"file",2:"module",3:"namespace",4:"package",5:"class",6:"method",7:"property",8:"field",9:"constructor",10:"enum",11:"interface",12:"function",13:"variable",14:"constant",15:"string",16:"number",17:"boolean",18:"array",19:"object",20:"key",21:"null",22:"enumMember",23:"struct",24:"event",25:"operator",26:"typeParameter"};for(let o of e){let s=r[o.kind]||"variable",a=o.selectionRange||o.range||o.location?.range;a&&t.push({name:o.name,line:(a.start?.line??0)+1,column:a.start?.character??0,kind:s}),o.children&&Array.isArray(o.children)&&t.push(...this.flattenDocumentSymbols(o.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=P.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function hr(i){return i.map(e=>JSON.stringify(e)).join(`
59
59
  `)+`
60
- `}var Xr=m(()=>{});function et(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 U__default.stat(s)).isDirectory()}catch{return false}},async fileIsReadable(s){try{return await U__default.access(s,U__default.constants.R_OK),!0}catch{return false}},async readFile(s,e="utf-8"){let t=await U__default.readFile(s,{encoding:e,flag:U__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(s,e,t="utf-8"){let r=Buffer.from(e,t);await U__default.writeFile(s,r,{encoding:t,flag:U__default.constants.O_WRONLY|U__default.constants.O_CREAT|U__default.constants.O_TRUNC});},async getFileStats(s){return await U__default.stat(s)},async getFileHandle(s,e,t){return await U__default.open(s,e,t)}};});var tt,Qr=m(()=>{tt=class s{constructor(e,t,r=1e4){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=r;this.stdout.on("data",n=>this.handleData(n)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
60
+ `}var yr=f(()=>{});function pt(i){try{return execFileSync(process.platform==="win32"?"where":"which",[i],{stdio:"ignore"}),!0}catch{return false}}var _,K=f(()=>{_={async directoryExists(i){try{return (await B__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await B__default.access(i,B__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await B__default.readFile(i,{encoding:e,flag:B__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let r=Buffer.from(e,t);await B__default.writeFile(i,r,{encoding:t,flag:B__default.constants.O_WRONLY|B__default.constants.O_CREAT|B__default.constants.O_TRUNC});},async getFileStats(i){return await B__default.stat(i)},async getFileHandle(i,e,t){return await B__default.open(i,e,t)}};});var ut,br=f(()=>{ut=class i{constructor(e,t,r=1e4){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=r;this.stdout.on("data",o=>this.handleData(o)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
61
61
  \r
62
- `);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,r){if(this.disposed)return Promise.reject(new Error("LspClient disposed"));let n=this.nextId++,o={jsonrpc:"2.0",id:n,method:e,...t!==void 0&&{params:t}};return new Promise((i,a)=>{let l=setTimeout(()=>{this.pendingRequests.delete(n),a(new Error(`LSP request '${e}' timed out after ${r??this.defaultTimeoutMs}ms`));},r??this.defaultTimeoutMs);this.pendingRequests.set(n,{resolve:i,reject:a,timer:l}),this.writeMessage(o);})}sendNotification(e,t){if(this.disposed)return;let r={jsonrpc:"2.0",method:e,...t!==void 0&&{params:t}};this.writeMessage(r);}dispose(){this.disposed=true;for(let[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("LspClient disposed"));this.pendingRequests.clear(),this.stdout.removeAllListeners("data");}writeMessage(e){let t=JSON.stringify(e),n=`Content-Length: ${Buffer.byteLength(t,"utf-8")}\r
62
+ `);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,r){if(this.disposed)return Promise.reject(new Error("LspClient disposed"));let o=this.nextId++,s={jsonrpc:"2.0",id:o,method:e,...t!==void 0&&{params:t}};return new Promise((a,l)=>{let c=setTimeout(()=>{this.pendingRequests.delete(o),l(new Error(`LSP request '${e}' timed out after ${r??this.defaultTimeoutMs}ms`));},r??this.defaultTimeoutMs);this.pendingRequests.set(o,{resolve:a,reject:l,timer:c}),this.writeMessage(s);})}sendNotification(e,t){if(this.disposed)return;let r={jsonrpc:"2.0",method:e,...t!==void 0&&{params:t}};this.writeMessage(r);}dispose(){this.disposed=true;for(let[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("LspClient disposed"));this.pendingRequests.clear(),this.stdout.removeAllListeners("data");}writeMessage(e){let t=JSON.stringify(e),o=`Content-Length: ${Buffer.byteLength(t,"utf-8")}\r
63
63
  \r
64
- `;this.stdin.write(n+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(s.HEADER_SEPARATOR);if(t===-1)break;let n=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!n){this.buffer=this.buffer.subarray(t+4);continue}let o=parseInt(n[1],10),i=t+4;if(this.buffer.length-i<o)break;let a=this.buffer.subarray(i,i+o).toString("utf-8");this.buffer=this.buffer.subarray(i+o);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 Dt,rt,ge,nt=m(()=>{Dt=b.join(Ce.homedir(),".constellation","lsp-servers"),rt=b.join(Dt,"node_modules",".bin"),ge=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 ti,ot,tn=m(()=>{z();Qr();nt();ti={log:s=>console.log(s),warn:s=>console.warn(s),error:s=>console.error(s)},ot=class{constructor(e,t){this.projectRoot=e;this.logger=t??ti;}servers=new Map;unavailable=new Set;nextId=1;logger;async startServer(e,t){if(t===false||this.unavailable.has(e))return null;let r=this.servers.get(e);if(r)return this.toConnection(r);let n=this.resolveCommand(e,t);if(!n)return this.unavailable.add(e),null;let{command:o,args:i}=n;try{let a=spawn(o,i,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((p,u)=>{a.once("spawn",p),a.once("error",u);}),a.stderr?.on("data",p=>{let u=p.toString().trim();u.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${u}`);});let l=new tt(a.stdin,a.stdout,12e4),d=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 g={language:e,process:a,client:l};return this.servers.set(e,g),a.on("exit",p=>{let u=this.servers.get(e);u&&(u.client.dispose(),this.servers.delete(e)),p!==0&&p!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${p}`);}),this.toConnection(g)}catch(a){this.unavailable.add(e);let l=`[LSP:${e}] Failed to start: ${a instanceof Error?a.message:String(a)}`,d=a?.code;return d==="ENOENT"||d==="EACCES"?this.logger.warn(l):this.logger.error(l),null}}async shutdown(e){let t=this.servers.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(r=>{let n=setTimeout(()=>{t.process.kill("SIGKILL"),r();},3e3);t.process.on("exit",()=>{clearTimeout(n),r();});});}catch(r){this.logger.warn(`[LSP:${e}] Graceful shutdown failed, force killing: ${r instanceof Error?r.message:String(r)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.servers.delete(e);}}async shutdownAll(){let e=[...this.servers.keys()];await Promise.allSettled(e.map(t=>this.shutdown(t)));}destroyAll(){for(let e of this.servers.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.servers.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let r=ge.get(e);if(!r)return null;let n=b.join(rt,r.command);return existsSync(n)?{command:n,args:r.args}:et(r.command)?{command:r.command,args:r.args}:null}toConnection(e){let t=`lsp-${e.language}-${this.nextId++}`;return {language:e.language,process:e.process,id:t,sendRequest:(r,n,o)=>e.client.sendRequest(r,n,o),sendNotification:(r,n)=>e.client.sendNotification(r,n)}}};});var ee,it=m(()=>{ee=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var de,Mt=m(()=>{D();de=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:r=>r==="node_modules"||r===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:r=>r==="node_modules"||r===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${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"),r=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let n=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,n),n}if(r){if(this.isJavaScriptEnabled)try{let n=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,n),n}catch(n){if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}throw n}if(this.isTypeScriptEnabled){let n=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,n),n}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let r=await find(e,{root:this.projectRoot,configName:t});return !r||this.failedConfigFiles.has(r)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let r=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(r&&!this.failedConfigFiles.has(r)){this.failedConfigFiles.add(r);let n=t instanceof Error?t.message:String(t);console.warn(`${C} Failed to parse ${r}: ${n}`),console.warn(`${C} Path alias resolution will be skipped for files using this config`);}else r||console.warn(`${C} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var st,nn=m(()=>{ne();st=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let r=await this.loadFromTsConfig();Object.assign(e,r),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,r]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let n=e.substring(t.length+1),o=await this.resolveSubPath(r,n);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,r=this.tsconfigResult.tsconfigFile?b.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[n,o]of Object.entries(t)){if(n.includes("*")||!Array.isArray(o))continue;let i=o[0];if(!i)continue;let a=b.resolve(r,i),l=await this.findEntryPoint(a);l&&(e[n]=l);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=b.join(this.projectRoot,"package.json"),r=await U.readFile(t,"utf-8"),o=JSON.parse(r).workspaces;if(!o)return e;let i=Array.isArray(o)?o:o.packages||[];for(let a of i){let l=await this.findWorkspaceDirs(a);for(let d of l){let g=await this.loadWorkspacePackage(d);g&&Object.assign(e,g);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let r=e.slice(0,-2),n=b.join(this.projectRoot,r);try{let o=await U.readdir(n,{withFileTypes:!0});for(let i of o)i.isDirectory()&&t.push(b.join(n,i.name));}catch{}}else {let r=b.join(this.projectRoot,e);try{(await U.stat(r)).isDirectory()&&t.push(r);}catch{}}return t}async loadWorkspacePackage(e){try{let t=b.join(e,"package.json"),r=await U.readFile(t,"utf-8"),n=JSON.parse(r),o=n.name;if(!o)return null;let i=await this.findPackageEntryPoint(e,n);return i?{[o]:i}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let n=t.exports;if(typeof n=="string")return b.join(e,n);if(typeof n=="object"){let o=n["."]||n["./index"];if(typeof o=="string")return b.join(e,o);if(typeof o=="object"){let i=o.import||o.default||o.require;if(i)return b.join(e,i)}}}if(t.main)return b.join(e,t.main);let r=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let n of r){let o=b.join(e,n);try{if((await U.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 r of t){let n=b.join(e,r);try{if((await U.stat(n)).isFile())return n}catch{}}try{if((await U.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let r=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?b.dirname(e):b.dirname(e),n=[b.join(r,t+".ts"),b.join(r,t+".tsx"),b.join(r,t+".js"),b.join(r,t+".jsx"),b.join(r,t+".d.ts"),b.join(r,t,"index.ts"),b.join(r,t,"index.tsx"),b.join(r,t,"index.js"),b.join(r,t,"index.jsx")];for(let o of n)try{if((await U.stat(o)).isFile())return o}catch{}return null}toProjectRelative(e){let t=O(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var ue,Ut=m(()=>{ne();nn();ue=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=b.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new st(this.projectRoot,t);let r=e.toLowerCase(),n=r.endsWith(".ts")||r.endsWith(".tsx")||r.endsWith(".d.ts"),o=r.endsWith(".js")||r.endsWith(".jsx")||r.endsWith(".mjs")||r.endsWith(".cjs");if(n?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=b.dirname(t.tsconfigFile);let i=t.tsconfig?.compilerOptions;i&&(i.baseUrl&&(this.baseUrl=b.resolve(this.tsconfigDir,i.baseUrl)),i.paths&&typeof i.paths=="object"&&(this.paths=i.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let r=b.resolve(this.sourceDir,e),n=await this.findFileWithExtensions(r);return n?this.toProjectRelative(n):e}if(e.startsWith("#")){let r=await this.resolveWithPackageImports(e);return r?this.toProjectRelative(r):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let r=await this.resolveWithPaths(e);if(r)return this.toProjectRelative(r)}if(this.baseUrl){let r=await this.resolveWithBaseUrl(e);if(r)return this.toProjectRelative(r)}return e}toProjectRelative(e){let t=O(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,r]of Object.entries(this.paths)){let n=this.matchPathPattern(e,t);if(n!==null)for(let o of r){let i=await this.trySubstitution(e,t,o,n);if(i)return i}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[r,n]=t.split("*");if(!e.startsWith(r)||n&&!e.endsWith(n))return null;let o=r.length,i=n?e.length-n.length:e.length;return e.substring(o,i)}async trySubstitution(e,t,r,n){let o=r.replaceAll("*",n),i=b.resolve(this.tsconfigDir,o);return await this.findFileWithExtensions(i)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=b.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(i=>e.endsWith(i));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let r=[".js",".jsx",".mjs",".cjs"],n=r.some(i=>e.endsWith(i)),o=e;if(n&&!t){for(let i of r)if(e.endsWith(i)){o=e.slice(0,-i.length);break}}if(!t)for(let i of this.extensions){let a=o+i;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let i of this.extensions){let a=b.join(o,`index${i}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await U.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await U.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let r=b.join(t,"package.json");try{if((await U.stat(r)).isFile())return r}catch{}let n=b.dirname(t);if(n===t)break;t=n;}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 U.readFile(e,"utf-8"),r=JSON.parse(t);this.packageJsonDir=b.dirname(e),r.imports&&typeof r.imports=="object"&&(this.packageImports=r.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,r]of Object.entries(this.packageImports)){let n=this.matchPathPattern(e,t);if(n!==null){if(typeof r=="string"){let o=await this.tryPackageImportSubstitution(r,n);if(o)return o}if(Array.isArray(r)){for(let o of r)if(typeof o=="string"){let i=await this.tryPackageImportSubstitution(o,n);if(i)return i}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let r=e.replaceAll("*",t),n=b.resolve(this.packageJsonDir,r);return await this.findFileWithExtensions(n)}};});var at,on=m(()=>{it();Mt();Ut();at=class extends ee{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new de(e,t)}getImportResolver(e,t){return new ue(e,t)}};});var lt,sn=m(()=>{it();Mt();Ut();lt=class extends ee{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new de(e,t)}getImportResolver(e,t){return new ue(e,t)}};});async function te(s,e,t,r,n){let o=await t.resolve(s),i=an(s,o),a=n(s,o,i),l=i?void 0:Xe(o);r[e.toString()]={source:s,resolvedPath:l,isExternal:i,importType:a};}function an(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var Bt,Se=m(()=>{ne();Bt=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function si(s,e,t,r){let n=s.childForFieldName("name");if(!n)return;let o;if(n.type==="aliased_import"){let i=n.childForFieldName("name");o=i?i.text:n.text;}else o=n.text;await te(o,s.startPosition.row,e,t,r);}async function ai(s,e,t,r){let n,o=s.childForFieldName("module_name");if(o)n=o.text;else {let i="";for(let a=0;a<s.childCount;a++){let l=s.child(a);if(l){if(l.type==="relative_import"){i=l.text;break}(l.type==="."||l.type==="import_prefix")&&(i+=l.text);}}n=i||".";}await te(n,s.startPosition.row,e,t,r);}async function li(s,e,t,r){await te("__future__",s.startPosition.row,e,t,r);}function Ht(){return {language:"python",handlers:new Map([["import_statement",si],["import_from_statement",ai],["future_import_statement",li]]),classifyImportType:ii}}var ii,ct=m(()=>{Se();ii=(s,e,t)=>{if(t)return "external";if(/^\.+/.test(s))return "relative";let r=s.split(".")[0];return PYTHON_STDLIB_MODULES.has(r)?"builtin":"alias"};});var pt,cn=m(()=>{ct();pt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=b.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 r=e.replace(/\./g,"/"),n=await this.tryResolveFile(b.resolve(this.projectRoot,r));return n?b.relative(this.projectRoot,n).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let r=e.slice(t),n=t<=1?"":"../".repeat(t-1),o=r?n+r.replace(/\./g,"/"):n.slice(0,-1)||".",i=b.resolve(this.sourceDir,o),a=await this.tryResolveFile(i);return a?b.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,b.join(e,"__init__.py"),b.join(e,"__init__.pyi")];for(let r of t)try{return await Ot.promises.access(r,Ot.constants.F_OK),r}catch{continue}return null}};});var dt,pn=m(()=>{it();cn();dt=class extends ee{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new pt(e,process.cwd())}};});function Pe(s){return di[s]??s.charAt(0).toUpperCase()+s.slice(1)}var di,be,ut,ft=m(()=>{on();sn();pn();di={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"};be={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"]},ut=class{constructor(e){this.config=e;this.registerPlugin(new at),this.registerPlugin(new lt),this.registerPlugin(new dt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>ci,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??be.javascript};typescript={language:()=>gi.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??be.typescript};python={language:()=>pi,fileExtensions:()=>this.config?.languages.python?.fileExtensions??be.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});var mt,un=m(()=>{z();mt=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let r=this.langRegistry[t]?.language;if(!r)throw new Error(`Unsupported language: ${t}`);let n=await r();if(!n)throw new Error(`Failed to load language: ${t}`);let o=new ui;o.setLanguage(n);let i=await v.getFileStats(e),a=10*1024*1024;if(i.size<=a){let l=await v.readFile(e),d={bufferSize:1024*1024};return o.parse(l,void 0,d)}else return this.parseWithStream(o,e,i.size)}async parseWithStream(e,t,r){let n=null;try{n=await U.open(t,"r");let o=n.fd,i=64*1024,a=Buffer.alloc(i),l=0;return e.parse(g=>{if(r>50*1024*1024){let u=Math.round(g/r*100);u>l+10&&(console.log(` Parsing large file: ${u}%...`),l=u);}let p=Ot.readSync(o,a,0,i,g);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(o){if(n)try{await n.close();}catch(i){console.error(`Warning: Failed to close file handle for ${t}:`,i);}throw o}finally{if(n)try{await n.close();}catch{}}}};});var ht,mn=m(()=>{z();ne();D();ht=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=fn();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 r=[],n=null;t.exclude&&t.exclude.length>0&&(n=fn().add(t.exclude));let o=await U__default.realpath(this.rootPath);for(let i of e)try{let a=b__default.isAbsolute(i)?i:b__default.join(this.rootPath,i),l=await U__default.lstat(a);if(l.isSymbolicLink()){let d=await U__default.realpath(a);if(!d.startsWith(o+b__default.sep)&&d!==o){console.warn(`${C} Skipping symlink pointing outside project: ${i} -> ${d}`);continue}let g=await U__default.stat(a);if(!g.isFile())continue;let p=O(this.rootPath,a);if(n&&n.ignores(p))continue;let u=this.detectLanguage(p,t.languages);if(!u)continue;r.push({path:a,relativePath:p,language:u,size:g.size});}else if(l.isFile()){let d=O(this.rootPath,a);if(n&&n.ignores(d))continue;let g=this.detectLanguage(d,t.languages);if(!g)continue;r.push({path:a,relativePath:d,language:g,size:l.size});}}catch{console.warn(`${C} Skipping inaccessible file: ${i}`);}return r}async loadGitignoreRules(e,t){let r=[],n=t;for(;;){let o=b__default.join(n,".gitignore");await v.fileIsReadable(o)&&r.unshift(o);let i=b__default.dirname(n);if(i===n)break;n=i;let a=b__default.join(n,".git");if(await v.directoryExists(a)){let l=b__default.join(n,".gitignore");await v.fileIsReadable(l)&&!r.includes(l)&&r.unshift(l);break}}for(let o of r)try{let i=await v.readFile(o);e.add(i);}catch{console.warn(`${C} Failed to load .gitignore: ${o}`);}e.add(".git");}async walkDirectory(e,t,r,n){let o=[],i=t||e,a=r||await U__default.realpath(this.rootPath),l=n||new Set([a]);try{let d=await U__default.readdir(e,{withFileTypes:!0});for(let g of d){let p=b__default.join(e,g.name),u=O(i,p);if(g.isDirectory()){if(g.name.startsWith("."))continue;let f=await this.walkDirectory(p,i,a,l);o.push(...f);}else if(g.isFile()){let f=await U__default.stat(p);o.push({path:p,relativePath:u,language:"",size:f.size});}else if(g.isSymbolicLink())try{let f=await U__default.realpath(p);if(!f.startsWith(a+b__default.sep)&&f!==a){console.warn(`${C} Skipping symlink pointing outside project: ${p} -> ${f}`);continue}let h=await U__default.stat(p);if(h.isDirectory()){if(g.name.startsWith(".")||l.has(f))continue;l.add(f);let _=await this.walkDirectory(p,i,a,l);o.push(..._);}else h.isFile()&&o.push({path:p,relativePath:u,language:"",size:h.size});}catch{console.warn(`${C} Skipping invalid symlink: ${p}`);}}}catch(d){console.error(`${S} Error walking directory ${e}:`,d);}return o}matchesLanguageExtension(e,t){let r=b__default.extname(e.path).toLowerCase();for(let[n,o]of Object.entries(t))if(o.fileExtensions.includes(r))return e.language=n,true;return false}detectLanguage(e,t){let r=b__default.extname(e).toLowerCase();for(let[n,o]of Object.entries(t))if(o.fileExtensions.includes(r))return n;return null}};});var fi,mi,hn,yn=m(()=>{fi=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"])}),mi=z$1.record(z$1.string(),fi),hn=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:mi.optional()});});var yi,yt,vn=m(()=>{yi=promisify(Gt.gunzip),yt=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],r=Gt.createGzip();r.on("data",i=>t.push(i));let n=new Promise((i,a)=>{r.on("end",i),r.on("error",a);}),o=Readable.from(e);return await pipeline(o,r),await n,Buffer.concat(t).toString("base64")}async compress(e){let t=[],r=Gt.createGzip();r.on("data",i=>t.push(i));let n=new Promise((i,a)=>{r.on("end",i),r.on("error",a);}),o=Readable.from(this.serializeASTChunks(e));return await pipeline(o,r),await n,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),r=await yi(t);return JSON.parse(r.toString("utf-8"))}};});var Wt,Ct=m(()=>{Wt=new Set(["ACCESS_KEY_MISSING","AUTH_FAILURE","PROJECT_NOT_REGISTERED","PROJECT_INACTIVE","INVALID_PROJECT_ID","DIRTY_WORKTREE","CONCURRENT_INDEXING","GIT_SYNC_FAILURE","BRANCH_NOT_CONFIGURED","ENRICHMENT_FAILED"]);});function zt(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 xe,_n=m(()=>{Ct();xe=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(zt).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:c.unstyle(e.map(zt).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:c.unstyle(e.map(zt).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||!Wt.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!Wt.has(e.code)))}capture(e,t,r){this.entries.push({level:e,message:c.unstyle(t),timestamp:new Date().toISOString(),code:r});let n=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?n.call(console,t):console[e==="info"?"log":e](t);}};});var vt,En=m(()=>{vt=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let r=new Map,n=0,o=0;for(;o<e.length&&r.size<this.concurrency;){let i=n++,a=this.processItem(e[o],o,t).then(l=>({result:l!==null?l.result:null,promiseId:i}));r.set(i,a),o++;}for(;r.size>0;){let i=await Promise.race(r.values());if(r.delete(i.promiseId),i.result!==null&&(yield i.result),o<e.length){let a=n++,l=this.processItem(e[o],o,t).then(d=>({result:d!==null?d.result:null,promiseId:a}));r.set(a,l),o++;}}}async processItem(e,t,r){try{return {result:await r(e,t),index:t}}catch{return null}}};});async function Ci(s,e,t,r){let n=s.childForFieldName("source");if(!n)return;let o=n.startPosition.row,i=n.text.replace(/['"]/g,"");await te(i,o,e,t,r);}async function wi(s,e,t,r){let n=s.childForFieldName("source");if(!n)return;let o=n.startPosition.row,i=n.text.replace(/['"]/g,"");await te(i,o,e,t,r);}function _t(){return {language:"javascript",handlers:new Map([["import_statement",Ci],["export_statement",wi]])}}function Jt(){return {..._t(),language:"typescript"}}var Vt=m(()=>{Se();});var Sn,bn=m(()=>{Vt();ct();Se();Vt();ct();Sn=[_t(),Jt(),Ht()];});var Pn={};Tr(Pn,{ImportExtractor:()=>Kt});var Kt,xn=m(()=>{bn();Se();Kt=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Sn)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,r,n){if(!n)return {};let o=this.languageHandlers.get(r);if(!o)return {};let i=this.classifiers.get(r)??Bt,a={};return await this.walkAST(e.rootNode,async l=>{let d=o.get(l.type);d&&await d(l,n,a,i);}),a}async walkAST(e,t){await t(e);for(let r=0;r<e.childCount;r++){let n=e.child(r);n&&await this.walkAST(n,t);}}};});var Ie,In,Yt,Rn,$n,Et=m(()=>{Ie=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"]),In=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"]),Yt={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"]},Rn={language:"javascript",textIncludedTypes:In,fieldNames:Yt},$n={language:"typescript",textIncludedTypes:In,fieldNames:Yt};});var vi,Tn,kn,qt=m(()=>{vi=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"]),Tn={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"]},kn={language:"python",textIncludedTypes:vi,fieldNames:Tn,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function Nn(s){return Re.get(s)}function An(s){if(!s)return Ie;let e=Re.get(s);if(!e)return Ie;let t=new Set(Ie);for(let r of e.textIncludedTypes)t.add(r);return t}function Xt(s){if(!s){let t=Array.from(Re.values()).map(r=>r.fieldNames);return $e(...t)}let e=Re.get(s);if(!e){let t=Array.from(Re.values()).map(r=>r.fieldNames);return $e(...t)}return e.fieldNames}var Re,Ln=m(()=>{Qt();Et();qt();Et();Et();qt();Re=new Map([["javascript",Rn],["typescript",$n],["python",kn]]);});var Mn={};Tr(Mn,{COMMON_FIELD_NAMES:()=>tr,JS_TS_FIELD_NAMES:()=>Fn,PYTHON_FIELD_NAMES:()=>Dn,TEXT_INCLUDED_TYPES:()=>jn,mergeFieldMaps:()=>$e,serializeAST:()=>Ei,serializeASTStream:()=>_i});function*_i(s,e,t){yield*er(s,e,t);}function*er(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)}`),On(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let n=(t?Xt(t):tr)[s.type]||[],o=new Set,i=true;for(let a of n){let l=s.childForFieldName(a);l&&(i||(yield ","),i=false,o.add(l),yield*er(l,a,t));}for(let a=0;a<s.childCount;a++){let l=s.child(a);l&&!o.has(l)&&(i||(yield ","),i=false,yield*er(l,void 0,t));}yield "]";}yield "}";}async function Ei(s,e,t){let r=Zt(s,e,t),n=t?Xt(t):tr,o=[{treeNode:s,serializedNode:r,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;o.length>0;){let i=o[o.length-1];if(i.childIndex===0&&i.treeNode.childCount>0){let a=n[i.treeNode.type]||[];for(let l of a){let d=i.treeNode.childForFieldName(l);if(d){i.fieldChildren.add(d);let g=Zt(d,l,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(g),o.push({treeNode:d,serializedNode:g,fieldName:l,childIndex:0,fieldChildren:new Set});}}}if(i.childIndex<i.treeNode.childCount){let a=i.treeNode.child(i.childIndex);if(i.childIndex++,a&&!i.fieldChildren.has(a)){let l=Zt(a,void 0,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(l),o.push({treeNode:a,serializedNode:l,childIndex:0,fieldChildren:new Set});}}else o.pop();}return r}function Zt(s,e,t){let r={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 On(s,t)&&(r.text=s.text),r}function On(s,e){if(e){let r=Nn(e);if(r?.shouldIncludeText){let o=r.shouldIncludeText(s);if(o===false)return false;if(o===true)return true}return An(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:jn.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function $e(...s){let e={};for(let t of s)for(let[r,n]of Object.entries(t)){let i=[...e[r]||[]];for(let a of n)i.includes(a)||i.push(a);e[r]=i;}return e}var jn,Fn,Dn,tr,Qt=m(()=>{Ln();jn=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"]);Fn={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},Dn={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"]};tr=$e(Fn,Dn);});var Te,Bn=m(()=>{Ve();Yr();Xr();tn();nt();ft();un();mn();yn();vn();Ye();Ct();_n();ne();En();D();qe();Te=class extends Z{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;logCollector=new xe;discoveredFiles=[];constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new ht(process.cwd()),this.parser=new mt(this.langRegistry),this.compressor=new yt;for(let t of Object.keys(this.config.languages)){let r=this.langRegistry.getPlugin(t);if(r?.getBuildConfigManager){let n=r.getBuildConfigManager(process.cwd(),this.config.languages);n&&this.buildConfigManagers.set(t,n);}}}async run(e=false,t=false,r=false){this.logCollector=new xe,this.logCollector.start();let n="failed";try{let o=await this.getAccessKey();this.apiClient=new ze(this.config,o),await this.validateProject(),this.logCollector.log(`${Y}Starting indexing procedure...
65
- `);let i=performance.now();if(t?this.logCollector.log(`${C} Skipping git branch validation`):await this.validateGitBranch(),t?this.logCollector.log(`${C} Skipping git status validation`):await this.validateGitStatus(),t?this.logCollector.log(`${C} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){this.logCollector.log(`${y} Discovering language build configurations...`);let R=0;for(let[,k]of this.buildConfigManagers.entries()){let ae=await k.initialize();R+=ae.length;}R>0&&this.logCollector.log(`${w} Found ${R} configuration file(s)`);}let a=await this.determineIndexScope(e),l=await this.git.getLatestCommitHash();if(a.upToDate){this.logCollector.log(`
66
- ${w} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${l.substring(0,8)}`),n="succeeded";return}let d=await this.apiClient.claimAstLock(this.config.projectId,this.config.branch,a.isIncremental,l);if(d.status==="current"){this.logCollector.log(`${w} Index already up to date for branch ${this.config.branch} at commit ${l?.substring(0,8)||"unknown"}`),n="succeeded";return}if(d.status==="processing"){this.logIndexingInProgress(this.config.branch),n="succeeded";return}let g=!1,p=()=>{g||this.logCollector.log(`${y} Uploading metadata, processing, and indexing...`);},u,f,h=new Promise((R,k)=>{u=R,f=k;}),_=new AbortController,I=this.createIndexPipeline(a.isIncremental,p,u),P=null;try{let[,R]=await Promise.all([this.uploadToAPI(I,a.isIncremental,l,d.attemptId).then(k=>(g=!0,k)).catch(k=>{throw _.abort(k),f(k),g=!0,k}),h.then(k=>{let ae=this.getEnrichmentEligibleLanguages(r,k);return ae?this.runLspEnrichment(k,ae,_.signal).catch(le=>(_.signal.aborted||this.logCollector.warn(`${C} Index enrichment failed: ${le instanceof Error?le.message:String(le)}`,{code:"ENRICHMENT_FAILED"}),null)):null}).catch(()=>null)]);P=R;}catch(R){throw g=!0,R}if(P&&P.length>0)try{let le=this.discoveredFiles.length,$r=Math.min(12e4+le*1e3,9e5);if(this.logCollector.log(`${y} Waiting for server to finish syntax tree processing (${le} files, timeout ${Math.round($r/1e3)}s)...`),await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,l,$r)){this.logCollector.log(`${y} Uploading enrichment data (${P.length} files)...`);let vo=qr(P);await this.apiClient.uploadEnrichment(vo,this.config.projectId,this.config.branch,l)?this.logCollector.log(`${w} Enrichment data uploaded to Constellation Service, index enhancement in progress`):this.logCollector.log(`${C} Enrichment upload skipped (index state changed)`);}else this.logCollector.log(`${C} AST processing did not complete in time, enrichment skipped`);}catch(R){this.logCollector.warn(`${C} Enrichment upload failed: ${R instanceof Error?R.message:String(R)}`,{code:"ENRICHMENT_FAILED"});}let x=(performance.now()-i)/1e3,A=Math.floor(x/60),T=(x%60).toFixed(3),K=A>0?`${A}m ${T}s`:`${T}s`;this.logCollector.log(`
67
- ${w} Upload completed in ${K}! Server indexing in progress.`),n="succeeded";}catch(o){if(o instanceof M)throw o;if(o instanceof ce){this.logIndexingInProgress(o.branchName||this.config?.branch),n="succeeded";return}if(o instanceof $)throw this.logCollector.error(`
68
- ${S} Authentication failed.`,{code:"AUTH_FAILURE"}),this.logCollector.log(`${y} Your access key may be invalid or expired. Run 'constellation auth'
69
- to set or update your access key.`),o;if(o instanceof X)throw this.logCollector.error(`${S} Indexing failed: ${o.message}`,{code:o.errorCode}),o;if(o instanceof Error&&o.message==="Access key not configured")throw o;let i=o instanceof Error?o.message:"An unexpected error occurred";throw this.logCollector.error(`${S} Indexing failed: ${i}`),o}finally{this.logCollector.stop();try{let i=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",a=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,l=this.logCollector.getReportableErrors();if(!i&&a&&l.length>0){let d=this.logCollector.getEntries(),g=l.map(P=>({type:"CLI_ERROR",message:P.message,phase:"indexing"})).slice(0,100),p=d.filter(P=>P.level==="warn").map(P=>({type:"CLI_WARNING",message:P.message,phase:"indexing"})).slice(0,100),u=g.length,f=p.length,h=[];u>0&&h.push(`${u} error${u!==1?"s":""}`),f>0&&h.push(`${f} warning${f!==1?"s":""}`);let _=h.join(", "),I=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:_,errorData:{errors:g,warnings:p},logEntries:d.slice(0,1e3),cliVersion:I,outcome:n,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(Q);if(!e)throw this.logCollector.error(`
70
- ${S} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),this.logCollector.log(`${y} Set the ${Q} environment variable or run
71
- 'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){this.logCollector.log(`${y} Validating project access...`);try{await this.apiClient.getProjectState(),this.logCollector.log(`${w} Project validated successfully`);}catch(e){if(e instanceof M)throw this.displayProjectValidationError(e),e;if(e instanceof q){this.logCollector.log(`${w} Project validated (first index)`);return}if(e instanceof $)throw e;let t=e instanceof Error?e.message:String(e);throw t==="fetch failed"||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("ETIMEDOUT")||t.includes("EHOSTUNREACH")||t.includes("ECONNRESET")?new Error(`Unable to connect to the Constellation service.
64
+ `;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(i.HEADER_SEPARATOR);if(t===-1)break;let o=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!o){this.buffer=this.buffer.subarray(t+4);continue}let s=parseInt(o[1],10),a=t+4;if(this.buffer.length-a<s)break;let l=this.buffer.subarray(a,a+s).toString("utf-8");this.buffer=this.buffer.subarray(a+s);try{let c=JSON.parse(l);this.handleResponse(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,console.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var Qt,dt,me,gt=f(()=>{Qt=P.join(xe.homedir(),".constellation","lsp-servers"),dt=P.join(Qt,"node_modules",".bin"),me=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});var Go,mt,_r=f(()=>{K();br();gt();Go={log:i=>console.log(i),warn:i=>console.warn(i),error:i=>console.error(i)},mt=class{constructor(e,t){this.projectRoot=e;this.logger=t??Go;}servers=new Map;unavailable=new Set;nextId=1;logger;async startServer(e,t){if(t===false||this.unavailable.has(e))return null;let r=this.servers.get(e);if(r)return this.toConnection(r);let o=this.resolveCommand(e,t);if(!o)return this.unavailable.add(e),null;let{command:s,args:a}=o;try{let l=spawn(s,a,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((d,m)=>{l.once("spawn",d),l.once("error",m);}),l.stderr?.on("data",d=>{let m=d.toString().trim();m.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${m}`);});let c=new ut(l.stdin,l.stdout,12e4),u=await c.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);c.sendNotification("initialized",{});let g={language:e,process:l,client:c};return this.servers.set(e,g),l.on("exit",d=>{let m=this.servers.get(e);m&&(m.client.dispose(),this.servers.delete(e)),d!==0&&d!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${d}`);}),this.toConnection(g)}catch(l){this.unavailable.add(e);let c=`[LSP:${e}] Failed to start: ${l instanceof Error?l.message:String(l)}`,u=l?.code;return u==="ENOENT"||u==="EACCES"?this.logger.warn(c):this.logger.error(c),null}}async shutdown(e){let t=this.servers.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(r=>{let o=setTimeout(()=>{t.process.kill("SIGKILL"),r();},3e3);t.process.on("exit",()=>{clearTimeout(o),r();});});}catch(r){this.logger.warn(`[LSP:${e}] Graceful shutdown failed, force killing: ${r instanceof Error?r.message:String(r)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.servers.delete(e);}}async shutdownAll(){let e=[...this.servers.keys()];await Promise.allSettled(e.map(t=>this.shutdown(t)));}destroyAll(){for(let e of this.servers.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.servers.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let r=me.get(e);if(!r)return null;let o=P.join(dt,r.command);return existsSync(o)?{command:o,args:r.args}:pt(r.command)?{command:r.command,args:r.args}:null}toConnection(e){let t=`lsp-${e.language}-${this.nextId++}`;return {language:e.language,process:e.process,id:t,sendRequest:(r,o,s)=>e.client.sendRequest(r,o,s),sendNotification:(r,o)=>e.client.sendNotification(r,o)}}};});var re,ft=f(()=>{re=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var fe,Zt=f(()=>{D();fe=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:r=>r==="node_modules"||r===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:r=>r==="node_modules"||r===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${b} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),r=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}if(r){if(this.isJavaScriptEnabled)try{let o=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let s=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,s),s}throw o}if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let r=await find(e,{root:this.projectRoot,configName:t});return !r||this.failedConfigFiles.has(r)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let r=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(r&&!this.failedConfigFiles.has(r)){this.failedConfigFiles.add(r);let o=t instanceof Error?t.message:String(t);console.warn(`${b} Failed to parse ${r}: ${o}`),console.warn(`${b} Path alias resolution will be skipped for files using this config`);}else r||console.warn(`${b} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var ht,wr=f(()=>{ae();ht=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let r=await this.loadFromTsConfig();Object.assign(e,r),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,r]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),s=await this.resolveSubPath(r,o);if(s)return this.toProjectRelative(s)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,r=this.tsconfigResult.tsconfigFile?P.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,s]of Object.entries(t)){if(o.includes("*")||!Array.isArray(s))continue;let a=s[0];if(!a)continue;let l=P.resolve(r,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=P.join(this.projectRoot,"package.json"),r=await B.readFile(t,"utf-8"),s=JSON.parse(r).workspaces;if(!s)return e;let a=Array.isArray(s)?s:s.packages||[];for(let l of a){let c=await this.findWorkspaceDirs(l);for(let u of c){let g=await this.loadWorkspacePackage(u);g&&Object.assign(e,g);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let r=e.slice(0,-2),o=P.join(this.projectRoot,r);try{let s=await B.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(P.join(o,a.name));}catch{}}else {let r=P.join(this.projectRoot,e);try{(await B.stat(r)).isDirectory()&&t.push(r);}catch{}}return t}async loadWorkspacePackage(e){try{let t=P.join(e,"package.json"),r=await B.readFile(t,"utf-8"),o=JSON.parse(r),s=o.name;if(!s)return null;let a=await this.findPackageEntryPoint(e,o);return a?{[s]:a}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return P.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return P.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return P.join(e,a)}}}if(t.main)return P.join(e,t.main);let r=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let o of r){let s=P.join(e,o);try{if((await B.stat(s)).isFile())return s}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let r of t){let o=P.join(e,r);try{if((await B.stat(o)).isFile())return o}catch{}}try{if((await B.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let r=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?P.dirname(e):P.dirname(e),o=[P.join(r,t+".ts"),P.join(r,t+".tsx"),P.join(r,t+".js"),P.join(r,t+".jsx"),P.join(r,t+".d.ts"),P.join(r,t,"index.ts"),P.join(r,t,"index.tsx"),P.join(r,t,"index.js"),P.join(r,t,"index.jsx")];for(let s of o)try{if((await B.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=M(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var he,en=f(()=>{ae();wr();he=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=P.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new ht(this.projectRoot,t);let r=e.toLowerCase(),o=r.endsWith(".ts")||r.endsWith(".tsx")||r.endsWith(".d.ts"),s=r.endsWith(".js")||r.endsWith(".jsx")||r.endsWith(".mjs")||r.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:s?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=P.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=P.resolve(this.tsconfigDir,a.baseUrl)),a.paths&&typeof a.paths=="object"&&(this.paths=a.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let r=P.resolve(this.sourceDir,e),o=await this.findFileWithExtensions(r);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let r=await this.resolveWithPackageImports(e);return r?this.toProjectRelative(r):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let r=await this.resolveWithPaths(e);if(r)return this.toProjectRelative(r)}if(this.baseUrl){let r=await this.resolveWithBaseUrl(e);if(r)return this.toProjectRelative(r)}return e}toProjectRelative(e){let t=M(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,r]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let s of r){let a=await this.trySubstitution(e,t,s,o);if(a)return a}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[r,o]=t.split("*");if(!e.startsWith(r)||o&&!e.endsWith(o))return null;let s=r.length,a=o?e.length-o.length:e.length;return e.substring(s,a)}async trySubstitution(e,t,r,o){let s=r.replaceAll("*",o),a=P.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=P.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(a=>e.endsWith(a));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let r=[".js",".jsx",".mjs",".cjs"],o=r.some(a=>e.endsWith(a)),s=e;if(o&&!t){for(let a of r)if(e.endsWith(a)){s=e.slice(0,-a.length);break}}if(!t)for(let a of this.extensions){let l=s+a;if(await this.fileExists(l))return await this.resolveSymlink(l)}for(let a of this.extensions){let l=P.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await B.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await B.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let r=P.join(t,"package.json");try{if((await B.stat(r)).isFile())return r}catch{}let o=P.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await B.readFile(e,"utf-8"),r=JSON.parse(t);this.packageJsonDir=P.dirname(e),r.imports&&typeof r.imports=="object"&&(this.packageImports=r.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,r]of Object.entries(this.packageImports)){let o=this.matchPathPattern(e,t);if(o!==null){if(typeof r=="string"){let s=await this.tryPackageImportSubstitution(r,o);if(s)return s}if(Array.isArray(r)){for(let s of r)if(typeof s=="string"){let a=await this.tryPackageImportSubstitution(s,o);if(a)return a}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let r=e.replaceAll("*",t),o=P.resolve(this.packageJsonDir,r);return await this.findFileWithExtensions(o)}};});var yt,xr=f(()=>{ft();Zt();en();yt=class extends re{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new fe(e,t)}getImportResolver(e,t){return new he(e,t)}};});var bt,Er=f(()=>{ft();Zt();en();bt=class extends re{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new fe(e,t)}getImportResolver(e,t){return new he(e,t)}};});var Ko,Y,Re,Jo,ye,Te,Vo,Yo,qo,$e,Xo,Qo,Zo,es,ts,ns,rs,is,os,ss,as,ls,cs,ps,us,ds,gs,Pr,ms,fs,hs,ys,bs,vs,Cs,_s,Ss,ws,xs,Es,Ps,Is,Ns,Rs,Nr,Ts,$s,tn,ks,js,As,Ls,Rr,Ir,Fs,Os,Ds,Ms,Us,Bs,Hs,Gs,Tr,$r,kr,jr,Ws,zs,Ks,Ar,Lr,vt=f(()=>{Ko=z.object({total:z.number().int().nonnegative(),returned:z.number().int().nonnegative(),hasMore:z.boolean(),nextOffset:z.number().int().nonnegative().optional(),currentOffset:z.number().int().nonnegative().optional()}),z.object({overall:z.number().min(0).max(1),factors:z.object({dataFreshness:z.number().min(0).max(1).optional(),coverageComplete:z.number().min(0).max(1).optional(),heuristicAccuracy:z.number().min(0).max(1).optional(),semanticAnalysisDepth:z.number().min(0).max(1).optional(),patternMatchQuality:z.number().min(0).max(1).optional()}).optional(),warnings:z.array(z.string()).optional(),recommendations:z.array(z.string()).optional()}),z.object({qualityScore:z.number().min(0).max(100).optional(),lastUpdated:z.string().optional(),cached:z.boolean().optional(),executionTime:z.number().nonnegative().optional(),coveragePercentage:z.number().min(0).max(100).optional(),issues:z.array(z.string()).optional()}),Y=z.object({language:z.string(),features:z.array(z.string()).optional(),visibility:z.string().optional(),decorators:z.array(z.string()).optional(),typeInfo:z.any().optional(),custom:z.record(z.string(),z.any()).optional()}),z.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),Re=z.enum(["low","medium","high","critical"]),Jo=z.enum(["low","moderate","high","very_high"]),ye=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:Jo}),Te=z.object({filePath:z.string(),line:z.number().int().positive().optional(),lineStart:z.number().int().positive().optional(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional()}),Te.extend({symbolId:z.string().optional(),symbolName:z.string().optional(),symbolKind:z.string().optional()}),z.object({outgoing:z.array(z.string()),incoming:z.array(z.string())}),Vo=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),Yo=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),qo=z.object({nodes:z.array(Vo),edges:z.array(Yo),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),$e=new Set(["abc","aifc","argparse","array","ast","asynchat","asyncio","asyncore","atexit","audioop","base64","bdb","binascii","bisect","builtins","bz2","cProfile","calendar","cgi","cgitb","chunk","cmath","cmd","code","codecs","codeop","collections","colorsys","compileall","concurrent","configparser","contextlib","contextvars","copy","copyreg","crypt","csv","ctypes","curses","dataclasses","datetime","dbm","decimal","difflib","dis","distutils","doctest","email","encodings","ensurepip","enum","errno","faulthandler","fcntl","filecmp","fileinput","fnmatch","fractions","ftplib","functools","gc","getopt","getpass","gettext","glob","graphlib","grp","gzip","hashlib","heapq","hmac","html","http","idlelib","imaplib","imghdr","imp","importlib","inspect","io","ipaddress","itertools","json","keyword","lib2to3","linecache","locale","logging","lzma","mailbox","mailcap","marshal","math","mimetypes","mmap","modulefinder","msilib","msvcrt","multiprocessing","netrc","nis","nntplib","numbers","operator","optparse","os","ossaudiodev","pathlib","pdb","pickle","pickletools","pipes","pkgutil","platform","plistlib","poplib","posix","posixpath","pprint","profile","pstats","pty","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","readline","reprlib","resource","rlcompleter","runpy","sched","secrets","select","selectors","shelve","shlex","shutil","signal","site","sitecustomize","smtpd","smtplib","sndhdr","socket","socketserver","spwd","sqlite3","ssl","stat","statistics","string","stringprep","struct","subprocess","sunau","symtable","sys","sysconfig","syslog","tabnanny","tarfile","telnetlib","tempfile","termios","test","textwrap","threading","time","timeit","tkinter","token","tokenize","tomllib","trace","traceback","tracemalloc","tty","turtle","turtledemo","types","typing","unicodedata","unittest","urllib","usercustomize","uu","uuid","venv","warnings","wave","weakref","webbrowser","winreg","winsound","wsgiref","xdrlib","xml","xmlrpc","zipapp","zipfile","zipimport","zlib","zoneinfo","_thread","_tkinter","__future__","__main__"]),z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.any().optional()})}),z.object({query:z.string().max(200),filterByKind:z.array(z.string()).optional(),filterByVisibility:z.array(z.string()).optional(),isExported:z.boolean().optional(),filterByFile:z.string().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeUsageCount:z.boolean().optional(),includeDocumentation:z.boolean().optional()}).refine(i=>i.query.length>0||i.filterByKind&&i.filterByKind.length>0||i.filterByVisibility&&i.filterByVisibility.length>0||i.isExported!==void 0||i.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),Xo=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),isExported:z.boolean(),usageCount:z.number().int().nonnegative().optional(),complexity:ye.optional(),languageMetadata:Y.optional()}),z.object({symbols:z.array(Xo),pagination:Ko.optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeReferences:z.boolean().optional(),includeRelationships:z.boolean().optional(),includeImpactScore:z.boolean().optional()}),Qo=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),modifiers:z.array(z.string()).optional(),typeInfo:z.any().optional(),decorators:z.array(z.string()).optional(),isExported:z.boolean(),isDeprecated:z.boolean(),complexity:ye.optional(),languageMetadata:Y.optional()}),Zo=Te.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),es=z.object({calls:z.array(z.string()),calledBy:z.array(z.string()),inheritsFrom:z.array(z.string()),inheritedBy:z.array(z.string()),children:z.array(z.string())}),ts=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Re}),z.object({symbol:Qo,references:z.array(Zo).optional(),relationships:es.optional(),impactScore:ts.optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includePackages:z.boolean().optional(),includeSymbols:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),ns=z.object({type:z.enum(["file","module"]),filePath:z.string().nullable(),moduleName:z.string().nullable().optional(),importedSymbols:z.array(z.string()).optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),rs=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),is=z.object({name:z.string(),version:z.string().optional(),type:z.string()}),z.object({totalFiles:z.number().int().nonnegative(),totalPackages:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()}),z.object({file:z.string(),directDependencies:z.array(ns),transitiveDependencies:z.array(rs).optional(),packages:z.array(is).optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includeSymbols:z.boolean().optional(),includeImpactMetrics:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),os=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),ss=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),z.object({totalFiles:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative(),riskLevel:Re}),z.object({file:z.string(),directDependents:z.array(os),transitiveDependents:z.array(ss).optional(),detailedMetrics:z.object({byDepth:z.record(z.string(),z.number()),criticalPaths:z.array(z.array(z.string())),mostImpactedFiles:z.array(z.string())}).optional()}),z.object({filePath:z.string().min(1).optional(),minCycleLength:z.number().int().min(2).max(10).optional(),maxCycleLength:z.number().int().min(2).max(10).optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeImpactScore:z.boolean().optional(),includeConfidence:z.boolean().optional()}),as=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Re}),z.object({cycles:z.array(as)}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),filterByUsageType:z.array(z.string()).optional(),filterByRelationshipType:z.array(z.string()).optional(),includeTransitive:z.boolean().optional(),includeContext:z.boolean().optional(),excludeTests:z.boolean().optional(),excludeGenerated:z.boolean().optional(),includeImportanceWeight:z.boolean().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0)}),ls=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:ye.optional(),languageMetadata:Y.optional()}),cs=z.object({filePath:z.string(),usageType:z.string(),relationshipType:z.string(),line:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional(),enclosingSymbol:z.object({name:z.string(),kind:z.string()}).optional(),context:z.string().optional(),aliasName:z.string().optional(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),importanceWeight:z.number().min(0).max(1).optional()}),ps=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:ls,directUsages:z.array(cs),transitiveUsages:z.array(ps).optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:z.enum(["callers","callees","both"]).default("both"),depth:z.number().int().positive().max(10).default(3),excludeExternal:z.boolean().optional(),includeGraph:z.boolean().optional(),limit:z.number().int().positive().max(100).default(25),offset:z.number().int().nonnegative().default(0)}),us=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),complexity:ye.optional(),languageMetadata:Y.optional()}),ds=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),depth:z.number().int().nonnegative(),complexity:ye.optional(),languageMetadata:Y.optional()}),gs=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isAsync:z.boolean(),depth:z.number().int().nonnegative(),complexity:ye.optional(),languageMetadata:Y.optional()}),z.object({root:us,callers:z.array(ds).optional(),callees:z.array(gs).optional(),graph:qo.optional()}),z.object({symbolId:z.string().optional(),qualifiedName:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeDirectDependents:z.boolean().default(true),includeTransitiveDependents:z.boolean().default(true),depth:z.number().int().min(1).max(5).default(3),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),Pr=Te.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),relationshipType:z.string(),depth:z.number().int().positive(),isExported:z.boolean().optional(),transitiveImpactCount:z.number().int().nonnegative().optional(),languageMetadata:Y.optional()}),ms=z.object({filePath:z.string(),symbolCount:z.number().int().positive(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),symbols:z.array(z.object({id:z.string(),name:z.string(),kind:z.string(),line:z.number().int().positive()}))}),fs=z.object({riskLevel:Re,factors:z.array(z.object({factor:z.string(),severity:z.enum(["low","medium","high"]),description:z.string()})),recommendations:z.array(z.string())}),z.object({symbol:z.object({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isExported:z.boolean().optional(),languageMetadata:Y.optional()}),directDependents:z.array(Pr).optional(),transitiveDependents:z.array(Pr).optional(),impactedFiles:z.array(ms),breakingChangeRisk:fs.optional(),summary:z.object({directDependentCount:z.number().int().nonnegative(),transitiveDependentCount:z.number().int().nonnegative(),impactedFileCount:z.number().int().nonnegative(),testFileCount:z.number().int().nonnegative(),productionFileCount:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()})}),z.object({filePattern:z.string().optional(),filterByKind:z.array(z.string()).optional(),exportedOnly:z.boolean().optional(),excludeTests:z.boolean().default(true),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeConfidence:z.boolean().optional()}),hs=z.object({symbolId:z.string(),name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),isExported:z.boolean(),reason:z.string(),confidence:z.number().min(0).max(1),languageMetadata:Y.optional()}),ys=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(hs),orphanedFiles:z.array(ys)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),bs=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),vs=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),Cs=z.object({languages:z.array(bs),frameworks:z.array(vs),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),_s=z.object({files:z.object({total:z.number().int().nonnegative(),byType:z.record(z.string(),z.number()),byParadigm:z.record(z.string(),z.number())}),symbols:z.object({total:z.number().int().nonnegative(),byKind:z.record(z.string(),z.number()),exported:z.number().int().nonnegative(),public:z.number().int().nonnegative()}),modules:z.object({total:z.number().int().nonnegative(),averageSize:z.number().nonnegative(),largest:z.string()})}),Ss=z.object({internal:z.object({totalConnections:z.number().int().nonnegative(),averagePerFile:z.number().nonnegative(),mostConnectedFiles:z.array(z.object({path:z.string(),incomingCount:z.number().int().nonnegative(),outgoingCount:z.number().int().nonnegative()}))}),external:z.object({totalPackages:z.number().int().nonnegative(),directDependencies:z.number().int().nonnegative(),topPackages:z.array(z.object({name:z.string(),usageCount:z.number().int().nonnegative()}))})}),ws=z.object({complexity:z.object({average:z.number().nonnegative(),high:z.number().int().nonnegative()}),maintainability:z.object({score:z.number().min(0).max(100),issues:z.array(z.string())}),testCoverage:z.object({percentage:z.number().min(0).max(100),testedFiles:z.number().int().nonnegative(),totalFiles:z.number().int().nonnegative()}).optional()}),xs=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),Es=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),Ps=z.object({nodes:z.array(xs),edges:z.array(Es)}),z.object({metadata:Cs,structure:_s,dependencies:Ss,metrics:ws.optional(),moduleGraph:Ps.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),Is=z.enum(["relative","workspace","alias","external","builtin"]),Ns=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:Is}),Rs=z.record(z.string(),Ns),Nr=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),Ts=Nr.exclude(["import-use","declaration"]),$s=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:Nr}).strict(),tn=z.object({filePath:z.string().min(1),entries:z.array($s)}).strict(),z.object({file:z.string().min(1),language:z.string().min(1),commit:z.string().min(1),timestamp:z.string().datetime(),ast:z.string().min(1),importResolutions:Rs.optional(),classificationMap:tn.optional()}).strict(),ks=z.object({file:z.string(),error:z.string()}),js=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),As=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(js)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(ks).optional(),relationships:As}),z.object({projectId:z.string(),projectName:z.string(),branch:z.string(),latestCommit:z.string().nullable(),fileCount:z.number().int().nonnegative(),lastIndexedAt:z.string().nullable(),languages:z.array(z.string())}),Ls=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(Ls),isType:z.boolean(),isDynamic:z.boolean(),isConditional:z.boolean().optional(),isLazy:z.boolean().optional(),isWildcard:z.boolean().optional(),line:z.number(),column:z.number()}),z.object({referencerId:z.string(),referencedName:z.string(),referenceType:Ts,line:z.number(),column:z.number(),scope:z.string().optional(),objectContext:z.string().optional(),language:z.string().optional()}),Rr=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),Ir=Rr.extend({name:z.string().min(1)}).strict(),Fs=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().optional()}).strict(),Os=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:Fs.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(Rr).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(Ir).max(200),outgoingCalls:z.array(Ir).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(Os)}).strict(),z.object({projectId:z.string().min(1),branch:z.string().min(1),commit:z.string().regex(/^[0-9a-f]{40}$/),timestamp:z.string().datetime()}).strict(),z.enum(["pending","processing","completed","failed","skipped"]),Ds=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),Ms=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),Us=z.object({id:z.string(),label:z.string(),type:Ds,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),Bs=z.object({id:z.string(),source:z.string(),target:z.string(),type:Ms,label:z.string().optional()}),Hs=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Re.optional()}),Gs=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(Us),edges:z.array(Bs),summary:Hs,metadata:Gs,features:z.record(z.string(),z.boolean()).optional()}),Tr=z.object({projectId:z.string(),projectName:z.string(),defaultBranch:z.string(),lastIndexedAt:z.string().datetime().optional(),fileCount:z.number().int().nonnegative().optional(),languages:z.array(z.string()).optional()}),z.object({projects:z.array(Tr)}),Tr.pick({projectId:true,projectName:true,defaultBranch:true}),$r=z.enum(["unresolved","resolved","archived"]),kr=z.enum(["succeeded","failed"]),jr=z.enum(["full","incremental"]),Ws=z.enum(["info","warn","error"]),zs=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),Ks=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),Ar=z.object({errors:z.array(zs),warnings:z.array(Ks)}),Lr=z.object({level:Ws,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:Ar,logEntries:z.array(Lr),cliVersion:z.string(),outcome:kr,indexType:jr}),z.object({status:$r.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:jr,status:$r,outcome:kr,errorSummary:z.string(),errorData:Ar,logEntries:z.array(Lr),cliVersion:z.string(),resolvedAt:z.string().nullable(),resolvedBy:z.string().nullable(),createdAt:z.string(),updatedAt:z.string(),organizationName:z.string().optional(),projectName:z.string().optional(),userEmail:z.string().optional(),resolvedByEmail:z.string().optional()}),z.object({unresolvedCount:z.number(),failedRunCount:z.number(),resolvedLast30d:z.number(),avgResolutionDays:z.number().nullable(),affectedOrgCount:z.number()});});async function ie(i,e,t,r,o,s=[]){let a=await t.resolve(i),l=Fr(i,a),c=o(i,a,l),u=l?void 0:lt(a);r[e.toString()]={source:i,resolvedPath:u,isExternal:l,importType:c,specifiers:s};}function Fr(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var nn,ke=f(()=>{ae();nn=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function Vs(i,e,t,r){let o=i.childForFieldName("name");if(!o)return;let s,a;if(o.type==="aliased_import"){let l=o.childForFieldName("name"),c=o.childForFieldName("alias");s=l?l.text:o.text,a={local:c?c.text:s.split(".")[0],original:s,isDefault:false,isNamespace:false};}else s=o.text,a={local:s.split(".")[0],original:s,isDefault:false,isNamespace:false};await ie(s,i.startPosition.row,e,t,r,[a]);}function Ys(i,e){if(!e)return [];let t=[],r=i.childForFieldName("name");if(r){if(r.type==="aliased_import"){let s=r.childForFieldName("name"),a=r.childForFieldName("alias");s&&t.push({local:a?a.text:s.text,original:s.text,isDefault:false,isNamespace:false});}else t.push({local:r.text,original:r.text,isDefault:false,isNamespace:false});return t}let o=false;for(let s=0;s<i.childCount;s++){let a=i.child(s);if(a){if(a.type==="import"){o=true;continue}if(o){if(a.type==="dotted_name"||a.type==="identifier")t.push({local:a.text,original:a.text,isDefault:false,isNamespace:false});else if(a.type==="aliased_import"){let l=a.childForFieldName("name"),c=a.childForFieldName("alias");l&&t.push({local:c?c.text:l.text,original:l.text,isDefault:false,isNamespace:false});}}}}return t}async function qs(i,e,t,r){let o,s=i.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<i.childCount;c++){let u=i.child(c);if(u){if(u.type==="relative_import"){l=u.text;break}(u.type==="."||u.type==="import_prefix")&&(l+=u.text);}}o=l||".";}let a=Ys(i,!!s);await ie(o,i.startPosition.row,e,t,r,a);}async function Xs(i,e,t,r){await ie("__future__",i.startPosition.row,e,t,r,[]);}function rn(){return {language:"python",handlers:new Map([["import_statement",Vs],["import_from_statement",qs],["future_import_statement",Xs]]),classifyImportType:Js}}var Js,Ct=f(()=>{vt();ke();vt();Js=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let r=i.split(".")[0];return $e.has(r)?"builtin":"alias"};});var _t,Or=f(()=>{Ct();_t=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=P.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if($e.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let r=e.replace(/\./g,"/"),o=await this.tryResolveFile(P.resolve(this.projectRoot,r));return o?P.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let r=e.slice(t),o=t<=1?"":"../".repeat(t-1),s=r?o+r.replace(/\./g,"/"):o.slice(0,-1)||".",a=P.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?P.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,P.join(e,"__init__.py"),P.join(e,"__init__.pyi")];for(let r of t)try{return await qt.promises.access(r,qt.constants.F_OK),r}catch{continue}return null}};});var wt,Dr=f(()=>{ft();Or();wt=class extends re{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new _t(e,process.cwd())}};});function Ae(i){return ta[i]??i.charAt(0).toUpperCase()+i.slice(1)}var ta,je,xt,Et=f(()=>{xr();Er();Dr();ta={bash:"Bash",c:"C","c-sharp":"C#",cpp:"C++",go:"Go",java:"Java",javascript:"JavaScript",json:"JSON",php:"PHP",python:"Python",ruby:"Ruby",typescript:"TypeScript"};je={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},xt=class{constructor(e){this.config=e;this.registerPlugin(new yt),this.registerPlugin(new bt),this.registerPlugin(new wt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Qs,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??je.javascript};typescript={language:()=>ea.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??je.typescript};python={language:()=>Zs,fileExtensions:()=>this.config?.languages.python?.fileExtensions??je.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function be(i,e,t=32){let r=i.parent,o=0;for(;r!==null&&o<t;){if(e(r))return r;r=r.parent,o++;}return null}var Pt,on=f(()=>{Pt=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function sn(i,e){if(i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"||i.type==="jsx_closing_element"){let t=i.childForFieldName("name");t!==null&&na(t,e);}for(let t of i.namedChildren)t&&sn(t,e);}function na(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(ce(i.startPosition.row,i.startPosition.column),"call");return}if(i.type==="member_expression"||i.type==="nested_identifier"){let t=i.childForFieldName("property");t!==null&&e.set(ce(t.startPosition.row,t.startPosition.column),"call");}}var Mr=f(()=>{Le();});function ve(i,e){i.rootNode&&(Br(i.rootNode,e),sn(i.rootNode,e));}function Br(i,e){if(ra.has(i.type)){let t=ia(i);t!==null&&e.set(ce(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&Br(t,e);}function ia(i){if(sa(i))return "declaration";if(ha(i))return "read";if(ma(i))return "type";let e=be(i,t=>t.type==="decorator");return e!==null&&ca(i,e)?"call":la(i)?"instantiate":aa(i)?"call":pa(i)||ua(i)||da(i)||xa(i)||wa(i)?"write":ya(i)?"import-use":"read"}function sa(i){let e=i.parent;return e===null?false:!!(oa.has(e.type)&&(e.childForFieldName("name")===i||e.childForFieldName("property")===i)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===i||e.type==="import_specifier"&&(e.childForFieldName("name")===i||e.childForFieldName("alias")===i)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===i&&i.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===i||e.type==="enum_body")}function aa(i){let e=i.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function la(i){let e=i.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function ca(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call_expression"){let r=t.childForFieldName("function");if(r===i||r?.type==="member_expression"&&r.childForFieldName("property")===i)return true}return t.type==="member_expression"&&t.childForFieldName("property")===i}function pa(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="unary_expression")return t.child(0)?.type==="delete";if(t.type==="member_expression"&&t.childForFieldName("object")===e||Pt.has(t.type))return false;e=t;}return false}function ua(i){let e=i.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===i)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function da(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="assignment_expression"||t.type==="augmented_assignment_expression")&&t.childForFieldName("left")===e)return true;if(t.type==="member_expression"&&t.childForFieldName("object")===e||t.type==="subscript_expression"&&t.childForFieldName("object")!==e||Pt.has(t.type))return false;e=t;}return false}function ma(i){let e=i.parent,t=i;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let r=e.namedChild(1);return r===null?false:r===t||fa(r,i)}if(ga.has(e.type))return true;if(Pt.has(e.type))return false;t=e,e=e.parent;}return false}function fa(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function ha(i){return be(i,t=>t.type==="type_query")!==null}function ya(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,r=_a(i);return Sa(r,t)?!va(i,t):false}function va(i,e){let t=i.parent;for(;t!==null;){if(ba.has(t.type)&&Ca(t,e))return true;t=t.parent;}return false}function Ca(i,e){for(let t of i.namedChildren){if(t.type==="lexical_declaration"||t.type==="variable_declaration")for(let r of t.namedChildren){if(r.type!=="variable_declarator")continue;if(r.childForFieldName("name")?.text===e)return true}if(t.type==="formal_parameters")for(let r of t.namedChildren){if(r.type!=="required_parameter"&&r.type!=="optional_parameter")continue;let o=r.childForFieldName("pattern");if(o?.type==="identifier"&&o.text===e)return true}}return false}function _a(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function Sa(i,e){for(let t of i.descendantsOfType("namespace_import")){let r=t.namedChild(0);if(r!==null&&r.text===e)return true}return false}function wa(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function xa(i){let e=i.parent;if(e===null||!Ur.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===i||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==i)return false;let t=e;for(;t!==null;){let r=t.parent;if(r===null)return false;if(r.type==="variable_declarator"&&r.childForFieldName("name")===t||(r.type==="assignment_expression"||r.type==="augmented_assignment_expression")&&r.childForFieldName("left")===t||(r.type==="required_parameter"||r.type==="optional_parameter")&&r.childForFieldName("pattern")===t||r.type==="formal_parameters"||r.type==="for_in_statement"&&r.childForFieldName("left")===t)return true;if(!Ur.has(r.type))return false;t=r;}return false}var ra,oa,ga,ba,Ur,It=f(()=>{Le();on();Mr();ra=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));oa=Object.freeze(new Set(["variable_declarator","function_declaration","function_signature","generator_function_declaration","class_declaration","abstract_class_declaration","interface_declaration","type_alias_declaration","enum_declaration","enum_assignment","method_signature","abstract_method_signature","method_definition","public_field_definition","field_definition","property_signature"]));ga=Object.freeze(new Set(["type_annotation","type_arguments","type_parameter","type_parameters","type_alias_declaration","interface_declaration","generic_type","type_predicate","type_query","conditional_type","union_type","intersection_type","tuple_type","mapped_type_clause","implements_clause","extends_type_clause"]));ba=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Ur=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function Hr(i,e){ve(i,e);}var Gr=f(()=>{It();});function Wr(i,e){ve(i,e);}var zr=f(()=>{It();});function Kr(i,e){if(!i.rootNode)return;let t=za(i.rootNode);Jr(i.rootNode,e,t);}function Jr(i,e,t){if(Ea.has(i.type)){let r=Pa(i,t);r!==null&&e.set(ce(i.startPosition.row,i.startPosition.column),r);}for(let r of i.namedChildren)r&&Jr(r,e,t);}function Pa(i,e){if(Ia(i))return "declaration";if(Ta(i))return "read";if(Ra(i))return "declaration";if($a(i))return "type";let t=be(i,r=>r.type==="decorator");return t!==null&&ka(i,t)||ja(i)?"call":Aa(i)||La(i)||Fa(i)||Da(i)||Ua(i)?"write":Ba(i,e)?"import-use":"read"}function Ia(i){let e=i.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===i||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===i)return true;if(e.type==="list_splat_pattern"||e.type==="dictionary_splat_pattern"){let t=e.parent;if(t?.type==="parameters"||t?.type==="lambda_parameters")return true}return !!(e.type==="as_pattern_target"||Na(i))}function Na(i){let e=i.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function Ra(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(an.has(e.type))return false;e=e.parent;}return false}function Ta(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function $a(i){return be(i,t=>t.type==="type")!==null}function ka(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call"){let r=t.childForFieldName("function");if(r===i||r?.type==="attribute"&&r.childForFieldName("attribute")===i)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===i}function ja(i){let e=i.parent;if(e?.type==="call"&&e.childForFieldName("function")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function Aa(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="delete_statement")return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||an.has(t.type))return false;e=t;}return false}function La(i){let e=i.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function Fa(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function Da(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment"&&t.childForFieldName("left")===e)return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||t.type==="subscript"&&t.childForFieldName("value")!==e)return false;if(Oa.has(t.type)){e=t;continue}if(an.has(t.type))return false;e=t;}return false}function Ua(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="for_statement"||t.type==="for_in_clause")&&t.childForFieldName("left")===e)return true;if(!Ma.has(t.type))return false;e=t;}return false}function Ba(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let r=i.text;return e.has(r)?!Ga(i,r):false}function Ga(i,e){let t=i.parent;for(;t!==null;){if(Ha.has(t.type)&&Wa(t,e))return true;t=t.parent;}return false}function Wa(i,e){for(let t of i.namedChildren){if(t.type==="expression_statement"){let r=t.namedChild(0);if(r?.type==="assignment"){let o=r.childForFieldName("left");if(o?.type==="identifier"&&o.text===e)return true}}if(t.type==="parameters"){for(let r of t.namedChildren)if(r.type==="identifier"&&r.text===e||(r.type==="typed_parameter"||r.type==="typed_default_parameter"||r.type==="default_parameter")&&r.namedChild(0)?.type==="identifier"&&r.namedChild(0)?.text===e)return true}}return false}function za(i){let e=new Set;for(let t of i.descendantsOfType("import_statement"))for(let r of t.namedChildren)if(r.type==="dotted_name"&&e.add(r.text),r.type==="aliased_import"){let o=r.childForFieldName("alias");o&&e.add(o.text);}return e}var Ea,an,Oa,Ma,Ha,Vr=f(()=>{Le();on();Ea=Object.freeze(new Set(["identifier"])),an=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));Oa=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));Ma=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));Ha=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function qr(i,e){let t=new Map;switch(e){case "typescript":ve(i,t);break;case "tsx":Hr(i,t);break;case "javascript":Wr(i,t);break;case "python":Kr(i,t);break}return t}function ce(i,e){return `${i}:${e}`}var Yr,Le=f(()=>{It();Gr();zr();Vr();Yr=Object.freeze(new Set(["typescript","javascript","python"]));});function Va(i,e){return Yr.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function Ya(i){let e=[];for(let[t,r]of i.entries()){let o=t.indexOf(":");if(o<0)continue;let s=Number(t.slice(0,o)),a=Number(t.slice(o+1));!Number.isFinite(s)||!Number.isFinite(a)||e.push({line:s,column:a,referenceType:r});}return e.sort((t,r)=>t.line-r.line||t.column-r.column),e}var Nt,Zr=f(()=>{Le();K();Nt=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let r=this.langRegistry[t]?.language;if(!r)throw new Error(`Unsupported language: ${t}`);let o=await r();if(!o)throw new Error(`Failed to load language: ${t}`);t==="typescript"&&e.toLowerCase().endsWith(".tsx")&&(o=ea.tsx);let s=new Ka;s.setLanguage(o);let a=await _.getFileStats(e),l=10*1024*1024,c;if(a.size<=l){let m=await _.readFile(e),h={bufferSize:1024*1024};c=s.parse(m,void 0,h);}else c=await this.parseWithStream(s,e,a.size);let u=Va(t,e),g=u===null?[]:Ya(qr(c,u));return {tree:c,classificationMap:{filePath:e,entries:g}}}async parseWithStream(e,t,r){let o=null;try{o=await B.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(g=>{if(r>50*1024*1024){let m=Math.round(g/r*100);m>c+10&&(console.log(` Parsing large file: ${m}%...`),c=m);}let d=qt.readSync(s,l,0,a,g);return d===0?null:l.subarray(0,d).toString("utf-8")})}catch(s){if(o)try{await o.close();}catch(a){console.error(`Warning: Failed to close file handle for ${t}:`,a);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var Rt,ti=f(()=>{K();ae();D();Rt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=ei();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(s=>!t.ignores(s.relativePath)&&this.matchesLanguageExtension(s,e.languages))}async scanSpecificFiles(e,t){let r=[],o=null;t.exclude&&t.exclude.length>0&&(o=ei().add(t.exclude));let s=await B__default.realpath(this.rootPath);for(let a of e)try{let l=P__default.isAbsolute(a)?a:P__default.join(this.rootPath,a),c=await B__default.lstat(l);if(c.isSymbolicLink()){let u=await B__default.realpath(l);if(!u.startsWith(s+P__default.sep)&&u!==s){console.warn(`${b} Skipping symlink pointing outside project: ${a} -> ${u}`);continue}let g=await B__default.stat(l);if(!g.isFile())continue;let d=M(this.rootPath,l);if(o&&o.ignores(d))continue;let m=this.detectLanguage(d,t.languages);if(!m)continue;r.push({path:l,relativePath:d,language:m,size:g.size});}else if(c.isFile()){let u=M(this.rootPath,l);if(o&&o.ignores(u))continue;let g=this.detectLanguage(u,t.languages);if(!g)continue;r.push({path:l,relativePath:u,language:g,size:c.size});}}catch{console.warn(`${b} Skipping inaccessible file: ${a}`);}return r}async loadGitignoreRules(e,t){let r=[],o=t;for(;;){let s=P__default.join(o,".gitignore");await _.fileIsReadable(s)&&r.unshift(s);let a=P__default.dirname(o);if(a===o)break;o=a;let l=P__default.join(o,".git");if(await _.directoryExists(l)){let c=P__default.join(o,".gitignore");await _.fileIsReadable(c)&&!r.includes(c)&&r.unshift(c);break}}for(let s of r)try{let a=await _.readFile(s);e.add(a);}catch{console.warn(`${b} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,r,o){let s=[],a=t||e,l=r||await B__default.realpath(this.rootPath),c=o||new Set([l]);try{let u=await B__default.readdir(e,{withFileTypes:!0});for(let g of u){let d=P__default.join(e,g.name),m=M(a,d);if(g.isDirectory()){if(g.name.startsWith("."))continue;let h=await this.walkDirectory(d,a,l,c);s.push(...h);}else if(g.isFile()){let h=await B__default.stat(d);s.push({path:d,relativePath:m,language:"",size:h.size});}else if(g.isSymbolicLink())try{let h=await B__default.realpath(d);if(!h.startsWith(l+P__default.sep)&&h!==l){console.warn(`${b} Skipping symlink pointing outside project: ${d} -> ${h}`);continue}let y=await B__default.stat(d);if(y.isDirectory()){if(g.name.startsWith(".")||c.has(h))continue;c.add(h);let S=await this.walkDirectory(d,a,l,c);s.push(...S);}else y.isFile()&&s.push({path:d,relativePath:m,language:"",size:y.size});}catch{console.warn(`${b} Skipping invalid symlink: ${d}`);}}}catch(u){console.error(`${E} Error walking directory ${e}:`,u);}return s}matchesLanguageExtension(e,t){let r=P__default.extname(e.path).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return e.language=o,true;return false}detectLanguage(e,t){let r=P__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(r))return o;return null}};});var qa,Xa,Qa,ni,ri=f(()=>{vt();qa=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Xa=z.object({source:z.string().min(1,"Import source cannot be empty"),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:z.enum(["relative","workspace","alias","external","builtin"]),specifiers:z.array(qa).optional()}),Qa=z.record(z.string(),Xa),ni=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Qa.optional(),classificationMap:tn.optional()});});var el,Tt,si=f(()=>{el=promisify(ln__default.gunzip),Tt=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],r=ln__default.createGzip();r.on("data",a=>t.push(a));let o=new Promise((a,l)=>{r.on("end",a),r.on("error",l);}),s=Readable.from(e);return await pipeline(s,r),await o,Buffer.concat(t).toString("base64")}async compress(e){let t=[],r=ln__default.createGzip();r.on("data",a=>t.push(a));let o=new Promise((a,l)=>{r.on("end",a),r.on("error",l);}),s=Readable.from(this.serializeASTChunks(e));return await pipeline(s,r),await o,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),r=await el(t);return JSON.parse(r.toString("utf-8"))}};});var cn,$t=f(()=>{cn=new Set(["ACCESS_KEY_MISSING","AUTH_FAILURE","PROJECT_NOT_REGISTERED","PROJECT_INACTIVE","INVALID_PROJECT_ID","DIRTY_WORKTREE","CONCURRENT_INDEXING","GIT_SYNC_FAILURE","BRANCH_NOT_CONFIGURED","ENRICHMENT_FAILED"]);});function pn(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var Fe,ai=f(()=>{$t();Fe=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:p.unstyle(e.map(pn).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:p.unstyle(e.map(pn).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:p.unstyle(e.map(pn).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!cn.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!cn.has(e.code)))}capture(e,t,r){this.entries.push({level:e,message:p.unstyle(t),timestamp:new Date().toISOString(),code:r});let o=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?o.call(console,t):console[e==="info"?"log":e](t);}};});var jt,li=f(()=>{jt=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let r=new Map,o=0,s=0;for(;s<e.length&&r.size<this.concurrency;){let a=o++,l=this.processItem(e[s],s,t).then(c=>({result:c!==null?c.result:null,promiseId:a}));r.set(a,l),s++;}for(;r.size>0;){let a=await Promise.race(r.values());if(r.delete(a.promiseId),a.result!==null&&(yield a.result),s<e.length){let l=o++,c=this.processItem(e[s],s,t).then(u=>({result:u!==null?u.result:null,promiseId:l}));r.set(l,c),s++;}}}async processItem(e,t,r){try{return {result:await r(e,t),index:t}}catch{return null}}};});function tl(i){let e=[];for(let t=0;t<i.childCount;t++){let r=i.child(t);if(r){if(r.type==="identifier")e.push({local:r.text,original:"default",isDefault:true,isNamespace:false});else if(r.type==="namespace_import"){let o;for(let s=0;s<r.childCount;s++){let a=r.child(s);if(a?.type==="identifier"){o=a.text;break}}o!==void 0&&e.push({local:o,original:void 0,isDefault:false,isNamespace:true});}else if(r.type==="named_imports")for(let o=0;o<r.childCount;o++){let s=r.child(o);if(!s||s.type!=="import_specifier")continue;let a=s.childForFieldName("name"),l=s.childForFieldName("alias");if(!a)continue;let c=a.text,u=l?l.text:c,g=c==="default";e.push({local:u,original:c,isDefault:g,isNamespace:false});}}}return e}async function nl(i,e,t,r){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=i.childForFieldName("import_clause"),c=l?tl(l):[];await ie(a,s,e,t,r,c);}async function rl(i,e,t,r){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await ie(a,s,e,t,r,[]);}function At(){return {language:"javascript",handlers:new Map([["import_statement",nl],["export_statement",rl]])}}function un(){return {...At(),language:"typescript"}}var dn=f(()=>{ke();});var ci,pi=f(()=>{dn();Ct();ke();dn();Ct();ci=[At(),un(),rn()];});var ui={};Vn(ui,{ImportExtractor:()=>gn});var gn,di=f(()=>{pi();ke();gn=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??ci)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,r,o){if(!o)return {};let s=this.languageHandlers.get(r);if(!s)return {};let a=this.classifiers.get(r)??nn,l={};return await this.walkAST(e.rootNode,async c=>{let u=s.get(c.type);u&&await u(c,o,l,a);}),l}async walkAST(e,t){await t(e);for(let r=0;r<e.childCount;r++){let o=e.child(r);o&&await this.walkAST(o,t);}}};});var Oe,gi,mn,mi,fi,Lt=f(()=>{Oe=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),gi=new Set(["true","false","null","undefined","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type"]),mn={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},mi={language:"javascript",textIncludedTypes:gi,fieldNames:mn},fi={language:"typescript",textIncludedTypes:gi,fieldNames:mn};});var il,hi,yi,fn=f(()=>{il=new Set(["true","false","none","None","True","False","yield","pass","continue","break","ellipsis","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","type","subscript","attribute","list","tuple","binary_operator","union_type","generic_type"]),hi={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],list_splat_pattern:[],dictionary_splat_pattern:[],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]},yi={language:"python",textIncludedTypes:il,fieldNames:hi,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function bi(i){return De.get(i)}function vi(i){if(!i)return Oe;let e=De.get(i);if(!e)return Oe;let t=new Set(Oe);for(let r of e.textIncludedTypes)t.add(r);return t}function hn(i){if(!i){let t=Array.from(De.values()).map(r=>r.fieldNames);return Me(...t)}let e=De.get(i);if(!e){let t=Array.from(De.values()).map(r=>r.fieldNames);return Me(...t)}return e.fieldNames}var De,Ci=f(()=>{yn();Lt();fn();Lt();Lt();fn();De=new Map([["javascript",mi],["typescript",fi],["python",yi]]);});var Ei={};Vn(Ei,{COMMON_FIELD_NAMES:()=>Cn,JS_TS_FIELD_NAMES:()=>wi,PYTHON_FIELD_NAMES:()=>xi,TEXT_INCLUDED_TYPES:()=>_i,mergeFieldMaps:()=>Me,serializeAST:()=>sl,serializeASTStream:()=>ol});function*ol(i,e,t){yield*vn(i,e,t);}function*vn(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),Si(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?hn(t):Cn)[i.type]||[],s=new Set,a=true;for(let l of o){let c=i.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*vn(c,l,t));}for(let l=0;l<i.childCount;l++){let c=i.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*vn(c,void 0,t));}yield "]";}yield "}";}async function sl(i,e,t){let r=bn(i,e,t),o=t?hn(t):Cn,s=[{treeNode:i,serializedNode:r,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;s.length>0;){let a=s[s.length-1];if(a.childIndex===0&&a.treeNode.childCount>0){let l=o[a.treeNode.type]||[];for(let c of l){let u=a.treeNode.childForFieldName(c);if(u){a.fieldChildren.add(u);let g=bn(u,c,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(g),s.push({treeNode:u,serializedNode:g,fieldName:c,childIndex:0,fieldChildren:new Set});}}}if(a.childIndex<a.treeNode.childCount){let l=a.treeNode.child(a.childIndex);if(a.childIndex++,l&&!a.fieldChildren.has(l)){let c=bn(l,void 0,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(c),s.push({treeNode:l,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else s.pop();}return r}function bn(i,e,t){let r={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return Si(i,t)&&(r.text=i.text),r}function Si(i,e){if(e){let r=bi(e);if(r?.shouldIncludeText){let s=r.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return vi(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:_i.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function Me(...i){let e={};for(let t of i)for(let[r,o]of Object.entries(t)){let a=[...e[r]||[]];for(let l of o)a.includes(l)||a.push(l);e[r]=a;}return e}var _i,wi,xi,Cn,yn=f(()=>{Ci();_i=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","string_fragment","number","true","false","null","undefined","import_specifier","export_specifier","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","yield","pass","continue","break","None","none","True","False","ellipsis","type","string_content"]);wi={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},xi={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]};Cn=Me(wi,xi);});var Ue,Ii=f(()=>{it();fr();yr();_r();gt();Et();Zr();ti();ri();si();st();$t();ai();ae();li();D();at();Ue=class extends ne{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;logCollector=new Fe;discoveredFiles=[];constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new Rt(process.cwd()),this.parser=new Nt(this.langRegistry),this.compressor=new Tt;for(let t of Object.keys(this.config.languages)){let r=this.langRegistry.getPlugin(t);if(r?.getBuildConfigManager){let o=r.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false,r=false){this.logCollector=new Fe,this.logCollector.start();let o="failed";try{let s=await this.getAccessKey();this.apiClient=new nt(this.config,s),await this.validateProject(),this.logCollector.log(`${Q}Starting indexing procedure...
65
+ `);let a=performance.now();if(t?this.logCollector.log(`${b} Skipping git branch validation`):await this.validateGitBranch(),t?this.logCollector.log(`${b} Skipping git status validation`):await this.validateGitStatus(),t?this.logCollector.log(`${b} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){this.logCollector.log(`${v} Discovering language build configurations...`);let N=0;for(let[,T]of this.buildConfigManagers.entries()){let se=await T.initialize();N+=se.length;}N>0&&this.logCollector.log(`${C} Found ${N} configuration file(s)`);}let l=await this.determineIndexScope(e),c=await this.git.getLatestCommitHash();if(l.upToDate){this.logCollector.log(`
66
+ ${C} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${c.substring(0,8)}`),o="succeeded";return}let u=await this.apiClient.claimAstLock(this.config.projectId,this.config.branch,l.isIncremental,c);if(u.status==="current"){this.logCollector.log(`${C} Index already up to date for branch ${this.config.branch} at commit ${c?.substring(0,8)||"unknown"}`),o="succeeded";return}if(u.status==="processing"){this.logIndexingInProgress(this.config.branch),o="succeeded";return}let g=!1,d=()=>{g||this.logCollector.log(`${v} Uploading metadata, processing, and indexing...`);},m,h,y=new Promise((N,T)=>{m=N,h=T;}),S=new AbortController,x=this.createIndexPipeline(l.isIncremental,d,m),w=null;try{let[,N]=await Promise.all([this.uploadToAPI(x,l.isIncremental,c,u.attemptId).then(T=>(g=!0,T)).catch(T=>{throw S.abort(T),h(T),g=!0,T}),y.then(T=>{let se=this.getEnrichmentEligibleLanguages(r,T);return se?this.runLspEnrichment(T,se,S.signal).catch(J=>(S.signal.aborted||this.logCollector.warn(`${b} Index enrichment failed: ${J instanceof Error?J.message:String(J)}`,{code:"ENRICHMENT_FAILED"}),null)):null}).catch(()=>null)]);w=N;}catch(N){throw g=!0,N}if(w&&w.length>0)try{let J=this.discoveredFiles.length,Ze=Math.min(12e4+J*1e3,9e5);if(this.logCollector.log(`${v} Waiting for server to finish syntax tree processing (${J} files, timeout ${Math.round(Ze/1e3)}s)...`),await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,c,Ze)){this.logCollector.log(`${v} Uploading enrichment data (${w.length} files)...`);let so=hr(w);await this.apiClient.uploadEnrichment(so,this.config.projectId,this.config.branch,c)?this.logCollector.log(`${C} Enrichment data uploaded to Constellation Service, index enhancement in progress`):this.logCollector.log(`${b} Enrichment upload skipped (index state changed)`);}else this.logCollector.log(`${b} AST processing did not complete in time, enrichment skipped`);}catch(N){this.logCollector.warn(`${b} Enrichment upload failed: ${N instanceof Error?N.message:String(N)}`,{code:"ENRICHMENT_FAILED"});}let I=(performance.now()-a)/1e3,O=Math.floor(I/60),j=(I%60).toFixed(3),X=O>0?`${O}m ${j}s`:`${j}s`;this.logCollector.log(`
67
+ ${C} Upload completed in ${X}! Server indexing in progress.`),o="succeeded";}catch(s){if(s instanceof U)throw s;if(s instanceof de){this.logIndexingInProgress(s.branchName||this.config?.branch),o="succeeded";return}if(s instanceof $)throw this.logCollector.error(`
68
+ ${E} Authentication failed.`,{code:"AUTH_FAILURE"}),this.logCollector.log(`${v} Your access key may be invalid or expired. Run 'constellation auth'
69
+ to set or update your access key.`),s;if(s instanceof ee)throw this.logCollector.error(`${E} Indexing failed: ${s.message}`,{code:s.errorCode}),s;if(s instanceof Error&&s.message==="Access key not configured")throw s;let a=s instanceof Error?s.message:"An unexpected error occurred";throw this.logCollector.error(`${E} Indexing failed: ${a}`),s}finally{this.logCollector.stop();try{let a=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",l=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,c=this.logCollector.getReportableErrors();if(!a&&l&&c.length>0){let u=this.logCollector.getEntries(),g=c.map(w=>({type:"CLI_ERROR",message:w.message,phase:"indexing"})).slice(0,100),d=u.filter(w=>w.level==="warn").map(w=>({type:"CLI_WARNING",message:w.message,phase:"indexing"})).slice(0,100),m=g.length,h=d.length,y=[];m>0&&y.push(`${m} error${m!==1?"s":""}`),h>0&&y.push(`${h} warning${h!==1?"s":""}`);let S=y.join(", "),x=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:S,errorData:{errors:g,warnings:d},logEntries:u.slice(0,1e3),cliVersion:x,outcome:o,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(te);if(!e)throw this.logCollector.error(`
70
+ ${E} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),this.logCollector.log(`${v} Set the ${te} environment variable or run
71
+ 'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){this.logCollector.log(`${v} Validating project access...`);try{await this.apiClient.getProjectState(),this.logCollector.log(`${C} Project validated successfully`);}catch(e){if(e instanceof U)throw this.displayProjectValidationError(e),e;if(e instanceof Z){this.logCollector.log(`${C} Project validated (first index)`);return}if(e instanceof $)throw e;let t=e instanceof Error?e.message:String(e);throw t==="fetch failed"||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("ETIMEDOUT")||t.includes("EHOSTUNREACH")||t.includes("ECONNRESET")?new Error(`Unable to connect to the Constellation service.
72
72
  Verify your network connection and that the API URL is correct.`):e}}displayProjectValidationError(e){let t=e.projectId||this.config.projectId,r=t.length>40?t.substring(0,37)+"...":t;switch(e.code){case "PROJECT_NOT_REGISTERED":this.logCollector.error(`
73
- ${S} Project not registered
73
+ ${E} Project not registered
74
74
  `,{code:"PROJECT_NOT_REGISTERED"}),this.logCollector.log(` The project ID "${r}" in constellation.json`),this.logCollector.log(` is not associated with your Constellation account.
75
75
  `),this.logCollector.log(" To resolve this:"),this.logCollector.log(" 1. Verify the project exists at https://app.constellationdev.io"),this.logCollector.log(" 2. Check that the project ID in constellation.json is correct"),this.logCollector.log(` 3. Run 'constellation index' again
76
76
  `);break;case "PROJECT_INACTIVE":this.logCollector.error(`
77
- ${S} Project is inactive
77
+ ${E} Project is inactive
78
78
  `,{code:"PROJECT_INACTIVE"}),this.logCollector.log(` The project "${r}" has been deactivated.
79
79
  `),this.logCollector.log(" To resolve this:"),this.logCollector.log(" 1. Reactivate the project at https://app.constellationdev.io"),this.logCollector.log(` 2. Run 'constellation index' again
80
80
  `);break;case "INVALID_PROJECT_ID":this.logCollector.error(`
81
- ${S} Invalid project ID
81
+ ${E} Invalid project ID
82
82
  `,{code:"INVALID_PROJECT_ID"}),this.logCollector.log(` The project ID "${r}" in constellation.json`),this.logCollector.log(` is not a valid Constellation project identifier.
83
83
  `),this.logCollector.log(" To resolve this:"),this.logCollector.log(" 1. Get your project ID from https://app.constellationdev.io"),this.logCollector.log(" 2. Update the projectId field in constellation.json"),this.logCollector.log(` 3. Run 'constellation index' again
84
84
  `);break;default:this.logCollector.error(`
85
- ${S} Project validation failed: ${e.message}
86
- `,{code:"PROJECT_VALIDATION_FAILED"});}}logIndexingInProgress(e){this.logCollector.log(`${y} Another indexing operation is already in progress for branch ${e||"unknown"}. Your index is up to date with the current operation.`),this.logCollector.log(" Re-run this command after the current operation completes if you have newer changes.");}async validateGitBranch(){this.logCollector.log(`${y} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.logCollector.log(`${w} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.logCollector.log(`${y} Validating Git status...`),!(await this.git.status()).clean)throw new X(`Outstanding changes detected.
87
- Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");this.logCollector.log(`${w} Working tree clean`);}async synchronizeChanges(){this.logCollector.log(`${y} Synchronizing latest changes...`);try{await this.git.pull()&&this.logCollector.log(`${w} Repository synchronized successfully`);}catch(e){throw this.logCollector.error(`${S} Failed to synchronize repository`,{code:"GIT_SYNC_FAILURE"}),e instanceof Error&&(e.message.includes("uncommitted changes")?(this.logCollector.log(`
85
+ ${E} Project validation failed: ${e.message}
86
+ `,{code:"PROJECT_VALIDATION_FAILED"});}}logIndexingInProgress(e){this.logCollector.log(`${v} Another indexing operation is already in progress for branch ${e||"unknown"}. Your index is up to date with the current operation.`),this.logCollector.log(" Re-run this command after the current operation completes if you have newer changes.");}async validateGitBranch(){this.logCollector.log(`${v} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.logCollector.log(`${C} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.logCollector.log(`${v} Validating Git status...`),!(await this.git.status()).clean)throw new ee(`Outstanding changes detected.
87
+ Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");this.logCollector.log(`${C} Working tree clean`);}async synchronizeChanges(){this.logCollector.log(`${v} Synchronizing latest changes...`);try{await this.git.pull()&&this.logCollector.log(`${C} Repository synchronized successfully`);}catch(e){throw this.logCollector.error(`${E} Failed to synchronize repository`,{code:"GIT_SYNC_FAILURE"}),e instanceof Error&&(e.message.includes("uncommitted changes")?(this.logCollector.log(`
88
88
  To resolve:`),this.logCollector.log(' 1. Commit your changes: git add . && git commit -m "your message"'),this.logCollector.log(" 2. Or stash them: git stash"),this.logCollector.log(` 3. Then run the index command again
89
89
  `)):e.message.includes("merge conflicts")?(this.logCollector.log(`
90
90
  To resolve:`),this.logCollector.log(" 1. Fix the conflicted files manually"),this.logCollector.log(" 2. Stage the resolved files: git add <resolved-files>"),this.logCollector.log(" 3. Complete the merge: git commit"),this.logCollector.log(` 4. Then run the index command again
@@ -92,11 +92,11 @@ To resolve:`),this.logCollector.log(" 1. Fix the conflicted files manually"),th
92
92
  Please check your internet connection and try again
93
93
  `):e.message.includes("Authentication")&&this.logCollector.log(`
94
94
  Please check your git credentials and try again
95
- `)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.logCollector.log(`${y} Determining index scope...`);try{let r=(await this.apiClient.getProjectState())?.latestCommit;if(!r)return this.logCollector.log(`${y} No previous index found, performing full index`),{isIncremental:!1,upToDate:!1};let n=await this.git.getLatestCommitHash();return r===n?(this.logCollector.log(`${w} Already up to date`),{isIncremental:!0,upToDate:!0}):(this.logCollector.log(`${y} Last indexed commit: ${r.substring(0,8)}`),this.logCollector.log(`${y} Current commit: ${n.substring(0,8)}`),this.logCollector.log(`${y} Performing incremental index starting from commit ${r.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof $)throw t;return this.logCollector.log(`${C} Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){this.logCollector.log(`${y} Analyzing codebase...`);let t;if(e)try{let r=await this.apiClient.getProjectState();if(!r?.latestCommit)this.logCollector.log(`${C} Cannot determine changes (no latestCommit in project state), falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let n=await this.git.getChangedFiles(r.latestCommit),o=[...n.added,...n.modified,...n.renamed.map(a=>a.to)];this.logCollector.log(`${y} Found ${o.length} changed files`),t=await this.scanner.scanSpecificFiles(o,this.config);let i=[...n.deleted,...n.renamed.map(a=>a.from)];if(i.length>0){let a=n.deleted.length,l=n.renamed.length,d=l>0?`${y} Removing ${a} deleted file(s) and ${l} renamed file(s) from graph`:`${y} Removing ${a} deleted file(s) from graph`;this.logCollector.log(d),await this.apiClient.deleteFiles(i);}}}catch(r){if(r instanceof $)throw r;this.logCollector.log(`${C} Cannot determine changes (${r instanceof Error?r.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else this.logCollector.log(`${y} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return this.logCollector.log(`${w} Found ${t.length} files to index`),t}async*generateASTs(e,t){let r=new Date().toISOString(),n=e.length,o=0,i=0;this.logCollector.log(`${y} Processing ${n} files...`);let a=await this.git.getLatestCommitHash(),l=n>1e4?5:n>5e3?7:10;l<10&&this.logCollector.log(`${y} Large project detected, using concurrency of ${l} to optimize memory usage`);let g=new vt(l).run(e,async(p,u)=>{let f=Math.round((u+1)/n*100);this.logCollector.log(`${y} Analyzing file ${p.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let h=await this.parser.parseFile(p.path,p.language),_=this.langRegistry.getPlugin(p.language),I;if(_?.getImportResolver){let T=this.buildConfigManagers.get(p.language),K=T?await T.getConfigForFile(p.path):null,R=_.getImportResolver(p.path,K);if(R){let{ImportExtractor:k}=await Promise.resolve().then(()=>(xn(),Pn));I=await new k().extractImportResolutions(h,p.path,p.language,R);}}let{serializeASTStream:P}=await Promise.resolve().then(()=>(Qt(),Mn)),j=P(h.rootNode,void 0,p.language),E=await this.compressor.compressStream(j),x={file:this.normalizePathToCanonical(p.relativePath),language:p.language,commit:a,timestamp:r,ast:E,importResolutions:I},A=hn.safeParse(x);if(!A.success)throw new Error(`AST validation failed: ${A.error.issues[0].message}`);return o++,A.data}catch(h){throw i++,this.logCollector.warn(` ${C} Failed to parse ${p.relativePath}: ${h.message}`,{code:"PARSE_FAILURE"}),h}});for await(let p of g)yield p;i>0?this.logCollector.log(`${C} Completed parsing with ${i} parsing errors`):this.logCollector.log(`${w} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,r,n){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,r,n))throw new Error("Failed to upload data to Constellation Service");this.logCollector.log(`${w} Data uploaded to Constellation Service, indexing in progress`);}async*createIndexPipeline(e,t,r){let n=await this.discoverFiles(e);this.discoveredFiles=n,r(n),yield*this.generateASTs(n,t);}normalizePathToCanonical(e){return Xe(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||ge.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.logCollector.log(`${y} Index enrichment skipped (--no-enrich flag)`),null;if(this.config.lspEnrichment===false)return this.logCollector.log(`${y} Index enrichment disabled in constellation.json`),null;let n=[...new Set(t.map(o=>o.language))].filter(o=>this.isLanguageLspEligible(o));return n.length===0?null:(this.logCollector.log(`${y} Index enrichment enabled for: ${n.map(Pe).join(", ")}`),new Set(n))}async runLspEnrichment(e,t,r){let n=new ot(process.cwd(),this.logCollector);try{if(r?.aborted)return null;this.logCollector.log(`${y} Starting index enrichment...`);let o=new Map,i=new Map;for(let u of e){if(!t.has(u.language))continue;let f=o.get(u.language)||[];if(f.push(this.normalizePathToCanonical(u.relativePath)),o.set(u.language,f),!i.has(u.language)){let _=this.config.languages[u.language]?.lsp,I=await n.startServer(u.language,_);I&&i.set(u.language,I);}}if(i.size===0)return this.logCollector.log(`${C} No language servers started, index enrichment skipped`),null;if(r?.aborted)return n.destroyAll(),null;this.logCollector.log(`${w} Language servers started: ${[...i.keys()].map(Pe).join(", ")}`);let a=new Map,l=new Ze(process.cwd()),d=r?new Promise((u,f)=>{r.addEventListener("abort",()=>{n.destroyAll(),f(r.reason||new Error("Indexing aborted"));},{once:!0});}):null,g=await(d?Promise.race([l.enrich(o,a,i),d]):l.enrich(o,a,i)),p=g.reduce((u,f)=>u+f.symbols.length,0);return this.logCollector.log(`${w} Index enrichment analysis completed: ${p} symbols across ${g.length} files`),g.length>0?g:null}catch(o){return this.logCollector.warn(`${C} Index enrichment failed: ${o instanceof Error?o.message:String(o)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await n.shutdownAll();}}};});function rr(s){return `name: Constellation Index
95
+ `)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.logCollector.log(`${v} Determining index scope...`);try{let r=(await this.apiClient.getProjectState())?.latestCommit;if(!r)return this.logCollector.log(`${v} No previous index found, performing full index`),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return r===o?(this.logCollector.log(`${C} Already up to date`),{isIncremental:!0,upToDate:!0}):(this.logCollector.log(`${v} Last indexed commit: ${r.substring(0,8)}`),this.logCollector.log(`${v} Current commit: ${o.substring(0,8)}`),this.logCollector.log(`${v} Performing incremental index starting from commit ${r.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof $)throw t;return this.logCollector.log(`${b} Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){this.logCollector.log(`${v} Analyzing codebase...`);let t;if(e)try{let r=await this.apiClient.getProjectState();if(!r?.latestCommit)this.logCollector.log(`${b} Cannot determine changes (no latestCommit in project state), falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let o=await this.git.getChangedFiles(r.latestCommit),s=[...o.added,...o.modified,...o.renamed.map(l=>l.to)];this.logCollector.log(`${v} Found ${s.length} changed files`),t=await this.scanner.scanSpecificFiles(s,this.config);let a=[...o.deleted,...o.renamed.map(l=>l.from)];if(a.length>0){let l=o.deleted.length,c=o.renamed.length,u=c>0?`${v} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${v} Removing ${l} deleted file(s) from graph`;this.logCollector.log(u),await this.apiClient.deleteFiles(a);}}}catch(r){if(r instanceof $)throw r;this.logCollector.log(`${b} Cannot determine changes (${r instanceof Error?r.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else this.logCollector.log(`${v} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return this.logCollector.log(`${C} Found ${t.length} files to index`),t}async*generateASTs(e,t){let r=new Date().toISOString(),o=e.length,s=0,a=0;this.logCollector.log(`${v} Processing ${o} files...`);let l=await this.git.getLatestCommitHash(),c=o>1e4?5:o>5e3?7:10;c<10&&this.logCollector.log(`${v} Large project detected, using concurrency of ${c} to optimize memory usage`);let g=new jt(c).run(e,async(d,m)=>{let h=Math.round((m+1)/o*100);this.logCollector.log(`${v} Analyzing file ${d.path.replace(process.cwd()+"/","")} (${h}%)...`);try{let{tree:y,classificationMap:S}=await this.parser.parseFile(d.path,d.language);S.entries.length>5e4&&this.logCollector.warn(`${b} Large classification map for ${d.relativePath}: ${S.entries.length} entries`);let w=this.langRegistry.getPlugin(d.language),R;if(w?.getImportResolver){let T=this.buildConfigManagers.get(d.language),se=T?await T.getConfigForFile(d.path):null,J=w.getImportResolver(d.path,se);if(J){let{ImportExtractor:Ze}=await Promise.resolve().then(()=>(di(),ui));R=await new Ze().extractImportResolutions(y,d.path,d.language,J);}}let{serializeASTStream:L}=await Promise.resolve().then(()=>(yn(),Ei)),I=L(y.rootNode,void 0,d.language),O=await this.compressor.compressStream(I),j=this.normalizePathToCanonical(d.relativePath),X={file:j,language:d.language,commit:l,timestamp:r,ast:O,importResolutions:R,classificationMap:{filePath:j,entries:S.entries}},N=ni.safeParse(X);if(!N.success)throw new Error(`AST validation failed: ${N.error.issues[0].message}`);return s++,N.data}catch(y){throw a++,this.logCollector.warn(` ${b} Failed to parse ${d.relativePath}: ${y.message}`,{code:"PARSE_FAILURE"}),y}});for await(let d of g)yield d;a>0?this.logCollector.log(`${b} Completed parsing with ${a} parsing errors`):this.logCollector.log(`${C} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,r,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,r,o))throw new Error("Failed to upload data to Constellation Service");this.logCollector.log(`${C} Data uploaded to Constellation Service, indexing in progress`);}async*createIndexPipeline(e,t,r){let o=await this.discoverFiles(e);this.discoveredFiles=o,r(o),yield*this.generateASTs(o,t);}normalizePathToCanonical(e){return lt(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||me.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.logCollector.log(`${v} Index enrichment skipped (--no-enrich flag)`),null;if(this.config.lspEnrichment===false)return this.logCollector.log(`${v} Index enrichment disabled in constellation.json`),null;let o=[...new Set(t.map(s=>s.language))].filter(s=>this.isLanguageLspEligible(s));return o.length===0?null:(this.logCollector.log(`${v} Index enrichment enabled for: ${o.map(Ae).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,r){let o=new mt(process.cwd(),this.logCollector);try{if(r?.aborted)return null;this.logCollector.log(`${v} Starting index enrichment...`);let s=new Map,a=new Map;for(let m of e){if(!t.has(m.language))continue;let h=s.get(m.language)||[];if(h.push(this.normalizePathToCanonical(m.relativePath)),s.set(m.language,h),!a.has(m.language)){let S=this.config.languages[m.language]?.lsp,x=await o.startServer(m.language,S);x&&a.set(m.language,x);}}if(a.size===0)return this.logCollector.log(`${b} No language servers started, index enrichment skipped`),null;if(r?.aborted)return o.destroyAll(),null;this.logCollector.log(`${C} Language servers started: ${[...a.keys()].map(Ae).join(", ")}`);let l=new Map,c=new ct(process.cwd()),u=r?new Promise((m,h)=>{r.addEventListener("abort",()=>{o.destroyAll(),h(r.reason||new Error("Indexing aborted"));},{once:!0});}):null,g=await(u?Promise.race([c.enrich(s,l,a),u]):c.enrich(s,l,a)),d=g.reduce((m,h)=>m+h.symbols.length,0);return this.logCollector.log(`${C} Index enrichment analysis completed: ${d} symbols across ${g.length} files`),g.length>0?g:null}catch(s){return this.logCollector.warn(`${b} Index enrichment failed: ${s instanceof Error?s.message:String(s)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await o.shutdownAll();}}};});function _n(i){return `name: Constellation Index
96
96
 
97
97
  on:
98
98
  push:
99
- branches: ["${s}"]
99
+ branches: ["${i}"]
100
100
 
101
101
  permissions:
102
102
  contents: read
@@ -110,15 +110,15 @@ jobs:
110
110
  - uses: ShiftinBits/constellation-github@v1
111
111
  with:
112
112
  access-key: \${{ secrets.CONSTELLATION_ACCESS_KEY }}
113
- `}function nr(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 St(s){return `include:
113
+ `}function Sn(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function Ft(i){return `include:
114
114
  - component: gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1
115
115
  inputs:
116
116
  access_key: $CONSTELLATION_ACCESS_KEY
117
117
 
118
118
  constellation-index:
119
119
  rules:
120
- - if: $CI_COMMIT_BRANCH == "${s}"
121
- `}var or=m(()=>{});var ke,Gn=m(()=>{z();or();ke=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,r]=await Promise.all([v.directoryExists(b__default.join(this.gitRoot,".github","workflows")),v.fileIsReadable(b__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),r&&e.push("gitlab"),e}async githubWorkflowExists(){return v.fileIsReadable(b__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=b__default.join(this.gitRoot,".gitlab-ci.yml");if(!await v.fileIsReadable(e))return false;try{let r=await v.readFile(e),o=parseDocument(r).contents;return isMap(o)&&o.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=b__default.join(this.gitRoot,".github","workflows");await U__default.mkdir(t,{recursive:true});let r=b__default.join(t,"constellation-index.yml");return await v.writeFile(r,rr(e)),r}async createOrMergeGitLabCI(e){let t=b__default.join(this.gitRoot,".gitlab-ci.yml");if(!await v.fileIsReadable(t))return await v.writeFile(t,St(e)),t;let n=await v.readFile(t),o=parseDocument(n);if(!isMap(o.contents))return await v.writeFile(t,St(e)),t;let{includeEntry:i,job:a}=nr(e);return this.mergeIncludeEntry(o,i),o.set("constellation-index",a),await v.writeFile(t,o.toString()),t}mergeIncludeEntry(e,t){let r=e.get("include");if(!r){e.set("include",[t]);return}if(isSeq(r)){let n=r.items.filter(o=>{if(isMap(o)){let i=o.get("component");return typeof i!="string"||!i.includes("constellation-gitlab")}return true});r.items=n,r.items.push(e.createNode(t));return}e.set("include",[r,t]);}};});var Wn=m(()=>{Gn();or();});function sr(){return zn}var zn,Jn=m(()=>{zn=[{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.
120
+ - if: $CI_COMMIT_BRANCH == "${i}"
121
+ `}var wn=f(()=>{});var Be,Ri=f(()=>{K();wn();Be=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,r]=await Promise.all([_.directoryExists(P__default.join(this.gitRoot,".github","workflows")),_.fileIsReadable(P__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),r&&e.push("gitlab"),e}async githubWorkflowExists(){return _.fileIsReadable(P__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await _.fileIsReadable(e))return false;try{let r=await _.readFile(e),s=parseDocument(r).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=P__default.join(this.gitRoot,".github","workflows");await B__default.mkdir(t,{recursive:true});let r=P__default.join(t,"constellation-index.yml");return await _.writeFile(r,_n(e)),r}async createOrMergeGitLabCI(e){let t=P__default.join(this.gitRoot,".gitlab-ci.yml");if(!await _.fileIsReadable(t))return await _.writeFile(t,Ft(e)),t;let o=await _.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await _.writeFile(t,Ft(e)),t;let{includeEntry:a,job:l}=Sn(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await _.writeFile(t,s.toString()),t}mergeIncludeEntry(e,t){let r=e.get("include");if(!r){e.set("include",[t]);return}if(isSeq(r)){let o=r.items.filter(s=>{if(isMap(s)){let a=s.get("component");return typeof a!="string"||!a.includes("constellation-gitlab")}return true});r.items=o,r.items.push(e.createNode(t));return}e.set("include",[r,t]);}};});var Ti=f(()=>{Ri();wn();});function En(){return $i}var $i,ki=f(()=>{$i=[{event:"SessionStart",type:"prompt",content:`You have Constellation access. \`{MCP_TOOL_NAME}\` is your PRIMARY tool for understanding this codebase\u2014not an alternative, not a fallback, THE DEFAULT.
122
122
 
123
123
  Mental model:
124
124
  - "Where is X defined?" \u2192 {MCP_TOOL_NAME}
@@ -126,7 +126,7 @@ Mental model:
126
126
  - "What would break?" \u2192 {MCP_TOOL_NAME}
127
127
  - "Find the string 'ERROR_CODE_123'" \u2192 Grep
128
128
 
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 Ii(s){return Vn[s]}var Vn,xi,Ne,ar=m(()=>{Vn={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},xi="code_intel";Ne=class{id="cline";displayName="Cline";mapEventName(e){return Vn[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,xi)}generateAuxiliaryFiles(e){let t=new Map;for(let r of e){let n=Ii(r.event);if(!n)continue;let o=`.clinerules/hooks/${n}`,i=this.generateScript(r);t.set(o,i);}return t.size>0?t:void 0}generateScript(e){let r=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return `#!/bin/bash
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 ul(i){return ji[i]}var ji,pl,He,Pn=f(()=>{ji={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},pl="code_intel";He=class{id="cline";displayName="Cline";mapEventName(e){return ji[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,pl)}generateAuxiliaryFiles(e){let t=new Map;for(let r of e){let o=ul(r.event);if(!o)continue;let s=`.clinerules/hooks/${o}`,a=this.generateScript(r);t.set(s,a);}return t.size>0?t:void 0}generateScript(e){let r=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return `#!/bin/bash
130
130
  # Constellation ${e.event} Hook for Cline
131
131
  # Generated by constellation-cli - DO NOT EDIT
132
132
  #
@@ -139,7 +139,7 @@ cat << 'CONSTELLATION_EOF'
139
139
  "contextModification": "${r}"
140
140
  }
141
141
  CONSTELLATION_EOF
142
- `}};});var Ri,$i,fe,lr=m(()=>{Ri={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},$i="constellation__code_intel",fe=class{id="cursor";displayName="Cursor";mapEventName(e){return Ri[e]}generateConfig(e){let t={};for(let r of e){let n=this.mapEventName(r.event);if(!n)continue;t[n]||(t[n]=[]);let o={type:r.type};r.type==="prompt"&&(o.prompt=this.customizePrompt(r)),r.matcher&&(o.matcher=r.matcher),t[n].push(o);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,$i)}};});function Kn(s){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[s]}.sh`}var Ti,ki,Ni,Ae,cr=m(()=>{Ti={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},ki={SessionStart:"startup",SubagentStart:"",PreCompact:""},Ni="code_intel";Ae=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return Ti[e]}generateConfig(e){let t={};for(let r of e){let n=this.mapEventName(r.event);if(!n)continue;t[n]||(t[n]=[]);let o=ki[r.event]??"",i=Kn(r.event),a=t[n].find(l=>l.matcher===o);a||(a={matcher:o,hooks:[]},t[n].push(a)),a.hooks.push({name:`constellation-${r.event.toLowerCase()}`,type:"command",command:`$GEMINI_PROJECT_DIR/.gemini/hooks/${i}`,timeout:5e3,description:`Constellation: ${this.getHookDescription(r.event)}`});}return {hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,Ni)}generateAuxiliaryFiles(e){let t=new Map;for(let r of e){if(!this.mapEventName(r.event))continue;let i=`.gemini/hooks/${Kn(r.event)}`,a=this.generateScript(r);t.set(i,a);}return t.size>0?t:void 0}generateScript(e){let r=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return e.event==="PreCompact"?`#!/bin/bash
142
+ `}};});var dl,gl,Ce,In=f(()=>{dl={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},gl="constellation__code_intel",Ce=class{id="cursor";displayName="Cursor";mapEventName(e){return dl[e]}generateConfig(e){let t={};for(let r of e){let o=this.mapEventName(r.event);if(!o)continue;t[o]||(t[o]=[]);let s={type:r.type};r.type==="prompt"&&(s.prompt=this.customizePrompt(r)),r.matcher&&(s.matcher=r.matcher),t[o].push(s);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,gl)}};});function Ai(i){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[i]}.sh`}var ml,fl,hl,Ge,Nn=f(()=>{ml={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},fl={SessionStart:"startup",SubagentStart:"",PreCompact:""},hl="code_intel";Ge=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return ml[e]}generateConfig(e){let t={};for(let r of e){let o=this.mapEventName(r.event);if(!o)continue;t[o]||(t[o]=[]);let s=fl[r.event]??"",a=Ai(r.event),l=t[o].find(c=>c.matcher===s);l||(l={matcher:s,hooks:[]},t[o].push(l)),l.hooks.push({name:`constellation-${r.event.toLowerCase()}`,type:"command",command:`$GEMINI_PROJECT_DIR/.gemini/hooks/${a}`,timeout:5e3,description:`Constellation: ${this.getHookDescription(r.event)}`});}return {hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,hl)}generateAuxiliaryFiles(e){let t=new Map;for(let r of e){if(!this.mapEventName(r.event))continue;let a=`.gemini/hooks/${Ai(r.event)}`,l=this.generateScript(r);t.set(a,l);}return t.size>0?t:void 0}generateScript(e){let r=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return e.event==="PreCompact"?`#!/bin/bash
143
143
  # Constellation ${e.event} Hook for Gemini CLI
144
144
  # Generated by constellation-cli - DO NOT EDIT
145
145
  #
@@ -162,38 +162,38 @@ cat << 'CONSTELLATION_EOF'
162
162
  }
163
163
  }
164
164
  CONSTELLATION_EOF
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 pr(s){return Ai.get(s)}var Ai,gr=m(()=>{ar();lr();cr();ar();lr();cr();Ai=new Map([["cline",new Ne],["cursor",new fe],["gemini",new Ae]]);});var Le,qn=m(()=>{z();gr();Le=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 r=pr(e.hooksConfig.adapterId);if(!r)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let n=b__default.join(this.cwd,e.hooksConfig.filePath),o=r.generateConfig(t),i=Object.keys(o).some(l=>{let d=o[l];return d!=null&&(typeof d!="object"||Object.keys(d).length>0)});if(i){await this.ensureDirectoryExists(n);let l=await this.readConfig(n),d=this.mergeHooksConfig(l,o);await this.writeConfig(n,d);}let a;if(r.generateAuxiliaryFiles){let l=r.generateAuxiliaryFiles(t);l&&(await this.writeAuxiliaryFiles(l),a=Array.from(l.keys()));}return {toolId:e.id,toolDisplayName:e.displayName,success:!0,configuredPath:i?n:void 0,auxiliaryPaths:a}}catch(n){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:n instanceof Error?n.message:String(n)}}}async ensureDirectoryExists(e){let t=b__default.dirname(e);await U__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await v.fileIsReadable(e))return {};let r=await v.readFile(e);return JSON.parse(r)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let r=e.hooks??{},n=t.hooks??{},o={...r,...n},i={...e,hooks:o};return t.version!==void 0&&(i.version=t.version),i}async writeConfig(e,t){let r=JSON.stringify(t,null," ");r=r.replace(/\r\n/g,`
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 Rn(i){return yl.get(i)}var yl,Tn=f(()=>{Pn();In();Nn();Pn();In();Nn();yl=new Map([["cline",new He],["cursor",new Ce],["gemini",new Ge]]);});var We,Fi=f(()=>{K();Tn();We=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 r=Rn(e.hooksConfig.adapterId);if(!r)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let o=P__default.join(this.cwd,e.hooksConfig.filePath),s=r.generateConfig(t),a=Object.keys(s).some(c=>{let u=s[c];return u!=null&&(typeof u!="object"||Object.keys(u).length>0)});if(a){await this.ensureDirectoryExists(o);let c=await this.readConfig(o),u=this.mergeHooksConfig(c,s);await this.writeConfig(o,u);}let l;if(r.generateAuxiliaryFiles){let c=r.generateAuxiliaryFiles(t);c&&(await this.writeAuxiliaryFiles(c),l=Array.from(c.keys()));}return {toolId:e.id,toolDisplayName:e.displayName,success:!0,configuredPath:a?o:void 0,auxiliaryPaths:l}}catch(o){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:o instanceof Error?o.message:String(o)}}}async ensureDirectoryExists(e){let t=P__default.dirname(e);await B__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await _.fileIsReadable(e))return {};let r=await _.readFile(e);return JSON.parse(r)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let r=e.hooks??{},o=t.hooks??{},s={...r,...o},a={...e,hooks:s};return t.version!==void 0&&(a.version=t.version),a}async writeConfig(e,t){let r=JSON.stringify(t,null," ");r=r.replace(/\r\n/g,`
166
166
  `),r.endsWith(`
167
167
  `)||(r+=`
168
- `),await v.writeFile(e,r);}async writeAuxiliaryFiles(e){for(let[t,r]of e){let n=b__default.join(this.cwd,t);await this.ensureDirectoryExists(n);let o=r.replace(/\r\n/g,`
169
- `);o.endsWith(`
168
+ `),await _.writeFile(e,r);}async writeAuxiliaryFiles(e){for(let[t,r]of e){let o=P__default.join(this.cwd,t);await this.ensureDirectoryExists(o);let s=r.replace(/\r\n/g,`
169
+ `);s.endsWith(`
170
+ `)||(s+=`
171
+ `),await _.writeFile(o,s),(t.endsWith(".sh")||s.startsWith("#!"))&&await B__default.chmod(o,493);}}};});var Oi=f(()=>{ki();Fi();Tn();});function Di(i,e){let t=xe__default.homedir(),r=process.platform,o=vl[i];switch(r){case "darwin":return P__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return P__default.join(process.env.APPDATA||P__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return P__default.join(t,".config",o,"User/globalStorage",e)}}function Mi(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:P__default.join(Di(t,i),"settings","cline_mcp_settings.json")}))}function Ui(){return P__default.join(Di("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var vl,Bi=f(()=>{vl={stable:"Code",insiders:"Code - Insiders"};});function jn(i){return kn.find(e=>e.id===i)}var Hi,Cl,kn,An=f(()=>{Bi();Hi={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Cl={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},kn=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",skipMcpServer:true,permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:Cl},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Ui(),isGlobalConfig:true,getGlobalConfigPaths:Mi,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 Gi(){if(!Ln)try{let i=await import('@iarna/toml');Ln={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Ln}function wl(i){let e="",t=0,r=i.length;for(;t<r;)if(i[t]==='"'){for(e+='"',t++;t<r&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<r&&(e+=i[t++])):e+=i[t++];t<r&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<r&&i[t+1]==="/")for(t+=2;t<r&&i[t]!==`
172
+ `;)t++;else if(i[t]==="/"&&t+1<r&&i[t+1]==="*"){for(t+=2;t<r&&!(i[t]==="*"&&t+1<r&&i[t+1]==="/");)t++;t<r&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Ln,Ot,Wi=f(()=>{K();An();Ln=null;Ot=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=P__default.join(this.cwd,e.configPath),r=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(r){await this.ensureDirectoryExists(t);let s=await this.readConfig(t,e.format);if(e.configDefaults)for(let[a,l]of Object.entries(e.configDefaults))a in s||(s[a]=l);e.pluginConfig&&(s=this.addPluginToArray(s,e.pluginConfig)),e.skipMcpServer||(s=this.addConstellationServer(s,e),await this.configureEnvPolicy(s,e)),await this.writeConfig(t,s,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let o;return r?o=t:e.permissionsConfig?o=P__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=P__default.join(this.cwd,e.marketplaceConfig.filePath):o=t,{tool:e,success:!0,configuredPath:o}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),r=[];for(let{displayName:o,settingsPath:s}of t)try{await this.ensureDirectoryExists(s);let a=await this.readConfig(s,e.format);a=this.addConstellationServer(a,e),await this.writeConfig(s,a,e.format),r.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:s});}catch(a){let l=a instanceof Error?a.message:String(a);l.includes("ENOENT")||l.includes("no such file")||r.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:l});}return r}async ensureDirectoryExists(e){let t=P__default.dirname(e);await B__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await _.fileIsReadable(e))return {};let o=await _.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(wl(o)):(await Gi()).parse(o)}catch{return {}}}addConstellationServer(e,t){let r=e;for(let a=0;a<t.mcpServersKeyPath.length-1;a++){let l=t.mcpServersKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!r[o]||typeof r[o]!="object")&&(r[o]={});let s=r[o];if(!s.constellation){let a=t.mcpServerConfigOverride??Hi,l={...a};if(t.mcpServerExtras&&Object.assign(l,t.mcpServerExtras),t.mcpEnv){let c=t.mcpEnvKey??"env",u=a[c];l[c]={...u,...t.mcpEnv};}s.constellation=l;}return e}async writeConfig(e,t,r){let o;r==="json"||r==="jsonc"?o=JSON.stringify(t,null,2):o=(await Gi()).stringify(t),o=o.replace(/\r\n/g,`
173
+ `),o.endsWith(`
170
174
  `)||(o+=`
171
- `),await v.writeFile(n,o),(t.endsWith(".sh")||o.startsWith("#!"))&&await U__default.chmod(n,493);}}};});var Xn=m(()=>{Jn();qn();gr();});function Qn(s,e){let t=Ce__default.homedir(),r=process.platform,n=ji[s];switch(r){case "darwin":return b__default.join(t,"Library/Application Support",n,"User/globalStorage",e);case "win32":return b__default.join(process.env.APPDATA||b__default.join(t,"AppData/Roaming"),n,"User/globalStorage",e);default:return b__default.join(t,".config",n,"User/globalStorage",e)}}function Zn(){let s="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:b__default.join(Qn(t,s),"settings","cline_mcp_settings.json")}))}function eo(){return b__default.join(Qn("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var ji,to=m(()=>{ji={stable:"Code",insiders:"Code - Insiders"};});function fr(s){return ur.find(e=>e.id===s)}var ro,Oi,ur,mr=m(()=>{to();ro={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Oi={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},ur=[{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:Oi},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:eo(),isGlobalConfig:true,getGlobalConfigPaths:Zn,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 no(){if(!hr)try{let s=await import('@iarna/toml');hr={parse:s.parse,stringify:s.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return hr}function Mi(s){let e="",t=0,r=s.length;for(;t<r;)if(s[t]==='"'){for(e+='"',t++;t<r&&s[t]!=='"';)s[t]==="\\"?(e+=s[t++],t<r&&(e+=s[t++])):e+=s[t++];t<r&&(e+=s[t++]);}else if(s[t]==="/"&&t+1<r&&s[t+1]==="/")for(t+=2;t<r&&s[t]!==`
172
- `;)t++;else if(s[t]==="/"&&t+1<r&&s[t+1]==="*"){for(t+=2;t<r&&!(s[t]==="*"&&t+1<r&&s[t+1]==="/");)t++;t<r&&(t+=2);}else e+=s[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var hr,bt,oo=m(()=>{z();mr();hr=null;bt=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=b__default.join(this.cwd,e.configPath),r=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(r){await this.ensureDirectoryExists(t);let o=await this.readConfig(t,e.format);if(e.configDefaults)for(let[i,a]of Object.entries(e.configDefaults))i in o||(o[i]=a);e.pluginConfig&&(o=this.addPluginToArray(o,e.pluginConfig)),e.skipMcpServer||(o=this.addConstellationServer(o,e),await this.configureEnvPolicy(o,e)),await this.writeConfig(t,o,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let n;return r?n=t:e.permissionsConfig?n=b__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?n=b__default.join(this.cwd,e.marketplaceConfig.filePath):n=t,{tool:e,success:!0,configuredPath:n}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),r=[];for(let{displayName:n,settingsPath:o}of t)try{await this.ensureDirectoryExists(o);let i=await this.readConfig(o,e.format);i=this.addConstellationServer(i,e),await this.writeConfig(o,i,e.format),r.push({tool:{...e,displayName:`${e.displayName} (${n})`},success:!0,configuredPath:o});}catch(i){let a=i instanceof Error?i.message:String(i);a.includes("ENOENT")||a.includes("no such file")||r.push({tool:{...e,displayName:`${e.displayName} (${n})`},success:false,error:a});}return r}async ensureDirectoryExists(e){let t=b__default.dirname(e);await U__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await v.fileIsReadable(e))return {};let n=await v.readFile(e);return t==="json"?JSON.parse(n):t==="jsonc"?JSON.parse(Mi(n)):(await no()).parse(n)}catch{return {}}}addConstellationServer(e,t){let r=e;for(let i=0;i<t.mcpServersKeyPath.length-1;i++){let a=t.mcpServersKeyPath[i];(!r[a]||typeof r[a]!="object")&&(r[a]={}),r=r[a];}let n=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!r[n]||typeof r[n]!="object")&&(r[n]={});let o=r[n];if(!o.constellation){let i=t.mcpServerConfigOverride??ro,a={...i};if(t.mcpServerExtras&&Object.assign(a,t.mcpServerExtras),t.mcpEnv){let l=t.mcpEnvKey??"env",d=i[l];a[l]={...d,...t.mcpEnv};}o.constellation=a;}return e}async writeConfig(e,t,r){let n;r==="json"||r==="jsonc"?n=JSON.stringify(t,null,2):n=(await no()).stringify(t),n=n.replace(/\r\n/g,`
173
- `),n.endsWith(`
174
- `)||(n+=`
175
- `),await v.writeFile(e,n);}async configurePermissions(e){let t=b__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await v.fileIsReadable(t)){let l=await v.readFile(t);r=JSON.parse(l);}}catch{}let n=r;for(let a=0;a<e.allowKeyPath.length-1;a++){let l=e.allowKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let i=n[o];i.includes(e.allowValue)||i.push(e.allowValue),await v.writeFile(t,JSON.stringify(r,null," ")+`
176
- `);}async configureMarketplace(e){let t=b__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await v.fileIsReadable(t)){let o=await v.readFile(t);r=JSON.parse(o);}}catch{}r=this.deepMerge(r,e.config),await v.writeFile(t,JSON.stringify(r,null," ")+`
177
- `);}deepMerge(e,t){let r={...e};for(let n of Object.keys(t)){let o=t[n],i=e[n];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?r[n]=this.deepMerge(i,o):r[n]=o;}return r}addPluginToArray(e,t){let r=e;for(let i=0;i<t.pluginKeyPath.length-1;i++){let a=t.pluginKeyPath[i];(!r[a]||typeof r[a]!="object")&&(r[a]={}),r=r[a];}let n=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(r[n])||(r[n]=[]);let o=r[n];return o.includes(t.pluginValue)||o.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:r,envVarsToAllow:n,globalConfigPath:o}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,r,n),o&&await this.updateGlobalEnvPolicy(o,r,n,t.format);}addToEnvPolicyWhitelist(e,t,r){let n=e;for(let a=0;a<t.length-1;a++){let l=t[a];if(!n[l]||typeof n[l]!="object")return;n=n[l];}let o=t[t.length-1];if(!Array.isArray(n[o]))return;let i=n[o];for(let a of r)i.includes(a)||i.push(a);}async updateGlobalEnvPolicy(e,t,r,n){let o=e.replace(/^~/,Ce__default.homedir()),i=await this.readConfig(o,n);if(Object.keys(i).length===0)return;let a=JSON.stringify(i);this.addToEnvPolicyWhitelist(i,t,r);let l=JSON.stringify(i);a!==l&&await this.writeConfig(o,i,n);}};});function ye(s,e){let t=b__default.normalize(s),r=b__default.normalize(e);return t.startsWith(r+b__default.sep)?b__default.relative(e,s):s}var zi,Oe,ao=m(()=>{Wn();nt();Xn();ft();oo();mr();z();D();qe();Ke();zi=promisify(execFile);Oe=class extends Z{async run(e={}){try{if(console.log(`${Y}Initializing project configuration...
178
- `),!await this.git.isGitAvailable())throw new Error(`${C} Could not find git client installation.
179
- ${y} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let r=b__default.join(process.cwd(),"constellation.json"),n=null,o=await v.fileIsReadable(r);if(o)try{let x=await v.readFile(r);n=JSON.parse(x),console.log(`${y} Found existing constellation.json, current values will be used as defaults.
180
- `);}catch{console.log(`${C} Existing constellation.json is invalid, starting fresh.
181
- `);}if(!await this.git.isGitRepository())throw new Error(`${C} Current directory is not a git repository.
182
- ${y} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[l,d]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:g}=l,p=d.filter(x=>x!==g),u=g?[g,...p]:p,f=await input({message:"Constellation Project ID:",default:n?.projectId??"",validate:x=>x.trim().length>0||"Project ID is required",theme:N}),h=await select({message:"Branch to index:",choices:u.map(x=>({name:x,value:x})),default:n?.branch??u[0],theme:N}),I=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(n),required:!0,theme:N})).reduce((x,A)=>(x[A]={fileExtensions:be[A]||[]},x),{});console.log(""),console.log(`${y} Checking for LSP servers...`);for(let[x,A]of Object.entries(I)){let T=ge.get(x);if(!T)continue;let K=!1,R="";if(et(T.command)&&(K=!0,R="system"),!K){let k=b__default.join(rt,T.command);existsSync(k)&&(K=!0,R="managed");}if(K)console.log(` ${w} ${x}: Found ${T.command} (${R})`),A.lsp={command:T.command,args:T.args};else if(await confirm({message:`${x}: ${T.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:N}))try{console.log(` ${y} Installing ${T.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",Dt,...T.npmPackages],{stdio:"pipe"}),console.log(` ${w} ${x}: Installed ${T.command}`),A.lsp={command:T.command,args:T.args};}catch{console.log(` ${S} ${x}: Installation failed`),A.lspEnrichment=!1;}else A.lspEnrichment=!1;}let P=Object.entries(I).filter(([,x])=>x.lspEnrichment!==!1).map(([x])=>x);P.length>0?console.log(`${w} Index enrichment enabled for: ${P.map(Pe).join(", ")}`):console.log(`${C} No language servers configured. Index enrichment will be skipped.`);let j={projectId:f.trim(),branch:h,languages:{...I},...P.length>0&&{lspEnrichment:!0}},E=JSON.stringify(j,void 0,2);await v.writeFile(r,E),console.log(`${w} ${o?"Updated":"Initialized"} configuration file at ${ye(r,process.cwd())}`),await this.git.stageFile(r),console.log(`${w} 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 r=t.message??"An unexpected error occurred";console.error(`${S} Failed to initialize configuration file.
183
- ${r}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:N}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:ur.map(g=>({name:g.displayName,value:g.id})),required:true,theme:N}),r=new bt(process.cwd()),n=[];for(let g of t){let p=fr(g);if(p)if(console.log(` ${y} Configuring ${p.displayName}...`),p.pluginInstallCommand){let u=await this.executePluginInstall(p);n.push(u),u.success?console.log(` ${w} ${p.displayName} plugin installed successfully`):console.log(` ${C} ${p.displayName}: ${u.error}`);}else if(p.isGlobalConfig&&p.getGlobalConfigPaths){let u=await r.configureGlobalTool(p),f=false;for(let h of u)n.push(h),h.success?(f=true,console.log(` ${w} ${h.tool.displayName} configured at ${ye(h.configuredPath,process.cwd())}`)):h.error&&console.log(` ${C} ${h.tool.displayName}: ${h.error}`);if(f){let h=p.id==="cline"?"global VS Code settings":"global settings";console.log(` ${y} Note: ${p.displayName} uses ${h} (not project-level)`);}if(u.length===0){let h=p.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${C} ${p.displayName}: ${h}`);}}else {let u=await r.configureTool(p);n.push(u),u.success?(console.log(` ${w} ${p.displayName} configured at ${ye(u.configuredPath,process.cwd())}`),p.permissionsConfig&&console.log(` ${w} ${p.displayName} permissions set in ${p.permissionsConfig.filePath}`)):console.log(` ${C} ${p.displayName}: ${u.error}`);}}if(n.find(g=>g.tool.id==="claude-code"&&g.success)){let g=b__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(g),console.log(` ${w} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${C} Could not stage .claude/settings.json in git`);}}if(n.find(g=>g.tool.id==="codex-cli"&&g.success)){let g=b__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(g),console.log(` ${w} Added .codex/config.toml to staged changes in git`);}catch{}}if(n.find(g=>g.tool.id==="opencode"&&g.success)){let g=b__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(g),console.log(` ${w} Added opencode.jsonc to staged changes in git`);}catch{}}let l=n.filter(g=>g.success).length,d=n.filter(g=>!g.success).length;console.log(`
184
- ${w} Plugin + MCP configuration complete: ${l} configured`),d>0&&console.log(`${C} ${d} tool(s) could not be configured`),await this.configureHooks(t,n),console.log(`
185
- ${y} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let r=new Le(process.cwd()),n=sr(),o=e.map(l=>fr(l)).filter(l=>l!==void 0&&l.hooksConfig!==void 0&&t.some(d=>d.tool.id===l.id&&d.success));if(o.length===0)return;console.log(`
186
- ${y} Configuring AI hooks...`);let i=[];for(let l of o){let d=await r.configureHooks(l,n);if(i.push(d),d.success){let g=d.configuredPath?[d.configuredPath]:d.auxiliaryPaths??[];if(g.length>0){let p=d.configuredPath?ye(d.configuredPath,process.cwd()):b__default.dirname(g[0]);console.log(` ${w} ${l.displayName} hooks configured at ${p}`);for(let u of g){let f=b__default.isAbsolute(u)?ye(u,process.cwd()):u;try{await this.git.stageFile(u),console.log(` ${w} Added ${f} to staged changes in git`);}catch{console.log(` ${C} Could not stage ${f} in git`);}}}else console.log(` ${w} ${l.displayName} hooks configured`);}else console.log(` ${C} ${l.displayName}: ${d.error}`);}let a=i.filter(l=>l.success).length;a>0&&console.log(`${w} Hooks configuration complete: ${a} configured`);}async executePluginInstall(e){let{command:t,args:r}=e.pluginInstallCommand;try{return await zi(t,r,{timeout:3e4,env:process.env}),{tool:e,success:!0}}catch(n){let o=n,i;return o.code==="ENOENT"?i=`${t} not found. Is ${e.displayName} installed and on your PATH?`:o.killed?i="Plugin installation timed out after 30 seconds":o.stderr?i=`Plugin installation failed: ${o.stderr.trim()}`:i=`Plugin installation failed: ${o.message}`,{tool:e,success:false,error:i}}}async configureCICD(e,t){if(!await confirm({message:"Set up a CI/CD pipeline to automatically index your project?",default:true,theme:N}))return;let n=new ke(t),o=await n.detectPlatforms(),i;if(o.length===1){let g=o[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${g}. Configure Constellation CI/CD for this platform?`,default:true,theme:N}))return;i=o[0];}else i=await select({message:"Select CI/CD platform:",choices:[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],theme:N});let a=i==="github"?await n.githubWorkflowExists():await n.gitlabJobExists();if(a&&!await confirm({message:"Constellation CI/CD configuration already exists. Overwrite?",default:false,theme:N})){console.log(`${y} Skipping CI/CD configuration`);return}let l;try{l=i==="github"?await n.createGitHubWorkflow(e):await n.createOrMergeGitLabCI(e);}catch(g){console.log(`${C} Failed to configure CI/CD pipeline: ${g.message}`);return}let d=ye(l,process.cwd());console.log(i==="github"?`${w} Created ${d}`:`${w} ${a?"Updated":"Created"} ${d} with Constellation indexing`);try{await this.git.stageFile(l),console.log(`${w} Added ${d} to staged changes in git`);}catch{console.log(`${C} Could not stage ${d} in git`);}i==="github"?(console.log(`${y} 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(`${y} 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(r=>({...r,checked:t.includes(r.value)}))}};});var Pt,lo=m(()=>{Ve();Ct();z();D();Pt=class s{constructor(e,t,r,n,o){this.branch=e;this.languages=t;this.projectId=r;this.exclude=n;this.lspEnrichment=o;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await v.fileIsReadable(e)){let r=await v.readFile(e),n=JSON.parse(r),o=new s(n.branch,n.languages,n.projectId,n.exclude,n.lspEnrichment);return o.validate(),o}else throw new Error(`${S} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let r of t.fileExtensions)if(!r.startsWith("."))throw new Error(`Invalid configuration: file extension "${r}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new X("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new X(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var xt,Cr,wr,vr,It,po=m(()=>{z();xt=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,"\\$&")}},Cr=class extends xt{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((r,n)=>{let o=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),i="";o.stderr?.on("data",a=>{i+=a.toString();}),o.on("close",a=>{a===0?r():n(new Error(`setx failed with code ${a}: ${i}`));}),o.on("error",a=>{n(a);});}),process.env[e]=t;}catch(r){throw new Error(`Failed to set environment variable ${e}: ${r}`)}}async queryRegistry(e,t){try{let n=(await new Promise((o,i)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),l="",d="";a.stdout?.on("data",g=>{l+=g.toString();}),a.stderr?.on("data",g=>{d+=g.toString();}),a.on("close",g=>{g===0?o(l):i(new Error(`reg query failed: ${d}`));}),a.on("error",g=>{i(g);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return n?n[1].trim():void 0}catch{return}}},wr=class extends xt{userConfigFiles;constructor(){super(),this.userConfigFiles=[b.join(Ce.homedir(),".zshenv"),b.join(Ce.homedir(),".profile")];}getSourceFile(){let e=process.env.SHELL??"";return e.endsWith("/zsh")||e.endsWith("/zsh5")?this.userConfigFiles.find(t=>t.endsWith(".zshenv")):this.userConfigFiles.find(t=>t.endsWith(".profile"))}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
189
- Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let r=this.escapeShellValue(t),n=`export ${e}="${r}"`;try{for(let o of this.userConfigFiles)await this.writeToConfigFile(o,e,n);process.env[e]=t;}catch(o){throw new Error(`Failed to set environment variable ${e}: ${o}`)}}async writeToConfigFile(e,t,r){let n="";try{n=await v.readFile(e,"utf-8");}catch{}let o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^export ${o}=.*$`,"gm");i.test(n)?n=n.replace(i,r):n=n.trimEnd()+`
175
+ `),await _.writeFile(e,o);}async configurePermissions(e){let t=P__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await _.fileIsReadable(t)){let c=await _.readFile(t);r=JSON.parse(c);}}catch{}let o=r;for(let l=0;l<e.allowKeyPath.length-1;l++){let c=e.allowKeyPath[l];(!o[c]||typeof o[c]!="object")&&(o[c]={}),o=o[c];}let s=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(o[s])||(o[s]=[]);let a=o[s];a.includes(e.allowValue)||a.push(e.allowValue),await _.writeFile(t,JSON.stringify(r,null," ")+`
176
+ `);}async configureMarketplace(e){let t=P__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let r={};try{if(await _.fileIsReadable(t)){let s=await _.readFile(t);r=JSON.parse(s);}}catch{}r=this.deepMerge(r,e.config),await _.writeFile(t,JSON.stringify(r,null," ")+`
177
+ `);}deepMerge(e,t){let r={...e};for(let o of Object.keys(t)){let s=t[o],a=e[o];s&&typeof s=="object"&&!Array.isArray(s)&&a&&typeof a=="object"&&!Array.isArray(a)?r[o]=this.deepMerge(a,s):r[o]=s;}return r}addPluginToArray(e,t){let r=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(r[o])||(r[o]=[]);let s=r[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:r,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,r,o),s&&await this.updateGlobalEnvPolicy(s,r,o,t.format);}addToEnvPolicyWhitelist(e,t,r){let o=e;for(let l=0;l<t.length-1;l++){let c=t[l];if(!o[c]||typeof o[c]!="object")return;o=o[c];}let s=t[t.length-1];if(!Array.isArray(o[s]))return;let a=o[s];for(let l of r)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,r,o){let s=e.replace(/^~/,xe__default.homedir()),a=await this.readConfig(s,o);if(Object.keys(a).length===0)return;let l=JSON.stringify(a);this.addToEnvPolicyWhitelist(a,t,r);let c=JSON.stringify(a);l!==c&&await this.writeConfig(s,a,o);}};});function we(i,e){let t=P__default.normalize(i),r=P__default.normalize(e);return t.startsWith(r+P__default.sep)?P__default.relative(e,i):i}var Rl,Ke,Ji=f(()=>{Ti();gt();Oi();Et();Wi();An();K();D();at();ot();Rl=promisify(execFile);Ke=class extends ne{async run(e={}){try{if(console.log(`${Q}Initializing project configuration...
178
+ `),!await this.git.isGitAvailable())throw new Error(`${b} Could not find git client installation.
179
+ ${v} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let r=P__default.join(process.cwd(),"constellation.json"),o=null,s=await _.fileIsReadable(r);if(s)try{let I=await _.readFile(r);o=JSON.parse(I),console.log(`${v} Found existing constellation.json, current values will be used as defaults.
180
+ `);}catch{console.log(`${b} Existing constellation.json is invalid, starting fresh.
181
+ `);}if(!await this.git.isGitRepository())throw new Error(`${b} Current directory is not a git repository.
182
+ ${v} Please run this command from the root directory of a git repository.`);let l=await this.git.getRootDir(),[c,u]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:g}=c,d=u.filter(I=>I!==g),m=g?[g,...d]:d,h=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:I=>I.trim().length>0||"Project ID is required",theme:A}),y=await select({message:"Branch to index:",choices:m.map(I=>({name:I,value:I})),default:o?.branch??m[0],theme:A}),x=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:A})).reduce((I,O)=>(I[O]={fileExtensions:je[O]||[]},I),{});console.log(""),console.log(`${v} Checking for LSP servers...`);for(let[I,O]of Object.entries(x)){let j=me.get(I);if(!j)continue;let X=!1,N="";if(pt(j.command)&&(X=!0,N="system"),!X){let T=P__default.join(dt,j.command);existsSync(T)&&(X=!0,N="managed");}if(X)console.log(` ${C} ${I}: Found ${j.command} (${N})`),O.lsp={command:j.command,args:j.args};else if(await confirm({message:`${I}: ${j.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:A}))try{console.log(` ${v} Installing ${j.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",Qt,...j.npmPackages],{stdio:"pipe"}),console.log(` ${C} ${I}: Installed ${j.command}`),O.lsp={command:j.command,args:j.args};}catch{console.log(` ${E} ${I}: Installation failed`),O.lspEnrichment=!1;}else O.lspEnrichment=!1;}let w=Object.entries(x).filter(([,I])=>I.lspEnrichment!==!1).map(([I])=>I);w.length>0?console.log(`${C} Index enrichment enabled for: ${w.map(Ae).join(", ")}`):console.log(`${b} No language servers configured. Index enrichment will be skipped.`);let R={projectId:h.trim(),branch:y,languages:{...x},...w.length>0&&{lspEnrichment:!0}},L=JSON.stringify(R,void 0,2);await _.writeFile(r,L),console.log(`${C} ${s?"Updated":"Initialized"} configuration file at ${we(r,process.cwd())}`),await this.git.stageFile(r),console.log(`${C} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&l&&await this.configureCICD(y,l);}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let r=t.message??"An unexpected error occurred";console.error(`${E} Failed to initialize configuration file.
183
+ ${r}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:A}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:kn.map(g=>({name:g.displayName,value:g.id})),required:true,theme:A}),r=new Ot(process.cwd()),o=[];for(let g of t){let d=jn(g);if(d)if(console.log(` ${v} Configuring ${d.displayName}...`),d.pluginInstallCommand){let m=await this.executePluginInstall(d);o.push(m),m.success?console.log(` ${C} ${d.displayName} plugin installed successfully`):console.log(` ${b} ${d.displayName}: ${m.error}`);}else if(d.isGlobalConfig&&d.getGlobalConfigPaths){let m=await r.configureGlobalTool(d),h=false;for(let y of m)o.push(y),y.success?(h=true,console.log(` ${C} ${y.tool.displayName} configured at ${we(y.configuredPath,process.cwd())}`)):y.error&&console.log(` ${b} ${y.tool.displayName}: ${y.error}`);if(h){let y=d.id==="cline"?"global VS Code settings":"global settings";console.log(` ${v} Note: ${d.displayName} uses ${y} (not project-level)`);}if(m.length===0){let y=d.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${b} ${d.displayName}: ${y}`);}}else {let m=await r.configureTool(d);o.push(m),m.success?(console.log(` ${C} ${d.displayName} configured at ${we(m.configuredPath,process.cwd())}`),d.permissionsConfig&&console.log(` ${C} ${d.displayName} permissions set in ${d.permissionsConfig.filePath}`)):console.log(` ${b} ${d.displayName}: ${m.error}`);}}if(o.find(g=>g.tool.id==="claude-code"&&g.success)){let g=P__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(g),console.log(` ${C} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${b} Could not stage .claude/settings.json in git`);}}if(o.find(g=>g.tool.id==="codex-cli"&&g.success)){let g=P__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(g),console.log(` ${C} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(g=>g.tool.id==="opencode"&&g.success)){let g=P__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(g),console.log(` ${C} Added opencode.jsonc to staged changes in git`);}catch{}}let c=o.filter(g=>g.success).length,u=o.filter(g=>!g.success).length;console.log(`
184
+ ${C} Plugin + MCP configuration complete: ${c} configured`),u>0&&console.log(`${b} ${u} tool(s) could not be configured`),await this.configureHooks(t,o),console.log(`
185
+ ${v} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let r=new We(process.cwd()),o=En(),s=e.map(c=>jn(c)).filter(c=>c!==void 0&&c.hooksConfig!==void 0&&t.some(u=>u.tool.id===c.id&&u.success));if(s.length===0)return;console.log(`
186
+ ${v} Configuring AI hooks...`);let a=[];for(let c of s){let u=await r.configureHooks(c,o);if(a.push(u),u.success){let g=u.configuredPath?[u.configuredPath]:u.auxiliaryPaths??[];if(g.length>0){let d=u.configuredPath?we(u.configuredPath,process.cwd()):P__default.dirname(g[0]);console.log(` ${C} ${c.displayName} hooks configured at ${d}`);for(let m of g){let h=P__default.isAbsolute(m)?we(m,process.cwd()):m;try{await this.git.stageFile(m),console.log(` ${C} Added ${h} to staged changes in git`);}catch{console.log(` ${b} Could not stage ${h} in git`);}}}else console.log(` ${C} ${c.displayName} hooks configured`);}else console.log(` ${b} ${c.displayName}: ${u.error}`);}let l=a.filter(c=>c.success).length;l>0&&console.log(`${C} Hooks configuration complete: ${l} configured`);}async executePluginInstall(e){let{command:t,args:r}=e.pluginInstallCommand;try{return await Rl(t,r,{timeout:3e4,env:process.env}),{tool:e,success:!0}}catch(o){let s=o,a;return s.code==="ENOENT"?a=`${t} not found. Is ${e.displayName} installed and on your PATH?`:s.killed?a="Plugin installation timed out after 30 seconds":s.stderr?a=`Plugin installation failed: ${s.stderr.trim()}`:a=`Plugin installation failed: ${s.message}`,{tool:e,success:false,error:a}}}async configureCICD(e,t){if(!await confirm({message:"Set up a CI/CD pipeline to automatically index your project?",default:true,theme:A}))return;let o=new Be(t),s=await o.detectPlatforms(),a;if(s.length===1){let g=s[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${g}. Configure Constellation CI/CD for this platform?`,default:true,theme:A}))return;a=s[0];}else a=await select({message:"Select CI/CD platform:",choices:[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],theme:A});let l=a==="github"?await o.githubWorkflowExists():await o.gitlabJobExists();if(l&&!await confirm({message:"Constellation CI/CD configuration already exists. Overwrite?",default:false,theme:A})){console.log(`${v} Skipping CI/CD configuration`);return}let c;try{c=a==="github"?await o.createGitHubWorkflow(e):await o.createOrMergeGitLabCI(e);}catch(g){console.log(`${b} Failed to configure CI/CD pipeline: ${g.message}`);return}let u=we(c,process.cwd());console.log(a==="github"?`${C} Created ${u}`:`${C} ${l?"Updated":"Created"} ${u} with Constellation indexing`);try{await this.git.stageFile(c),console.log(`${C} Added ${u} to staged changes in git`);}catch{console.log(`${b} Could not stage ${u} in git`);}a==="github"?(console.log(`${v} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${v} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(r=>({...r,checked:t.includes(r.value)}))}};});var Dt,Vi=f(()=>{it();$t();K();D();Dt=class i{constructor(e,t,r,o,s){this.branch=e;this.languages=t;this.projectId=r;this.exclude=o;this.lspEnrichment=s;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await _.fileIsReadable(e)){let r=await _.readFile(e),o=JSON.parse(r),s=new i(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${E} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let r of t.fileExtensions)if(!r.startsWith("."))throw new Error(`Invalid configuration: file extension "${r}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new ee("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new ee(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var Mt,On,Dn,Mn,Ut,qi=f(()=>{K();Mt=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,"\\$&")}},On=class extends Mt{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((r,o)=>{let s=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0?r():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(r){throw new Error(`Failed to set environment variable ${e}: ${r}`)}}async queryRegistry(e,t){try{let o=(await new Promise((s,a)=>{let l=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",u="";l.stdout?.on("data",g=>{c+=g.toString();}),l.stderr?.on("data",g=>{u+=g.toString();}),l.on("close",g=>{g===0?s(c):a(new Error(`reg query failed: ${u}`));}),l.on("error",g=>{a(g);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},Dn=class extends Mt{userConfigFiles;constructor(){super(),this.userConfigFiles=[P.join(xe.homedir(),".zshenv"),P.join(xe.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 r=this.escapeShellValue(t),o=`export ${e}="${r}"`;try{for(let s of this.userConfigFiles)await this.writeToConfigFile(s,e,o);process.env[e]=t;}catch(s){throw new Error(`Failed to set environment variable ${e}: ${s}`)}}async writeToConfigFile(e,t,r){let o="";try{o=await _.readFile(e,"utf-8");}catch{}let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^export ${s}=.*$`,"gm");a.test(o)?o=o.replace(a,r):o=o.trimEnd()+`
190
190
  `+r+`
191
- `,await v.writeFile(e,n);}},vr=class{static create(){let e=Ce.platform();switch(e){case "win32":return new Cr;case "darwin":case "linux":return new wr;default:throw new Error(`Unsupported platform: ${e}`)}}},It=class{manager;constructor(){this.manager=vr.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 Rt,go=m(()=>{Rt=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,r]of Object.entries(e.languages))for(let n of r.fileExtensions)this.extensionToLanguageMap.set(n,t);}detectLanguage(e){let t=b__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function Vi(){let s=Ce.platform();if(s==="darwin")return b.join(Ce.homedir(),"Library","Caches","constellation");if(s==="win32"){let e=process.env.LOCALAPPDATA||b.join(Ce.homedir(),"AppData","Local");return b.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||b.join(Ce.homedir(),".cache");return b.join(e,"constellation")}}var Ki,Yi,qi,De,_r=m(()=>{Ki=Vi(),Yi="update-state.json",qi=1440*60*1e3,De=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??Ki,this.stateFile=b.join(this.stateDir,Yi);}async load(){if(this.state)return this.state;try{let e=await U.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await U.mkdir(this.stateDir,{recursive:!0}),await U.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>qi}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 U.unlink(this.stateFile),this.state=null;}catch{}}};});var Me,Er=m(()=>{Me=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...r]=this.getUpdateCommand(e);return new Promise(n=>{let o=spawn(t,r,{stdio:"inherit",shell:process.platform==="win32"});o.on("close",i=>{n(i===0);}),o.on("error",()=>{n(false);});})}};});var Ue,Sr=m(()=>{Ke();D();Ue=class{async promptForUpdate(e,t,r){console.log(""),console.log(c.cyan("\u2501".repeat(60))),console.log(`${Y} ${c.bold("Update Available!")}`),console.log(""),console.log(` Current version: ${c.dim(e)}`),console.log(` Latest version: ${c.green.bold(t)}`),console.log(""),console.log(` ${c.dim(`Package manager: ${r}`)}`),console.log(c.cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:N})}catch{return false}}};});async function br(s){return new Tt().check(s)}var Zi,$t,es,Tt,uo=m(()=>{D();_r();Er();Sr();Zi="https://registry.npmjs.org",$t="@constellationdev/cli",es=5e3,Tt=class{cache;packageManager;prompter;constructor(){this.cache=new De,this.packageManager=new Me,this.prompter=new Ue;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,r=setTimeout(()=>t.abort(),es);try{let n=await fetch(`${Zi}/${$t}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Registry returned ${n.status}`);let i=(await n.json()).version;return {current:e,latest:i,hasUpdate:this.isNewerVersion(i,e)}}finally{clearTimeout(r);}}isNewerVersion(e,t){let r=i=>i.split("-")[0],n=r(e).split(".").map(Number),o=r(t).split(".").map(Number);for(let i=0;i<3;i++){let a=n[i]||0,l=o[i]||0;if(a>l)return true;if(a<l)return false}return false}async performUpdate(){return console.log(`
192
- ${y} Updating ${$t}...
193
- `),await this.packageManager.executeUpdate($t)?(console.log(`
194
- ${w} Update complete! Please re-run your command.
191
+ `,await _.writeFile(e,o);}},Mn=class{static create(){let e=xe.platform();switch(e){case "win32":return new On;case "darwin":case "linux":return new Dn;default:throw new Error(`Unsupported platform: ${e}`)}}},Ut=class{manager;constructor(){this.manager=Mn.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 Bt,Xi=f(()=>{Bt=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,r]of Object.entries(e.languages))for(let o of r.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=P__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function $l(){let i=xe.platform();if(i==="darwin")return P.join(xe.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||P.join(xe.homedir(),"AppData","Local");return P.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||P.join(xe.homedir(),".cache");return P.join(e,"constellation")}}var kl,jl,Al,Ve,Un=f(()=>{kl=$l(),jl="update-state.json",Al=1440*60*1e3,Ve=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??kl,this.stateFile=P.join(this.stateDir,jl);}async load(){if(this.state)return this.state;try{let e=await B.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await B.mkdir(this.stateDir,{recursive:!0}),await B.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>Al}async recordCheck(){let e=await this.load();e.lastCheckTimestamp=Date.now(),await this.save(e);}async recordDecline(e){let t=await this.load();t.lastDeclinedVersion=e,t.lastDeclinedTimestamp=Date.now(),await this.save(t);}async wasVersionDeclined(e){return (await this.load()).lastDeclinedVersion===e}async clear(){try{await B.unlink(this.stateFile),this.state=null;}catch{}}};});var Ye,Bn=f(()=>{Ye=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...r]=this.getUpdateCommand(e);return new Promise(o=>{let s=spawn(t,r,{stdio:"inherit",shell:process.platform==="win32"});s.on("close",a=>{o(a===0);}),s.on("error",()=>{o(false);});})}};});var qe,Hn=f(()=>{ot();D();qe=class{async promptForUpdate(e,t,r){console.log(""),console.log(p.cyan("\u2501".repeat(60))),console.log(`${Q} ${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: ${r}`)}`),console.log(p.cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:A})}catch{return false}}};});async function Gn(i){return new Gt().check(i)}var Ol,Ht,Dl,Gt,Qi=f(()=>{D();Un();Bn();Hn();Ol="https://registry.npmjs.org",Ht="@constellationdev/cli",Dl=5e3,Gt=class{cache;packageManager;prompter;constructor(){this.cache=new Ve,this.packageManager=new Ye,this.prompter=new qe;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Dl);try{let o=await fetch(`${Ol}/${Ht}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let a=(await o.json()).version;return {current:e,latest:a,hasUpdate:this.isNewerVersion(a,e)}}finally{clearTimeout(r);}}isNewerVersion(e,t){let r=a=>a.split("-")[0],o=r(e).split(".").map(Number),s=r(t).split(".").map(Number);for(let a=0;a<3;a++){let l=o[a]||0,c=s[a]||0;if(l>c)return true;if(l<c)return false}return false}async performUpdate(){return console.log(`
192
+ ${v} Updating ${Ht}...
193
+ `),await this.packageManager.executeUpdate(Ht)?(console.log(`
194
+ ${C} Update complete! Please re-run your command.
195
195
  `),true):(console.log(`
196
- ${C} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString($t)}
197
- `),false)}};});var fo=m(()=>{_r();Er();Sr();uo();});function rs(){return ts.some(s=>!!process.env[s])}function ns(){return !!process.stdout.isTTY}function mo(){return !rs()&&ns()}var ts,ho=m(()=>{ts=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});var Be,yo=m(()=>{Be=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"]),r={added:[],modified:[],deleted:[],renamed:[]},n=t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.split(" ");if(i.length<2)continue;let a=i[0];a==="A"?r.added.push(i[1]):a==="M"?r.modified.push(i[1]):a==="D"?r.deleted.push(i[1]):a.startsWith("R")&&i.length>=3&&r.renamed.push({from:i[1],to:i[2]});}return r}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(r=>r.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,r=e.current;return {clean:t,currentBranch:r}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let n={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(n,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: ${n.modified}, Created: ${n.created}, Deleted: ${n.deleted}, Conflicted: ${n.conflicted}, Staged: ${n.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",n.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${n.conflicted.length} file(s): ${n.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 r=await this.git.status();if(r.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",r.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${r.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(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 ls={};var Co,xr,Ir,He,wo=m(async()=>{Ve();zr();Bn();ao();lo();po();go();ft();fo();kt();Ye();ho();yo();D();process.on("uncaughtException",s=>{s instanceof Error&&s.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${S} An unexpected error occurred during the index attempt:
199
- ${s?.message??String(s)}`),process.exit(1);});Co=globalThis.__constellationVersion??(()=>{let s=b__default.dirname(fileURLToPath(import.meta.url)),e=b__default.join(s,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})();if(mo()){let s=process.argv[2];["auth","help","init","index"].includes(s)?At(s):At(),Ge.includes(s)||await br(Co)&&process.exit(0);}xr=process.cwd(),Ir=new It,He=new Command;He.name("constellation").description("Connecting stars in your code into intelligent patterns").version(Co);He.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 Be(xr)};await new Oe(t).run({skipMcp:s.skipMcp,skipCi:s.skipCi});}catch(e){console.error(`${S} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});He.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:Ir};await new Ee(e).run(s.manual);}catch(e){console.error(`${S} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});He.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 Pt.loadFromFile(b__default.join(xr,"constellation.json")),t=new Be(xr),r=new ut(e),n=new Rt(e),o={GitClient:t,Config:e,LanguageRegistry:r,LanguageDetector:n,Environment:Ir},i=Ir.isCI(),a=s.full||!s.incremental&&i,l=s.dirty||!1,d=s.enrich===!1;!s.full&&!s.incremental&&i&&console.log(`${y} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new Te(o).run(a,l,d);}catch(e){!(e instanceof $)&&!(e instanceof M)&&console.error(`${S} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});He.parse();});var Eo=/^>=\s*\d+\.\d+\.\d+$/;function kr(s,e=process.version){if(!Eo.test(s))return {compatible:true,current:e,required:s};let t=s.replace(/^>=\s*/,""),r=e.replace(/^v/,""),n=t.split(".").map(Number),o=r.split(".").map(Number),i=true;for(let a=0;a<3;a++){let l=n[a]||0,d=o[a]||0;if(d>l)break;if(d<l){i=false;break}}return {compatible:i,current:e,required:s}}kt();var us=dirname(fileURLToPath(import.meta.url)),fs=join(us,"..","package.json"),Rr=JSON.parse(readFileSync(fs,"utf-8")),ms=process.argv[2];if(!Ge.includes(ms)&&Rr.engines?.node){let s=kr(Rr.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=Rr.version;await wo().then(()=>ls);
196
+ ${b} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Ht)}
197
+ `),false)}};});var Zi=f(()=>{Un();Bn();Hn();Qi();});function Ul(){return Ml.some(i=>!!process.env[i])}function Bl(){return !!process.stdout.isTTY}function eo(){return !Ul()&&Bl()}var Ml,to=f(()=>{Ml=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});var Xe,no=f(()=>{Xe=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"]),r={added:[],modified:[],deleted:[],renamed:[]},o=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);for(let s of o){let a=s.split(" ");if(a.length<2)continue;let l=a[0];l==="A"?r.added.push(a[1]):l==="M"?r.modified.push(a[1]):l==="D"?r.deleted.push(a[1]):l.startsWith("R")&&a.length>=3&&r.renamed.push({from:a[1],to:a[2]});}return r}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(r=>r.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,r=e.current;return {clean:t,currentBranch:r}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let o={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw console.error("\u274C Cannot pull: Working directory has uncommitted changes"),console.error(" Details:",JSON.stringify(o,null,2)),e.conflicted.length>0&&console.error(" \u26A0\uFE0F Conflicted files:",e.conflicted.join(", ")),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
198
+ Modified: ${o.modified}, Created: ${o.created}, Deleted: ${o.deleted}, Conflicted: ${o.conflicted}, Staged: ${o.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let o=await this.git.status();if(o.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",o.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${o.conflicted.length} file(s): ${o.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let r=await this.git.status();if(r.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",r.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${r.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(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 Kl={};var ro,zn,Kn,Qe,io=f(async()=>{it();ur();Ii();Ji();Vi();qi();Xi();Et();Zi();Wt();st();to();no();D();process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${E} An unexpected error occurred during the index attempt:
199
+ ${i?.message??String(i)}`),process.exit(1);});ro=globalThis.__constellationVersion??(()=>{let i=P__default.dirname(fileURLToPath(import.meta.url)),e=P__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})();if(eo()){let i=process.argv[2];["auth","help","init","index"].includes(i)?Kt(i):Kt(),et.includes(i)||await Gn(ro)&&process.exit(0);}zn=process.cwd(),Kn=new Ut,Qe=new Command;Qe.name("constellation").description("Connecting stars in your code into intelligent patterns").version(ro);Qe.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async i=>{try{let t={GitClient:new Xe(zn)};await new Ke(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){console.error(`${E} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Qe.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async i=>{try{let e={Environment:Kn};await new Ne(e).run(i.manual);}catch(e){console.error(`${E} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Qe.command("index").description("Create or update the Constellation data indices for the current project").option("--full","Conduct a full project re-index").option("--incremental","Conduct an incremental project index update").option("--dirty","Skip git validation checks (branch and working tree status)").option("--no-enrich","Skip LSP enrichment (only perform parse tree indexing)").action(async i=>{try{let e=await Dt.loadFromFile(P__default.join(zn,"constellation.json")),t=new Xe(zn),r=new xt(e),o=new Bt(e),s={GitClient:t,Config:e,LanguageRegistry:r,LanguageDetector:o,Environment:Kn},a=Kn.isCI(),l=i.full||!i.incremental&&a,c=i.dirty||!1,u=i.enrich===!1;!i.full&&!i.incremental&&a&&console.log(`${v} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new Ue(s).run(l,c,u);}catch(e){!(e instanceof $)&&!(e instanceof U)&&console.error(`${E} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Qe.parse();});var lo=/^>=\s*\d+\.\d+\.\d+$/;function Yn(i,e=process.version){if(!lo.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),r=e.replace(/^v/,""),o=t.split(".").map(Number),s=r.split(".").map(Number),a=true;for(let l=0;l<3;l++){let c=o[l]||0,u=s[l]||0;if(u>c)break;if(u<c){a=false;break}}return {compatible:a,current:e,required:i}}Wt();var Xl=dirname(fileURLToPath(import.meta.url)),Ql=join(Xl,"..","package.json"),Jn=JSON.parse(readFileSync(Ql,"utf-8")),Zl=process.argv[2];if(!et.includes(Zl)&&Jn.engines?.node){let i=Yn(Jn.engines.node);i.compatible||(console.error(`Error: Constellation CLI requires Node.js ${i.required} (current: ${i.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=Jn.version;await io().then(()=>Kl);
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.1",
4
+ "version": "0.5.1",
5
5
  "author": "ShiftinBits Inc",
6
6
  "main": "dist/main.js",
7
7
  "type": "module",
@@ -20,11 +20,10 @@
20
20
  "test:coverage": "jest --coverage",
21
21
  "test:ci": "jest --ci --coverage --maxWorkers=2",
22
22
  "type-check": "tsc --noEmit -p tsconfig.build.json",
23
- "prepare": "node -e \"try{require('husky').default()}catch(e){}\"",
24
- "postinstall": "node -e \"if(process.env.CI) { console.log('Using github sourced @constellationdev/types') } else { try { require('child_process').execSync('npm link @constellationdev/types', {stdio: 'inherit'}); console.log('Using locally linked @constellationdev/types') } catch(e) { console.log('Note: @constellationdev/types not linked globally, using GitHub version') } }\""
23
+ "prepare": "node -e \"try{require('husky').default()}catch(e){}\""
25
24
  },
26
25
  "dependencies": {
27
- "@constellationdev/types": "github:ShiftinBits/constellation-types#main",
26
+ "@constellationdev/types": "^1.0.0",
28
27
  "@iarna/toml": "^3.0.0",
29
28
  "@inquirer/prompts": "^8.4.1",
30
29
  "@scure/base": "^2.0.0",