@constellationdev/cli 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +63 -56
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as w from'path';import w__default from'path';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import*as Be from'fs';import {readFileSync}from'fs';import {fileURLToPath}from'url';import {Command}from'commander';import {Agent,fetch as fetch$1}from'undici';import {base32}from'@scure/base';import {Readable}from'stream';import l from'ansi-colors';import*as Q from'os';import Q__default from'os';import Pn from'enquirer';import {performance}from'perf_hooks';import*as T from'fs/promises';import T__default from'fs/promises';import Vn from'tree-sitter';import Mt from'ignore';import {z as z$1}from'zod';import {promisify}from'util';import tt from'zlib';import {pipeline}from'stream/promises';import hr from'tree-sitter-javascript';import yr from'tree-sitter-python';import _r from'tree-sitter-typescript';import {findAll,parse}from'tsconfck';import {spawn}from'child_process';import {simpleGit}from'simple-git';var In=Object.defineProperty;var j=(s,e)=>()=>(s&&(e=s(s=0)),e);var kt=(s,e)=>{for(var t in e)In(s,t,{get:e[t],enumerable:true});};function Ft(s){return s.replace(/\\/g,"/")}function $e(s){return Ft(s).replace(/^\.?\//,"")}function H(s,e){return Ft(w.relative(s,e))}var Y=j(()=>{});async function U(s,e,t,n,r){let o=await t.resolve(s),i=Ut(s,o),a=r(s,o,i),c=i?void 0:$e(o);n[e.toString()]={source:s,resolvedPath:c,isExternal:i,importType:a};}function Ut(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var nt,se=j(()=>{Y();nt=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function Zn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}async function Qn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}function Re(){return {language:"javascript",handlers:new Map([["import_statement",Zn],["export_statement",Qn]])}}function rt(){return {...Re(),language:"typescript"}}var ot=j(()=>{se();});async function nr(s,e,t,n){let r=s.childForFieldName("name");if(!r)return;let o;if(r.type==="aliased_import"){let i=r.childForFieldName("name");o=i?i.text:r.text;}else o=r.text;await U(o,s.startPosition.row,e,t,n);}async function rr(s,e,t,n){let r,o=s.childForFieldName("module_name");if(o)r=o.text;else {let i="";for(let a=0;a<s.childCount;a++){let c=s.child(a);if(c){if(c.type==="relative_import"){i=c.text;break}(c.type==="."||c.type==="import_prefix")&&(i+=c.text);}}r=i||".";}await U(r,s.startPosition.row,e,t,n);}async function or(s,e,t,n){await U("__future__",s.startPosition.row,e,t,n);}function it(){return {language:"python",handlers:new Map([["import_statement",nr],["import_from_statement",rr],["future_import_statement",or]]),classifyImportType:tr}}var tr,je=j(()=>{se();tr=(s,e,t)=>{if(t)return "external";if(/^\.+/.test(s))return "relative";let n=s.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var Gt,Wt=j(()=>{ot();je();se();ot();je();Gt=[Re(),rt(),it()];});var Kt={};kt(Kt,{ImportExtractor:()=>st});var st,Vt=j(()=>{Wt();se();st=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Gt)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,r){if(!r)return {};let o=this.languageHandlers.get(n);if(!o)return {};let i=this.classifiers.get(n)??nt,a={};return await this.walkAST(e.rootNode,async c=>{let g=o.get(c.type);g&&await g(c,r,a,i);}),a}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let r=e.child(n);r&&await this.walkAST(r,t);}}};});var ae,Jt,at,Yt,qt,Ae=j(()=>{ae=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"]),Jt=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"]),at={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"]},Yt={language:"javascript",textIncludedTypes:Jt,fieldNames:at},qt={language:"typescript",textIncludedTypes:Jt,fieldNames:at};});var ir,Xt,Zt,lt=j(()=>{ir=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"]),Xt={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"]},Zt={language:"python",textIncludedTypes:ir,fieldNames:Xt,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function Qt(s){return le.get(s)}function en(s){if(!s)return ae;let e=le.get(s);if(!e)return ae;let t=new Set(ae);for(let n of e.textIncludedTypes)t.add(n);return t}function ct(s){if(!s){let t=Array.from(le.values()).map(n=>n.fieldNames);return ce(...t)}let e=le.get(s);if(!e){let t=Array.from(le.values()).map(n=>n.fieldNames);return ce(...t)}return e.fieldNames}var le,tn=j(()=>{pt();Ae();lt();Ae();Ae();lt();le=new Map([["javascript",Yt],["typescript",qt],["python",Zt]]);});var an={};kt(an,{COMMON_FIELD_NAMES:()=>ut,JS_TS_FIELD_NAMES:()=>on,PYTHON_FIELD_NAMES:()=>sn,TEXT_INCLUDED_TYPES:()=>nn,mergeFieldMaps:()=>ce,serializeAST:()=>ar,serializeASTStream:()=>sr});function*sr(s,e,t){yield*dt(s,e,t);}function*dt(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)}`),rn(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let r=(t?ct(t):ut)[s.type]||[],o=new Set,i=true;for(let a of r){let c=s.childForFieldName(a);c&&(i||(yield ","),i=false,o.add(c),yield*dt(c,a,t));}for(let a=0;a<s.childCount;a++){let c=s.child(a);c&&!o.has(c)&&(i||(yield ","),i=false,yield*dt(c,void 0,t));}yield "]";}yield "}";}async function ar(s,e,t){let n=gt(s,e,t),r=t?ct(t):ut,o=[{treeNode:s,serializedNode:n,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=r[i.treeNode.type]||[];for(let c of a){let g=i.treeNode.childForFieldName(c);if(g){i.fieldChildren.add(g);let d=gt(g,c,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(d),o.push({treeNode:g,serializedNode:d,fieldName:c,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 c=gt(a,void 0,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(c),o.push({treeNode:a,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else o.pop();}return n}function gt(s,e,t){let n={type:s.type,startPosition:{row:s.startPosition.row,column:s.startPosition.column},endPosition:{row:s.endPosition.row,column:s.endPosition.column},...e&&{fieldName:e}};return rn(s,t)&&(n.text=s.text),n}function rn(s,e){if(e){let n=Qt(e);if(n?.shouldIncludeText){let o=n.shouldIncludeText(s);if(o===false)return false;if(o===true)return true}return en(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:nn.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function ce(...s){let e={};for(let t of s)for(let[n,r]of Object.entries(t)){let i=[...e[n]||[]];for(let a of r)i.includes(a)||i.push(a);e[n]=i;}return e}var nn,on,sn,ut,pt=j(()=>{tn();nn=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"]);on={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"]},sn={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"]};ut=ce(on,sn);});function Nt(s){return base32.encode(Buffer.from(s))}function Rt(s,e,t){let n=`${s}:${e}${t?`:${t}`:""}`;return Nt(n)}var Se=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
|
|
3
|
-
`,r=Buffer.from(n,"utf8");if(!this.push(r))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};function kn(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:
|
|
4
|
-
Caused by: ${
|
|
5
|
-
\u2502 ${
|
|
6
|
-
\u2502 _____ ${
|
|
7
|
-
\u2502 ${
|
|
8
|
-
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${
|
|
9
|
-
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${
|
|
10
|
-
\u2502 ${
|
|
11
|
-
\u2502${
|
|
12
|
-
\u2502 ${
|
|
2
|
+
import*as _ from'path';import ___default from'path';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import*as He from'fs';import {readFileSync}from'fs';import {fileURLToPath}from'url';import {Command}from'commander';import {Agent,fetch as fetch$1}from'undici';import {base32}from'@scure/base';import {Readable}from'stream';import c from'ansi-colors';import*as ee from'os';import ee__default from'os';import Pn from'enquirer';import {performance}from'perf_hooks';import*as T from'fs/promises';import T__default from'fs/promises';import Vn from'tree-sitter';import Mt from'ignore';import {z as z$1}from'zod';import {promisify}from'util';import tt from'zlib';import {pipeline}from'stream/promises';import hr from'tree-sitter-javascript';import yr from'tree-sitter-python';import wr from'tree-sitter-typescript';import {findAll,parse}from'tsconfck';import {spawn}from'child_process';import {simpleGit}from'simple-git';var In=Object.defineProperty;var j=(s,e)=>()=>(s&&(e=s(s=0)),e);var kt=(s,e)=>{for(var t in e)In(s,t,{get:e[t],enumerable:true});};function Ft(s){return s.replace(/\\/g,"/")}function Te(s){return Ft(s).replace(/^\.?\//,"")}function H(s,e){return Ft(_.relative(s,e))}var Y=j(()=>{});async function U(s,e,t,n,r){let o=await t.resolve(s),i=Ut(s,o),a=r(s,o,i),l=i?void 0:Te(o);n[e.toString()]={source:s,resolvedPath:l,isExternal:i,importType:a};}function Ut(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var nt,ae=j(()=>{Y();nt=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function Zn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}async function Qn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}function je(){return {language:"javascript",handlers:new Map([["import_statement",Zn],["export_statement",Qn]])}}function rt(){return {...je(),language:"typescript"}}var ot=j(()=>{ae();});async function nr(s,e,t,n){let r=s.childForFieldName("name");if(!r)return;let o;if(r.type==="aliased_import"){let i=r.childForFieldName("name");o=i?i.text:r.text;}else o=r.text;await U(o,s.startPosition.row,e,t,n);}async function rr(s,e,t,n){let r,o=s.childForFieldName("module_name");if(o)r=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);}}r=i||".";}await U(r,s.startPosition.row,e,t,n);}async function or(s,e,t,n){await U("__future__",s.startPosition.row,e,t,n);}function it(){return {language:"python",handlers:new Map([["import_statement",nr],["import_from_statement",rr],["future_import_statement",or]]),classifyImportType:tr}}var tr,Ae=j(()=>{ae();tr=(s,e,t)=>{if(t)return "external";if(/^\.+/.test(s))return "relative";let n=s.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var Gt,Wt=j(()=>{ot();Ae();ae();ot();Ae();Gt=[je(),rt(),it()];});var Kt={};kt(Kt,{ImportExtractor:()=>st});var st,Vt=j(()=>{Wt();ae();st=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Gt)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,r){if(!r)return {};let o=this.languageHandlers.get(n);if(!o)return {};let i=this.classifiers.get(n)??nt,a={};return await this.walkAST(e.rootNode,async l=>{let g=o.get(l.type);g&&await g(l,r,a,i);}),a}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let r=e.child(n);r&&await this.walkAST(r,t);}}};});var ce,Jt,at,Yt,qt,Le=j(()=>{ce=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"]),Jt=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"]),at={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"]},Yt={language:"javascript",textIncludedTypes:Jt,fieldNames:at},qt={language:"typescript",textIncludedTypes:Jt,fieldNames:at};});var ir,Xt,Zt,ct=j(()=>{ir=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"]),Xt={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"]},Zt={language:"python",textIncludedTypes:ir,fieldNames:Xt,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function Qt(s){return le.get(s)}function en(s){if(!s)return ce;let e=le.get(s);if(!e)return ce;let t=new Set(ce);for(let n of e.textIncludedTypes)t.add(n);return t}function lt(s){if(!s){let t=Array.from(le.values()).map(n=>n.fieldNames);return pe(...t)}let e=le.get(s);if(!e){let t=Array.from(le.values()).map(n=>n.fieldNames);return pe(...t)}return e.fieldNames}var le,tn=j(()=>{pt();Le();ct();Le();Le();ct();le=new Map([["javascript",Yt],["typescript",qt],["python",Zt]]);});var an={};kt(an,{COMMON_FIELD_NAMES:()=>ut,JS_TS_FIELD_NAMES:()=>on,PYTHON_FIELD_NAMES:()=>sn,TEXT_INCLUDED_TYPES:()=>nn,mergeFieldMaps:()=>pe,serializeAST:()=>ar,serializeASTStream:()=>sr});function*sr(s,e,t){yield*dt(s,e,t);}function*dt(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)}`),rn(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let r=(t?lt(t):ut)[s.type]||[],o=new Set,i=true;for(let a of r){let l=s.childForFieldName(a);l&&(i||(yield ","),i=false,o.add(l),yield*dt(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*dt(l,void 0,t));}yield "]";}yield "}";}async function ar(s,e,t){let n=gt(s,e,t),r=t?lt(t):ut,o=[{treeNode:s,serializedNode:n,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=r[i.treeNode.type]||[];for(let l of a){let g=i.treeNode.childForFieldName(l);if(g){i.fieldChildren.add(g);let d=gt(g,l,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(d),o.push({treeNode:g,serializedNode:d,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=gt(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 n}function gt(s,e,t){let n={type:s.type,startPosition:{row:s.startPosition.row,column:s.startPosition.column},endPosition:{row:s.endPosition.row,column:s.endPosition.column},...e&&{fieldName:e}};return rn(s,t)&&(n.text=s.text),n}function rn(s,e){if(e){let n=Qt(e);if(n?.shouldIncludeText){let o=n.shouldIncludeText(s);if(o===false)return false;if(o===true)return true}return en(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:nn.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function pe(...s){let e={};for(let t of s)for(let[n,r]of Object.entries(t)){let i=[...e[n]||[]];for(let a of r)i.includes(a)||i.push(a);e[n]=i;}return e}var nn,on,sn,ut,pt=j(()=>{tn();nn=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"]);on={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"]},sn={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"]};ut=pe(on,sn);});function Nt(s){return base32.encode(Buffer.from(s))}function Rt(s,e,t){let n=`${s}:${e}${t?`:${t}`:""}`;return Nt(n)}var Ee=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
|
|
3
|
+
`,r=Buffer.from(n,"utf8");if(!this.push(r))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};function kn(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:ee.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 Nn="\u2714",Rn="\u2717",jn="\u26A0",An="\u2139",Ln="\u26A1",On="[OK]",Fn="[ERR]",Mn="[WARN]",Dn="[INFO]",Bn="[>>]",ie=kn(),h=c.green(ie?Nn:On),C=c.red(ie?Rn:Fn),y=c.yellow(ie?jn:Mn),m=c.blue(ie?An:Dn),F=c.yellow(ie?Ln:Bn);var be=class{constructor(e,t){this.config=e;this.accessKey=t;}apiVersion="intel/v1";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),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new $(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new $(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new $(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new M("Project not found - no previous index exists");default:throw e.status===404?new M("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof $||t instanceof M?t:e.status===404?new M("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let r=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let o=await this.sendRequest(r,null,"GET");return !o||!o.ok?null:await o.json()}catch(o){if(o instanceof E)throw o;return null}}async deleteFiles(e){for(let t of e){let n=Rt(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,r,o,i){try{let{Readable:a}=await import('stream'),l=new Ee(e),g=a.toWeb(l),d=new Agent({headersTimeout:0,bodyTimeout:0}),p=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":n,"x-branch-name":r,"x-constellation-index":o?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...i&&{"x-commit-hash":i}},body:g,duplex:"half",dispatcher:d});if(p.status===401)throw new E("Authentication failed");if(p.status===409){let u="Indexing already in progress",f;try{let v=await p.json();u=v?.message||u,f=v?.details?.branchName;}catch{}throw new J(u,f)}if(p.status===200)try{let u=await p.json();if(u?.status==="current")return console.log(`${h} Index already up to date for ${r} at commit ${u.commitHash||"unknown"}`),!0}catch{}return p.ok===!0||p.status===202}catch(a){if(a instanceof E||a instanceof J)throw a;let l=a instanceof Error?a:new Error(String(a)),g="";if(l.message==="fetch failed"||a.code){let p=[],u=a.code||a.cause?.code;if(a.code&&p.push(`Error Code: ${a.code}`),a.cause){let f=a.cause;f.code&&p.push(`Cause Code: ${f.code}`),f.errno&&p.push(`Errno: ${f.errno}`),f.syscall&&p.push(`System Call: ${f.syscall}`),f.address&&p.push(`Address: ${f.address}`),f.port&&p.push(`Port: ${f.port}`);}u==="ERR_INVALID_ARG_VALUE"?g="Invalid argument value - check stream/body format and duplex option":u==="ECONNREFUSED"?g="Connection refused - service may be down or unreachable":u==="ENOTFOUND"?g="DNS lookup failed - check service URL":u==="ETIMEDOUT"?g="Connection timeout - service not responding":u==="ECONNRESET"?g="Connection reset by server":u==="EHOSTUNREACH"?g="Host unreachable - check network connectivity":g="Network failure",p.length>0&&(g+=` (${p.join(", ")})`);}else g=l.message;let d=new Error(`Failed to upload data to Constellation Service: ${g}`);throw d.cause=l,d.stack=`${d.stack}
|
|
4
|
+
Caused by: ${l.stack}`,d}}async sendRequest(e,t,n,r={},o=0,i=3,a=1e3,l=250){for(let g=1;g<=i;g++)try{let d=new AbortController,p;o>0&&(p=setTimeout(()=>d.abort(),o));let u={...r,"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:n,headers:u,body:t?JSON.stringify(t):void 0,signal:d.signal});if(p&&clearTimeout(p),f.status===401)throw new E("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new Ie(`${f.statusText} (${f.status})`);return f}catch(d){if(!(d instanceof E)){let p=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);console.log(`HTTP request attempt ${g}/${i} failed: ${p}`);}if(g<i&&d instanceof Ie){let p=a+Math.floor(Math.random()*l);await new Promise(u=>setTimeout(u,p));}else throw d}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Ie=class extends Error{constructor(e){super(e),this.name="RetryableError";}},E=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},M=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},$=class extends Error{constructor(t,n,r){super(t);this.code=n;this.projectId=r;this.name="ProjectValidationError";}},J=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}};function Qe(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
|
|
5
|
+
\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
|
|
6
|
+
\u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
|
|
7
|
+
\u2502 ${c.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${c.gray(".")} ${c.yellowBright("'")} ${c.gray("+")} ${c.gray("\\")} ${c.gray("`")} \u2502
|
|
8
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${c.gray("'")} ${c.blueBright("o")}${c.gray("\u2014\u2014\u2014\u2014")}${c.yellowBright("o")} ${c.whiteBright("o")} ${c.whiteBright(".")} \u2502
|
|
9
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${c.gray(".")} ${c.whiteBright("*")} ${c.gray(" \\ \\ ")}${c.gray("/")} \u2502
|
|
10
|
+
\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
|
|
11
|
+
\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
|
|
12
|
+
\u2502 ${c.bold(`constellation \u203A ${s}`)} \u2502
|
|
13
13
|
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(s.length)}\u2500\u256F
|
|
14
14
|
`):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");}`
|
|
15
15
|
\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
|
|
16
|
-
\u2502 ${
|
|
17
|
-
\u2502 _____ ${
|
|
18
|
-
\u2502 ${
|
|
19
|
-
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${
|
|
20
|
-
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${
|
|
21
|
-
\u2502 ${
|
|
22
|
-
\u2502${
|
|
16
|
+
\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
|
|
17
|
+
\u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
|
|
18
|
+
\u2502 ${c.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${c.gray(".")} ${c.yellowBright("'")} ${c.gray("+")} ${c.gray("\\")} ${c.gray("`")} \u2502
|
|
19
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${c.gray("'")} ${c.blueBright("o")}${c.gray("\u2014\u2014\u2014\u2014")}${c.yellowBright("o")} ${c.whiteBright("o")} ${c.whiteBright(".")} \u2502
|
|
20
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${c.gray(".")} ${c.whiteBright("*")} ${c.gray(" \\ \\ ")}${c.gray("/")} \u2502
|
|
21
|
+
\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
|
|
22
|
+
\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
|
|
23
23
|
\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
|
|
24
24
|
`;`
|
|
25
|
-
${
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
`;var D="CONSTELLATION_ACCESS_KEY";var B=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};var{prompt:At}=Pn,Gn=/^ak:[0-9a-f]{32}$/i;function Wn(s){return Gn.test(s)}function Kn(s){return s.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var
|
|
25
|
+
${c.yellowBright(" o")}
|
|
26
|
+
${c.gray(" \\")}
|
|
27
|
+
${c.blueBright(" o")}${c.blueBright("----")}${c.yellowBright("o")} ${c.gray("o")}
|
|
28
|
+
${c.gray(" \\ \\ ")}${c.blueBright("/")}
|
|
29
|
+
${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
|
|
30
|
+
`;var D="CONSTELLATION_ACCESS_KEY";var B=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};var{prompt:At}=Pn,Gn=/^ak:[0-9a-f]{32}$/i;function Wn(s){return Gn.test(s)}function Kn(s){return s.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var se=class extends B{async run(){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${F}Configuring access key authentication...
|
|
31
31
|
`),this.env.isCI()){console.error(`${C} Cannot configure authentication in CI/CD environments
|
|
32
32
|
|
|
33
33
|
The ${D} environment variable must be configured
|
|
@@ -38,18 +38,24 @@ ${l.whiteBright(" o o")}${l.blueBright("-")}${l.blueBright("o")}
|
|
|
38
38
|
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
39
39
|
- Jenkins: Manage Jenkins -> Credentials
|
|
40
40
|
- CircleCI: Project Settings -> Environment Variables
|
|
41
|
-
`);return}if(await this.env.getKey(D)){let{replaceKey:
|
|
41
|
+
`);return}if(await this.env.getKey(D)){let{replaceKey:i}=await At({message:"Replace existing Constellation access key?",name:"replaceKey",type:"confirm",initial:!1});if(!i){console.log(`${h} Keeping existing Constellation access key`);return}}let t,n=0,r=3;for(;n<r;){if(t=(await At({message:"Constellation Access Key:",name:"accessKey",type:"password",required:!0})).accessKey.trim(),!t){console.log(`${y} Access key cannot be empty.
|
|
42
42
|
`),n++;continue}if(!Wn(t)){if(n++,n<r)console.log(`${y} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
43
43
|
Attempts remaining: ${r-n}
|
|
44
44
|
`);else {console.error(`${C} Invalid access key format after ${r} attempts.
|
|
45
|
-
Please verify your access key and try again.`);return}continue}break}await this.env.setKey(D,t),console.log(`${h} Stored access key in ${D} user environment variable`)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
${
|
|
51
|
-
|
|
52
|
-
|
|
45
|
+
Please verify your access key and try again.`);return}continue}break}await this.env.setKey(D,t),console.log(`${h} Stored access key in ${D} user environment variable`);let o=this.env.getSourceFile();o&&console.log(`${m} To activate in this session, run:
|
|
46
|
+
|
|
47
|
+
source ${o}
|
|
48
|
+
|
|
49
|
+
New terminal sessions will load it automatically.`);}catch(e){let t=e.message??"An unexpected error occurred",n=Kn(t);console.error(`${C} Failed to store Constellation access key
|
|
50
|
+
${n}`);}}};var w={async directoryExists(s){try{return (await T__default.stat(s)).isDirectory()}catch{return false}},async fileIsReadable(s){try{return await T__default.access(s,T__default.constants.R_OK),!0}catch{return false}},async readFile(s,e="utf-8"){let t=await T__default.readFile(s,{encoding:e,flag:T__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(s,e,t="utf-8"){let n=Buffer.from(e,t);await T__default.writeFile(s,n,{encoding:t,flag:T__default.constants.O_WRONLY|T__default.constants.O_CREAT|T__default.constants.O_TRUNC});},async getFileStats(s){return await T__default.stat(s)},async getFileHandle(s,e,t){return await T__default.open(s,e,t)}};var $e=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let r=await n();if(!r)throw new Error(`Failed to load language: ${t}`);let o=new Vn;o.setLanguage(r);let i=await w.getFileStats(e),a=10*1024*1024;if(i.size<=a){let l=await w.readFile(e),g={bufferSize:1024*1024};return o.parse(l,void 0,g)}else return this.parseWithStream(o,e,i.size)}async parseWithStream(e,t,n){let r=null;try{r=await T.open(t,"r");let o=r.fd,i=64*1024,a=Buffer.alloc(i),l=0;return e.parse(d=>{if(n>50*1024*1024){let u=Math.round(d/n*100);u>l+10&&(console.log(` Parsing large file: ${u}%...`),l=u);}let p=He.readSync(o,a,0,i,d);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(o){if(r)try{await r.close();}catch(i){console.error(`Warning: Failed to close file handle for ${t}:`,i);}throw o}finally{if(r)try{await r.close();}catch{}}}};Y();var ke=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Mt();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(o=>!t.ignores(o.relativePath)&&this.matchesLanguageExtension(o,e.languages))}async scanSpecificFiles(e,t){let n=[],r=null;t.exclude&&t.exclude.length>0&&(r=Mt().add(t.exclude));let o=await T__default.realpath(this.rootPath);for(let i of e)try{let a=___default.isAbsolute(i)?i:___default.join(this.rootPath,i),l=await T__default.lstat(a);if(l.isSymbolicLink()){let g=await T__default.realpath(a);if(!g.startsWith(o+___default.sep)&&g!==o){console.warn(`${y} Skipping symlink pointing outside project: ${i} -> ${g}`);continue}let d=await T__default.stat(a);if(!d.isFile())continue;let p=H(this.rootPath,a);if(r&&r.ignores(p))continue;let u=this.detectLanguage(p,t.languages);if(!u)continue;n.push({path:a,relativePath:p,language:u,size:d.size});}else if(l.isFile()){let g=H(this.rootPath,a);if(r&&r.ignores(g))continue;let d=this.detectLanguage(g,t.languages);if(!d)continue;n.push({path:a,relativePath:g,language:d,size:l.size});}}catch{console.warn(`${y} Skipping inaccessible file: ${i}`);}return n}async loadGitignoreRules(e,t){let n=[],r=t;for(;;){let o=___default.join(r,".gitignore");await w.fileIsReadable(o)&&n.unshift(o);let i=___default.dirname(r);if(i===r)break;r=i;let a=___default.join(r,".git");if(await w.directoryExists(a)){let l=___default.join(r,".gitignore");await w.fileIsReadable(l)&&!n.includes(l)&&n.unshift(l);break}}for(let o of n)try{let i=await w.readFile(o);e.add(i);}catch{console.warn(`${y} Failed to load .gitignore: ${o}`);}e.add(".git");}async walkDirectory(e,t,n){let r=[],o=t||e,i=n||await T__default.realpath(this.rootPath);try{let a=await T__default.readdir(e,{withFileTypes:!0});for(let l of a){let g=___default.join(e,l.name),d=H(o,g);if(l.isDirectory()){if(l.name.startsWith("."))continue;let p=await this.walkDirectory(g,o,i);r.push(...p);}else if(l.isFile()){let p=await T__default.stat(g);r.push({path:g,relativePath:d,language:"",size:p.size});}else if(l.isSymbolicLink())try{let p=await T__default.realpath(g);if(!p.startsWith(i+___default.sep)&&p!==i){console.warn(`${y} Skipping symlink pointing outside project: ${g} -> ${p}`);continue}let u=await T__default.stat(g);if(u.isDirectory()){if(l.name.startsWith("."))continue;let f=await this.walkDirectory(g,o,i);r.push(...f);}else u.isFile()&&r.push({path:g,relativePath:d,language:"",size:u.size});}catch{console.warn(`${y} Skipping invalid symlink: ${g}`);}}}catch(a){console.error(`${C} Error walking directory ${e}:`,a);}return r}matchesLanguageExtension(e,t){let n=___default.extname(e.path).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return e.language=r,true;return false}detectLanguage(e,t){let n=___default.extname(e).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return r;return null}};var Jn=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"])}),Yn=z$1.record(z$1.string(),Jn),Dt=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:Yn.optional()});var Xn=promisify(tt.gunzip),Ne=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],n=tt.createGzip();n.on("data",i=>t.push(i));let r=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),o=Readable.from(e);return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=tt.createGzip();n.on("data",i=>t.push(i));let r=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),o=Readable.from(this.serializeASTChunks(e));return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await Xn(t);return JSON.parse(n.toString("utf-8"))}};var Re=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let n=new Map,r=0,o=0;for(;o<e.length&&n.size<this.concurrency;){let i=r++,a=this.processItem(e[o],o,t).then(l=>({result:l!==null?l.result:null,promiseId:i}));n.set(i,a),o++;}for(;n.size>0;){let i=await Promise.race(n.values());if(n.delete(i.promiseId),i.result!==null&&(yield i.result),o<e.length){let a=r++,l=this.processItem(e[o],o,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,l),o++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};Y();var ge=class extends B{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new ke(process.cwd()),this.parser=new $e(this.langRegistry),this.compressor=new Ne;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let r=n.getBuildConfigManager(process.cwd(),this.config.languages);r&&this.buildConfigManagers.set(t,r);}}}async run(e=false,t=false){try{let n=await this.getAccessKey();this.apiClient=new be(this.config,n),await this.validateProject(),console.log(`${F}Starting indexing procedure...
|
|
51
|
+
`);let r=performance.now();if(t?console.log(`${y} Skipping git branch validation`):await this.validateGitBranch(),t?console.log(`${y} Skipping git status validation`):await this.validateGitStatus(),t?console.log(`${y} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){console.log(`${m} Discovering language build configurations...`);let x=0;for(let[Se,re]of this.buildConfigManagers.entries()){let S=await re.initialize();x+=S.length;}x>0&&console.log(`${h} Found ${x} configuration file(s)`);}let o=await this.determineIndexScope(e),i=await this.git.getLatestCommitHash();if(o.upToDate){console.log(`
|
|
52
|
+
${h} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${i.substring(0,8)}`);return}if(o.isIncremental&&i){let x=await this.apiClient.getIndexStatus(this.config.branch,i);if(x?.status==="current"||x?.status==="processing"&&x?.commitHash===i){console.log(`${h} Index already up to date for branch ${this.config.branch} at commit ${i.substring(0,8)}`);return}}let a=await this.discoverFiles(o.isIncremental),l=!1,g=()=>{l||console.log(`${m} Uploading metadata, processing, and indexing...`);},d=this.generateASTs(a,g);try{await this.uploadToAPI(d,o.isIncremental,i),l=!0;}catch(x){throw l=!0,x}let f=(performance.now()-r)/1e3,v=Math.floor(f/60),P=(f%60).toFixed(3),ne=v>0?`${v}m ${P}s`:`${P}s`;console.log(`
|
|
53
|
+
${h} Upload completed in ${ne}! Server indexing in progress.`);}catch(n){if(n instanceof $)throw n;if(n instanceof J)throw console.error(`${C} Indexing failed: Another indexing operation is currently in progress for branch ${n.branchName||this.config?.branch||"unknown"}.`),console.log(" Your index may be out of date. Re-run this command after the current operation completes."),n;if(n instanceof E)throw console.error(`
|
|
54
|
+
${C} Authentication failed.`),console.log(`${m} Your access key may be invalid or expired. Run 'constellation auth'
|
|
55
|
+
to set or update your access key.`),n;if(n instanceof Error&&n.message==="Access key not configured")throw n;let r=n instanceof Error?n.message:"An unexpected error occurred";throw console.error(`${C} Indexing failed: ${r}`),n}}async getAccessKey(){let e=await this.env.getKey(D);if(!e)throw console.error(`
|
|
56
|
+
${C} Access key not found.`),console.log(`${m} Set the ${D} environment variable or run
|
|
57
|
+
'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){console.log(`${m} Validating project access...`);try{await this.apiClient.getProjectState(),console.log(`${h} Project validated successfully`);}catch(e){if(e instanceof $)throw this.displayProjectValidationError(e),e;if(e instanceof M){console.log(`${h} Project validated (first index)`);return}if(e instanceof E)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.
|
|
58
|
+
Verify your network connection and that the API URL is correct.`):e}}displayProjectValidationError(e){let t=e.projectId||this.config.projectId,n=t.length>40?t.substring(0,37)+"...":t;switch(e.code){case "PROJECT_NOT_REGISTERED":console.error(`
|
|
53
59
|
${C} Project not registered
|
|
54
60
|
`),console.error(` The project ID "${n}" in constellation.json`),console.error(` is not associated with your Constellation account.
|
|
55
61
|
`),console.error(" To resolve this:"),console.error(" 1. Verify the project exists at https://app.constellationdev.io"),console.error(" 2. Check that the project ID in constellation.json is correct"),console.error(` 3. Run 'constellation index' again
|
|
@@ -63,8 +69,8 @@ ${C} Invalid project ID
|
|
|
63
69
|
`),console.error(" To resolve this:"),console.error(" 1. Get your project ID from https://app.constellationdev.io"),console.error(" 2. Update the projectId field in constellation.json"),console.error(` 3. Run 'constellation index' again
|
|
64
70
|
`);break;default:console.error(`
|
|
65
71
|
${C} Project validation failed: ${e.message}
|
|
66
|
-
`);}}async validateGitBranch(){console.log(`${
|
|
67
|
-
Commit or stash changes first to ensure consistent indexing.`);console.log(`${h} Working tree clean`);}async synchronizeChanges(){console.log(`${
|
|
72
|
+
`);}}async validateGitBranch(){console.log(`${m} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),console.log(`${h} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(console.log(`${m} Validating Git status...`),!(await this.git.status()).clean)throw new Error(`Outstanding changes detected.
|
|
73
|
+
Commit or stash changes first to ensure consistent indexing.`);console.log(`${h} Working tree clean`);}async synchronizeChanges(){console.log(`${m} Synchronizing latest changes...`);try{await this.git.pull()&&console.log(`${h} Repository synchronized successfully`);}catch(e){throw console.error(`${C} Failed to synchronize repository`),e instanceof Error&&(e.message.includes("uncommitted changes")?(console.error(`
|
|
68
74
|
To resolve:`),console.error(' 1. Commit your changes: git add . && git commit -m "your message"'),console.error(" 2. Or stash them: git stash"),console.error(` 3. Then run the index command again
|
|
69
75
|
`)):e.message.includes("merge conflicts")?(console.error(`
|
|
70
76
|
To resolve:`),console.error(" 1. Fix the conflicted files manually"),console.error(" 2. Stage the resolved files: git add <resolved-files>"),console.error(" 3. Complete the merge: git commit"),console.error(` 4. Then run the index command again
|
|
@@ -72,7 +78,7 @@ To resolve:`),console.error(" 1. Fix the conflicted files manually"),console.er
|
|
|
72
78
|
Please check your internet connection and try again
|
|
73
79
|
`):e.message.includes("Authentication")&&console.error(`
|
|
74
80
|
Please check your git credentials and try again
|
|
75
|
-
`)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${
|
|
81
|
+
`)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${m} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return console.log(`${m} No previous index found - performing full index`),{isIncremental:!1,upToDate:!1};let r=await this.git.getLatestCommitHash();return n===r?(console.log(`${h} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${m} Last indexed commit: ${n.substring(0,8)}`),console.log(`${m} Current commit: ${r.substring(0,8)}`),console.log(`${m} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof E)throw t;return console.log(`${y} Could not determine last index - performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){console.log(`${m} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)console.log(`${y} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let r=await this.git.getChangedFiles(n.latestCommit),o=[...r.added,...r.modified,...r.renamed.map(a=>a.to)];console.log(`${m} Found ${o.length} changed files`),t=await this.scanner.scanSpecificFiles(o,this.config);let i=[...r.deleted,...r.renamed.map(a=>a.from)];if(i.length>0){let a=r.deleted.length,l=r.renamed.length,g=l>0?`${m} Removing ${a} deleted file(s) and ${l} renamed file(s) from graph`:`${m} Removing ${a} deleted file(s) from graph`;console.log(g),await this.apiClient.deleteFiles(i);}}}catch(n){if(n instanceof E)throw n;console.log(`${y} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else console.log(`${m} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return console.log(`${h} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),r=e.length,o=0,i=0;console.log(`${m} Processing ${r} files...`);let a=await this.git.getLatestCommitHash(),l=r>1e4?5:r>5e3?7:10;l<10&&console.log(`${m} Large project detected - using concurrency of ${l} to optimize memory usage`);let d=new Re(l).run(e,async(p,u)=>{let f=Math.round((u+1)/r*100);console.log(`${m} Analyzing file ${p.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let v=await this.parser.parseFile(p.path,p.language),P=this.langRegistry.getPlugin(p.language),ne;if(P?.getImportResolver){let Xe=this.buildConfigManagers.get(p.language),Ze=Xe?await Xe.getConfigForFile(p.path):null,Tt=P.getImportResolver(p.path,Ze);if(Tt){let{ImportExtractor:bn}=await Promise.resolve().then(()=>(Vt(),Kt));ne=await new bn().extractImportResolutions(v,p.path,p.language,Tt);}}let{serializeASTStream:x}=await Promise.resolve().then(()=>(pt(),an)),Se=x(v.rootNode,void 0,p.language),re=await this.compressor.compressStream(Se),S={file:this.normalizePathToCanonical(p.relativePath),language:p.language,commit:a,timestamp:n,ast:re,importResolutions:ne},L=Dt.safeParse(S);if(!L.success)throw new Error(`AST validation failed: ${L.error.issues[0].message}`);return o++,L.data}catch(v){throw i++,console.error(` ${y} Failed to parse ${p.relativePath}: ${v.message}`,v),v}});for await(let p of d)yield p;i>0?console.log(`${y} Completed parsing with ${i} parsing errors`):console.log(`${h} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n))throw new Error("Failed to upload data to Constellation Service");console.log(`${h} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return Te(e)}};var ln=[{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.
|
|
76
82
|
|
|
77
83
|
Mental model:
|
|
78
84
|
- "Where is X defined?" \u2192 {MCP_TOOL_NAME}
|
|
@@ -80,7 +86,7 @@ Mental model:
|
|
|
80
86
|
- "What would break?" \u2192 {MCP_TOOL_NAME}
|
|
81
87
|
- "Find the string 'ERROR_CODE_123'" \u2192 Grep
|
|
82
88
|
|
|
83
|
-
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
|
|
89
|
+
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 ft(){return ln}var pn={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},cr="code_intel";function lr(s){return pn[s]}var de=class{id="cline";displayName="Cline";mapEventName(e){return pn[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,cr)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){let r=lr(n.event);if(!r)continue;let o=`.clinerules/hooks/${r}`,i=this.generateScript(n);t.set(o,i);}return t.size>0?t:void 0}generateScript(e){let n=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return `#!/bin/bash
|
|
84
90
|
# Constellation ${e.event} Hook for Cline
|
|
85
91
|
# Generated by constellation-cli - DO NOT EDIT
|
|
86
92
|
#
|
|
@@ -93,7 +99,7 @@ cat << 'CONSTELLATION_EOF'
|
|
|
93
99
|
"contextModification": "${n}"
|
|
94
100
|
}
|
|
95
101
|
CONSTELLATION_EOF
|
|
96
|
-
`}};var pr={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},gr="constellation__code_intel",q=class{id="cursor";displayName="Cursor";mapEventName(e){return pr[e]}generateConfig(e){let t={};for(let n of e){let r=this.mapEventName(n.event);if(!r)continue;t[r]||(t[r]=[]);let o={type:n.type};n.type==="prompt"&&(o.prompt=this.customizePrompt(n)),n.matcher&&(o.matcher=n.matcher),t[r].push(o);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,gr)}};var dr={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},ur={SessionStart:"startup",SubagentStart:"",PreCompact:""},
|
|
102
|
+
`}};var pr={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},gr="constellation__code_intel",q=class{id="cursor";displayName="Cursor";mapEventName(e){return pr[e]}generateConfig(e){let t={};for(let n of e){let r=this.mapEventName(n.event);if(!r)continue;t[r]||(t[r]=[]);let o={type:n.type};n.type==="prompt"&&(o.prompt=this.customizePrompt(n)),n.matcher&&(o.matcher=n.matcher),t[r].push(o);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,gr)}};var dr={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},ur={SessionStart:"startup",SubagentStart:"",PreCompact:""},fr="code_intel";function gn(s){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[s]}.sh`}var ue=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return dr[e]}generateConfig(e){let t={};for(let n of e){let r=this.mapEventName(n.event);if(!r)continue;t[r]||(t[r]=[]);let o=ur[n.event]??"",i=gn(n.event),a=t[r].find(l=>l.matcher===o);a||(a={matcher:o,hooks:[]},t[r].push(a)),a.hooks.push({name:`constellation-${n.event.toLowerCase()}`,type:"command",command:`$GEMINI_PROJECT_DIR/.gemini/hooks/${i}`,timeout:5e3,description:`Constellation: ${this.getHookDescription(n.event)}`});}return {hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,fr)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){if(!this.mapEventName(n.event))continue;let i=`.gemini/hooks/${gn(n.event)}`,a=this.generateScript(n);t.set(i,a);}return t.size>0?t:void 0}generateScript(e){let n=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return e.event==="PreCompact"?`#!/bin/bash
|
|
97
103
|
# Constellation ${e.event} Hook for Gemini CLI
|
|
98
104
|
# Generated by constellation-cli - DO NOT EDIT
|
|
99
105
|
#
|
|
@@ -116,37 +122,38 @@ cat << 'CONSTELLATION_EOF'
|
|
|
116
122
|
}
|
|
117
123
|
}
|
|
118
124
|
CONSTELLATION_EOF
|
|
119
|
-
`}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]}};var
|
|
125
|
+
`}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]}};var mr=new Map([["cline",new de],["cursor",new q],["gemini",new ue]]);function mt(s){return mr.get(s)}var fe=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureHooks(e,t){if(!e.hooksConfig)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:"Tool does not support hooks configuration"};let n=mt(e.hooksConfig.adapterId);if(!n)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let r=___default.join(this.cwd,e.hooksConfig.filePath),o=n.generateConfig(t),i=Object.keys(o).some(l=>{let g=o[l];return g!=null&&(typeof g!="object"||Object.keys(g).length>0)});if(i){await this.ensureDirectoryExists(r);let l=await this.readConfig(r),g=this.mergeHooksConfig(l,o);await this.writeConfig(r,g);}let a;if(n.generateAuxiliaryFiles){let l=n.generateAuxiliaryFiles(t);l&&(await this.writeAuxiliaryFiles(l),a=Array.from(l.keys()));}return {toolId:e.id,toolDisplayName:e.displayName,success:!0,configuredPath:i?r:void 0,auxiliaryPaths:a}}catch(r){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:r instanceof Error?r.message:String(r)}}}async ensureDirectoryExists(e){let t=___default.dirname(e);await T__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await w.fileIsReadable(e))return {};let n=await w.readFile(e);return JSON.parse(n)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let n=e.hooks??{},r=t.hooks??{},o={...n,...r},i={...e,hooks:o};return t.version!==void 0&&(i.version=t.version),i}async writeConfig(e,t){let n=JSON.stringify(t,null," ");n=n.replace(/\r\n/g,`
|
|
120
126
|
`),n.endsWith(`
|
|
121
127
|
`)||(n+=`
|
|
122
|
-
`),await
|
|
128
|
+
`),await w.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let r=___default.join(this.cwd,t);await this.ensureDirectoryExists(r);let o=n.replace(/\r\n/g,`
|
|
123
129
|
`);o.endsWith(`
|
|
124
130
|
`)||(o+=`
|
|
125
|
-
`),await _.writeFile(r,o),(t.endsWith(".sh")||o.startsWith("#!"))&&await T__default.chmod(r,493);}}};var z=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};var X=class{configPaths=[];parseCache=new Map;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${y} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}if(n){if(this.isJavaScriptEnabled)try{let r=await parse(e,{root:this.projectRoot,configName:"jsconfig.json"});return this.parseCache.set(e,r),r}catch(r){if(this.isTypeScriptEnabled){let o=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,o),o}throw r}if(this.isTypeScriptEnabled){let r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}}return this.parseCache.set(e,null),null}catch(t){return console.warn(`${y} Failed to parse config for ${e}:`,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear();}};Y();Y();var Oe=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let r=e.substring(t.length+1),o=await this.resolveSubPath(n,r);if(o)return this.toProjectRelative(o)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?w.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[r,o]of Object.entries(t)){if(r.includes("*")||!Array.isArray(o))continue;let i=o[0];if(!i)continue;let a=w.resolve(n,i),c=await this.findEntryPoint(a);c&&(e[r]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=w.join(this.projectRoot,"package.json"),n=await T.readFile(t,"utf-8"),o=JSON.parse(n).workspaces;if(!o)return e;let i=Array.isArray(o)?o:o.packages||[];for(let a of i){let c=await this.findWorkspaceDirs(a);for(let g of c){let d=await this.loadWorkspacePackage(g);d&&Object.assign(e,d);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),r=w.join(this.projectRoot,n);try{let o=await T.readdir(r,{withFileTypes:!0});for(let i of o)i.isDirectory()&&t.push(w.join(r,i.name));}catch{}}else {let n=w.join(this.projectRoot,e);try{(await T.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=w.join(e,"package.json"),n=await T.readFile(t,"utf-8"),r=JSON.parse(n),o=r.name;if(!o)return null;let i=await this.findPackageEntryPoint(e,r);return i?{[o]:i}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let r=t.exports;if(typeof r=="string")return w.join(e,r);if(typeof r=="object"){let o=r["."]||r["./index"];if(typeof o=="string")return w.join(e,o);if(typeof o=="object"){let i=o.import||o.default||o.require;if(i)return w.join(e,i)}}}if(t.main)return w.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let r of n){let o=w.join(e,r);try{if((await T.stat(o)).isFile())return o}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let r=w.join(e,n);try{if((await T.stat(r)).isFile())return r}catch{}}try{if((await T.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?w.dirname(e):w.dirname(e),r=[w.join(n,t+".ts"),w.join(n,t+".tsx"),w.join(n,t+".js"),w.join(n,t+".jsx"),w.join(n,t+".d.ts"),w.join(n,t,"index.ts"),w.join(n,t,"index.tsx"),w.join(n,t,"index.js"),w.join(n,t,"index.jsx")];for(let o of r)try{if((await T.stat(o)).isFile())return o}catch{}return null}toProjectRelative(e){let t=H(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};var Z=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=w.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Oe(this.projectRoot,t);let n=e.toLowerCase(),r=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),o=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(r?this.extensions=[".ts",".tsx",".d.ts"]:o?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=w.dirname(t.tsconfigFile);let i=t.tsconfig?.compilerOptions;i&&(i.baseUrl&&(this.baseUrl=w.resolve(this.tsconfigDir,i.baseUrl)),i.paths&&typeof i.paths=="object"&&(this.paths=i.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=w.resolve(this.sourceDir,e),r=await this.findFileWithExtensions(n);return r?this.toProjectRelative(r):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=H(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let r=this.matchPathPattern(e,t);if(r!==null)for(let o of n){let i=await this.trySubstitution(e,t,o,r);if(i)return i}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,r]=t.split("*");if(!e.startsWith(n)||r&&!e.endsWith(r))return null;let o=n.length,i=r?e.length-r.length:e.length;return e.substring(o,i)}async trySubstitution(e,t,n,r){let o=n.replaceAll("*",r),i=w.resolve(this.tsconfigDir,o);return await this.findFileWithExtensions(i)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=w.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 n=[".js",".jsx",".mjs",".cjs"],r=n.some(i=>e.endsWith(i)),o=e;if(r&&!t){for(let i of n)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=w.join(o,`index${i}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await T.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await T.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=w.join(t,"package.json");try{if((await T.stat(n)).isFile())return n}catch{}let r=w.dirname(t);if(r===t)break;t=r;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await T.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=w.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let r=this.matchPathPattern(e,t);if(r!==null){if(typeof n=="string"){let o=await this.tryPackageImportSubstitution(n,r);if(o)return o}if(Array.isArray(n)){for(let o of n)if(typeof o=="string"){let i=await this.tryPackageImportSubstitution(o,r);if(i)return i}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),r=w.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(r)}};var Fe=class extends z{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new X(e,t)}getImportResolver(e,t){return new Z(e,t)}};var Me=class extends z{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new X(e,t)}getImportResolver(e,t){return new Z(e,t)}};je();var De=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=w.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(PYTHON_STDLIB_MODULES.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),r=await this.tryResolveFile(w.resolve(this.projectRoot,n));return r?w.relative(this.projectRoot,r).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),r=t<=1?"":"../".repeat(t-1),o=n?r+n.replace(/\./g,"/"):r.slice(0,-1)||".",i=w.resolve(this.sourceDir,o),a=await this.tryResolveFile(i);return a?w.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,w.join(e,"__init__.py"),w.join(e,"__init__.pyi")];for(let n of t)try{return await Be.promises.access(n,Be.constants.F_OK),n}catch{continue}return null}};var He=class extends z{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new De(e,process.cwd())}};var me={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"]},Ue=class{constructor(e){this.config=e;this.registerPlugin(new Fe),this.registerPlugin(new Me),this.registerPlugin(new He);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>hr,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??me.javascript};typescript={language:()=>_r.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??me.typescript};python={language:()=>yr,fileExtensions:()=>this.config?.languages.python?.fileExtensions??me.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};var wr={stable:"Code",insiders:"Code - Insiders"};function fn(s,e){let t=Q__default.homedir(),n=process.platform,r=wr[s];switch(n){case "darwin":return w__default.join(t,"Library/Application Support",r,"User/globalStorage",e);case "win32":return w__default.join(process.env.APPDATA||w__default.join(t,"AppData/Roaming"),r,"User/globalStorage",e);default:return w__default.join(t,".config",r,"User/globalStorage",e)}}function hn(){let s="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:w__default.join(fn(t,s),"settings","cline_mcp_settings.json")}))}function yn(){return w__default.join(fn("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}function yt(){let s=Q__default.homedir();return w__default.join(s,".copilot","mcp-config.json")}function _n(){return [{displayName:"Copilot CLI",settingsPath:yt()}]}var wn={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Cr={extraKnownMarketplaces:{"constellation-marketplace":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},_t=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:Cr},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:yn(),isGlobalConfig:true,getGlobalConfigPaths:hn,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:yt(),isGlobalConfig:true,getGlobalConfigPaths:_n,format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${CONSTELLATION_ACCESS_KEY}"},mcpServerExtras:{tools:["code_intel"],type:"local"}},{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"]}}];function wt(s){return _t.find(e=>e.id===s)}var Ct=null;async function Cn(){if(!Ct)try{let s=await import('@iarna/toml');Ct={parse:s.parse,stringify:s.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Ct}function xr(s){let e="",t=0,n=s.length;for(;t<n;)if(s[t]==='"'){for(e+='"',t++;t<n&&s[t]!=='"';)s[t]==="\\"?(e+=s[t++],t<n&&(e+=s[t++])):e+=s[t++];t<n&&(e+=s[t++]);}else if(s[t]==="/"&&t+1<n&&s[t+1]==="/")for(t+=2;t<n&&s[t]!==`
|
|
126
|
-
`;)t++;else if(s[t]==="/"&&t+1<n&&s[t+1]==="*"){for(t+=2;t<n&&!(s[t]==="*"&&t+1<n&&s[t+1]==="/");)t++;t<n&&(t+=2);}else e+=s[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Ge=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=
|
|
131
|
+
`),await w.writeFile(r,o),(t.endsWith(".sh")||o.startsWith("#!"))&&await T__default.chmod(r,493);}}};var z=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};var X=class{configPaths=[];parseCache=new Map;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${y} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}if(n){if(this.isJavaScriptEnabled)try{let r=await parse(e,{root:this.projectRoot,configName:"jsconfig.json"});return this.parseCache.set(e,r),r}catch(r){if(this.isTypeScriptEnabled){let o=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,o),o}throw r}if(this.isTypeScriptEnabled){let r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}}return this.parseCache.set(e,null),null}catch(t){return console.warn(`${y} Failed to parse config for ${e}:`,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear();}};Y();Y();var Fe=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let r=e.substring(t.length+1),o=await this.resolveSubPath(n,r);if(o)return this.toProjectRelative(o)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?_.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[r,o]of Object.entries(t)){if(r.includes("*")||!Array.isArray(o))continue;let i=o[0];if(!i)continue;let a=_.resolve(n,i),l=await this.findEntryPoint(a);l&&(e[r]=l);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=_.join(this.projectRoot,"package.json"),n=await T.readFile(t,"utf-8"),o=JSON.parse(n).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 g of l){let d=await this.loadWorkspacePackage(g);d&&Object.assign(e,d);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),r=_.join(this.projectRoot,n);try{let o=await T.readdir(r,{withFileTypes:!0});for(let i of o)i.isDirectory()&&t.push(_.join(r,i.name));}catch{}}else {let n=_.join(this.projectRoot,e);try{(await T.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=_.join(e,"package.json"),n=await T.readFile(t,"utf-8"),r=JSON.parse(n),o=r.name;if(!o)return null;let i=await this.findPackageEntryPoint(e,r);return i?{[o]:i}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let r=t.exports;if(typeof r=="string")return _.join(e,r);if(typeof r=="object"){let o=r["."]||r["./index"];if(typeof o=="string")return _.join(e,o);if(typeof o=="object"){let i=o.import||o.default||o.require;if(i)return _.join(e,i)}}}if(t.main)return _.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let r of n){let o=_.join(e,r);try{if((await T.stat(o)).isFile())return o}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let r=_.join(e,n);try{if((await T.stat(r)).isFile())return r}catch{}}try{if((await T.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?_.dirname(e):_.dirname(e),r=[_.join(n,t+".ts"),_.join(n,t+".tsx"),_.join(n,t+".js"),_.join(n,t+".jsx"),_.join(n,t+".d.ts"),_.join(n,t,"index.ts"),_.join(n,t,"index.tsx"),_.join(n,t,"index.js"),_.join(n,t,"index.jsx")];for(let o of r)try{if((await T.stat(o)).isFile())return o}catch{}return null}toProjectRelative(e){let t=H(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};var Z=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=_.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Fe(this.projectRoot,t);let n=e.toLowerCase(),r=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),o=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(r?this.extensions=[".ts",".tsx",".d.ts"]:o?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=_.dirname(t.tsconfigFile);let i=t.tsconfig?.compilerOptions;i&&(i.baseUrl&&(this.baseUrl=_.resolve(this.tsconfigDir,i.baseUrl)),i.paths&&typeof i.paths=="object"&&(this.paths=i.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=_.resolve(this.sourceDir,e),r=await this.findFileWithExtensions(n);return r?this.toProjectRelative(r):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=H(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let r=this.matchPathPattern(e,t);if(r!==null)for(let o of n){let i=await this.trySubstitution(e,t,o,r);if(i)return i}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,r]=t.split("*");if(!e.startsWith(n)||r&&!e.endsWith(r))return null;let o=n.length,i=r?e.length-r.length:e.length;return e.substring(o,i)}async trySubstitution(e,t,n,r){let o=n.replaceAll("*",r),i=_.resolve(this.tsconfigDir,o);return await this.findFileWithExtensions(i)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=_.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 n=[".js",".jsx",".mjs",".cjs"],r=n.some(i=>e.endsWith(i)),o=e;if(r&&!t){for(let i of n)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=_.join(o,`index${i}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await T.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await T.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=_.join(t,"package.json");try{if((await T.stat(n)).isFile())return n}catch{}let r=_.dirname(t);if(r===t)break;t=r;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await T.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=_.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let r=this.matchPathPattern(e,t);if(r!==null){if(typeof n=="string"){let o=await this.tryPackageImportSubstitution(n,r);if(o)return o}if(Array.isArray(n)){for(let o of n)if(typeof o=="string"){let i=await this.tryPackageImportSubstitution(o,r);if(i)return i}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),r=_.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(r)}};var Me=class extends z{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new X(e,t)}getImportResolver(e,t){return new Z(e,t)}};var De=class extends z{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new X(e,t)}getImportResolver(e,t){return new Z(e,t)}};Ae();var Be=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=_.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(PYTHON_STDLIB_MODULES.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),r=await this.tryResolveFile(_.resolve(this.projectRoot,n));return r?_.relative(this.projectRoot,r).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),r=t<=1?"":"../".repeat(t-1),o=n?r+n.replace(/\./g,"/"):r.slice(0,-1)||".",i=_.resolve(this.sourceDir,o),a=await this.tryResolveFile(i);return a?_.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,_.join(e,"__init__.py"),_.join(e,"__init__.pyi")];for(let n of t)try{return await He.promises.access(n,He.constants.F_OK),n}catch{continue}return null}};var Ue=class extends z{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new Be(e,process.cwd())}};var me={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"]},ze=class{constructor(e){this.config=e;this.registerPlugin(new Me),this.registerPlugin(new De),this.registerPlugin(new Ue);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>hr,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??me.javascript};typescript={language:()=>wr.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??me.typescript};python={language:()=>yr,fileExtensions:()=>this.config?.languages.python?.fileExtensions??me.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};var _r={stable:"Code",insiders:"Code - Insiders"};function mn(s,e){let t=ee__default.homedir(),n=process.platform,r=_r[s];switch(n){case "darwin":return ___default.join(t,"Library/Application Support",r,"User/globalStorage",e);case "win32":return ___default.join(process.env.APPDATA||___default.join(t,"AppData/Roaming"),r,"User/globalStorage",e);default:return ___default.join(t,".config",r,"User/globalStorage",e)}}function hn(){let s="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:___default.join(mn(t,s),"settings","cline_mcp_settings.json")}))}function yn(){return ___default.join(mn("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}function yt(){let s=ee__default.homedir();return ___default.join(s,".copilot","mcp-config.json")}function wn(){return [{displayName:"Copilot CLI",settingsPath:yt()}]}var _n={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Cr={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},wt=[{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:Cr},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:yn(),isGlobalConfig:true,getGlobalConfigPaths:hn,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:yt(),isGlobalConfig:true,getGlobalConfigPaths:wn,format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${CONSTELLATION_ACCESS_KEY}"},mcpServerExtras:{tools:["code_intel"],type:"local"}},{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"]}}];function _t(s){return wt.find(e=>e.id===s)}var Ct=null;async function Cn(){if(!Ct)try{let s=await import('@iarna/toml');Ct={parse:s.parse,stringify:s.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Ct}function xr(s){let e="",t=0,n=s.length;for(;t<n;)if(s[t]==='"'){for(e+='"',t++;t<n&&s[t]!=='"';)s[t]==="\\"?(e+=s[t++],t<n&&(e+=s[t++])):e+=s[t++];t<n&&(e+=s[t++]);}else if(s[t]==="/"&&t+1<n&&s[t+1]==="/")for(t+=2;t<n&&s[t]!==`
|
|
132
|
+
`;)t++;else if(s[t]==="/"&&t+1<n&&s[t+1]==="*"){for(t+=2;t<n&&!(s[t]==="*"&&t+1<n&&s[t+1]==="/");)t++;t<n&&(t+=2);}else e+=s[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Ge=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=___default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){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 r;return n?r=t:e.permissionsConfig?r=___default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?r=___default.join(this.cwd,e.marketplaceConfig.filePath):r=t,{tool:e,success:!0,configuredPath:r}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),n=[];for(let{displayName:r,settingsPath: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),n.push({tool:{...e,displayName:`${e.displayName} (${r})`},success:!0,configuredPath:o});}catch(i){let a=i instanceof Error?i.message:String(i);a.includes("ENOENT")||a.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${r})`},success:false,error:a});}return n}async ensureDirectoryExists(e){let t=___default.dirname(e);await T__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await w.fileIsReadable(e))return {};let r=await w.readFile(e);return t==="json"?JSON.parse(r):t==="jsonc"?JSON.parse(xr(r)):(await Cn()).parse(r)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let i=0;i<t.mcpServersKeyPath.length-1;i++){let a=t.mcpServersKeyPath[i];(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a];}let r=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[r]||typeof n[r]!="object")&&(n[r]={});let o=n[r];if(!o.constellation){let i=t.mcpServerConfigOverride??_n,a={...i};if(t.mcpServerExtras&&Object.assign(a,t.mcpServerExtras),t.mcpEnv){let l=t.mcpEnvKey??"env",g=i[l];a[l]={...g,...t.mcpEnv};}o.constellation=a;}return e}async writeConfig(e,t,n){let r;n==="json"||n==="jsonc"?r=JSON.stringify(t,null,2):r=(await Cn()).stringify(t),r=r.replace(/\r\n/g,`
|
|
127
133
|
`),r.endsWith(`
|
|
128
134
|
`)||(r+=`
|
|
129
|
-
`),await
|
|
130
|
-
`);}async configureMarketplace(e){let t=
|
|
131
|
-
`);}deepMerge(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],i=e[r];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?n[r]=this.deepMerge(i,o):n[r]=o;}return n}addPluginToArray(e,t){let n=e;for(let i=0;i<t.pluginKeyPath.length-1;i++){let a=t.pluginKeyPath[i];(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a];}let r=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[r])||(n[r]=[]);let o=n[r];return o.includes(t.pluginValue)||o.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:r,globalConfigPath:o}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,r),o&&await this.updateGlobalEnvPolicy(o,n,r,t.format);}addToEnvPolicyWhitelist(e,t,n){let r=e;for(let a=0;a<t.length-1;a++){let
|
|
135
|
+
`),await w.writeFile(e,r);}async configurePermissions(e){let t=___default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await w.fileIsReadable(t)){let l=await w.readFile(t);n=JSON.parse(l);}}catch{}let r=n;for(let a=0;a<e.allowKeyPath.length-1;a++){let l=e.allowKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let o=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(r[o])||(r[o]=[]);let i=r[o];i.includes(e.allowValue)||i.push(e.allowValue),await w.writeFile(t,JSON.stringify(n,null," ")+`
|
|
136
|
+
`);}async configureMarketplace(e){let t=___default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await w.fileIsReadable(t)){let o=await w.readFile(t);n=JSON.parse(o);}}catch{}n=this.deepMerge(n,e.config),await w.writeFile(t,JSON.stringify(n,null," ")+`
|
|
137
|
+
`);}deepMerge(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],i=e[r];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?n[r]=this.deepMerge(i,o):n[r]=o;}return n}addPluginToArray(e,t){let n=e;for(let i=0;i<t.pluginKeyPath.length-1;i++){let a=t.pluginKeyPath[i];(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a];}let r=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[r])||(n[r]=[]);let o=n[r];return o.includes(t.pluginValue)||o.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:r,globalConfigPath:o}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,r),o&&await this.updateGlobalEnvPolicy(o,n,r,t.format);}addToEnvPolicyWhitelist(e,t,n){let r=e;for(let a=0;a<t.length-1;a++){let l=t[a];if(!r[l]||typeof r[l]!="object")return;r=r[l];}let o=t[t.length-1];if(!Array.isArray(r[o]))return;let i=r[o];for(let a of n)i.includes(a)||i.push(a);}async updateGlobalEnvPolicy(e,t,n,r){let o=e.replace(/^~/,ee__default.homedir()),i=await this.readConfig(o,r);if(Object.keys(i).length===0)return;let a=JSON.stringify(i);this.addToEnvPolicyWhitelist(i,t,n);let l=JSON.stringify(i);a!==l&&await this.writeConfig(o,i,r);}};var{prompt:vn}=Pn;function he(s,e){let t=___default.normalize(s),n=___default.normalize(e);return t.startsWith(n+___default.sep)?___default.relative(e,s):s}var ye=class extends B{async run(e={}){try{if(console.log(`${F}Initializing project configuration...
|
|
132
138
|
`),!await this.git.isGitAvailable())throw new Error(`${y} Could not find git client installation.
|
|
133
|
-
${
|
|
139
|
+
${m} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=___default.join(process.cwd(),"constellation.json"),r=null,o=await w.fileIsReadable(n);if(o)try{let S=await w.readFile(n);r=JSON.parse(S),console.log(`${m} Found existing constellation.json, current values will be used as defaults.
|
|
134
140
|
`);}catch{console.log(`${y} Existing constellation.json is invalid, starting fresh.
|
|
135
141
|
`);}if(!await this.git.isGitRepository())throw new Error(`${y} Current directory is not a git repository.
|
|
136
|
-
${
|
|
137
|
-
${n}`);}}async configureMCPServers(){let{configureMcp:e}=await vn({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=
|
|
142
|
+
${m} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[l,g]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:d}=l,p=g.filter(S=>S!==d),u=d?[d,...p]:p,f=this.getBranchInitialIndex(u,r?.branch),v=this.getInitialLanguages(r),P=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:r?.projectId??"",validate:S=>S.trim().length>0||"Project ID is required"},{choices:u,initial:f,limit:10,maxChoices:1,message:"Branch to index:",name:"branch",scroll:!0,type:"select"},{type:"multiselect",name:"languages",multiple:!0,message:"Select Language(s):",choices:this.buildLanguageChoices(r),initial:v,result(S){return S.map(L=>this.choices.find(Ze=>Ze.name===L)?.value??L)}}],x=await new Pn().prompt(P),Se={projectId:x.projectId.trim(),branch:x.branch,languages:{...x.languages.reduce((S,L)=>(S[L]={fileExtensions:me[L]||[]},S),{})}},re=JSON.stringify(Se,void 0,2);await w.writeFile(n,re),console.log(`${h} ${o?"Updated":"Initialized"} configuration file at ${he(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${h} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers();}catch(t){let n=t.message??"An unexpected error occurred";console.error(`${C} Failed to initialize configuration file.
|
|
143
|
+
${n}`);}}async configureMCPServers(){let{configureMcp:e}=await vn({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=wt.map(p=>({name:p.displayName,value:p.id})),{selectedTools:n}=await vn({type:"multiselect",name:"selectedTools",message:"Select AI coding assistants to configure:",choices:t,result(p){return p.map(u=>this.choices.find(v=>v.name===u)?.value??u)}});if(n.length===0){console.log(`${m} No tools selected, skipping MCP configuration`);return}let r=new Ge(process.cwd()),o=[];for(let p of n){let u=_t(p);if(u)if(console.log(` ${m} Configuring ${u.displayName}...`),u.isGlobalConfig&&u.getGlobalConfigPaths){let f=await r.configureGlobalTool(u),v=false;for(let P of f)o.push(P),P.success?(v=true,console.log(` ${h} ${P.tool.displayName} configured at ${he(P.configuredPath,process.cwd())}`)):P.error&&console.log(` ${y} ${P.tool.displayName}: ${P.error}`);if(v){let P=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${m} Note: ${u.displayName} uses ${P} (not project-level)`);}if(f.length===0){let P=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${y} ${u.displayName}: ${P}`);}}else {let f=await r.configureTool(u);o.push(f),f.success?(console.log(` ${h} ${u.displayName} configured at ${he(f.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${h} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${y} ${u.displayName}: ${f.error}`);}}if(o.find(p=>p.tool.id==="claude-code"&&p.success)){let p=___default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),console.log(` ${h} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${y} Could not stage .claude/settings.json in git`);}}if(o.find(p=>p.tool.id==="codex-cli"&&p.success)){let p=___default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),console.log(` ${h} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=___default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),console.log(` ${h} Added opencode.jsonc to staged changes in git`);}catch{}}let g=o.filter(p=>p.success).length,d=o.filter(p=>!p.success).length;console.log(`
|
|
138
144
|
${h} MCP configuration complete: ${g} configured`),d>0&&console.log(`${y} ${d} tool(s) could not be configured`),await this.configureHooks(n,o),console.log(`
|
|
139
|
-
${
|
|
140
|
-
${
|
|
145
|
+
${m} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new fe(process.cwd()),r=ft(),o=e.map(l=>_t(l)).filter(l=>l!==void 0&&l.hooksConfig!==void 0&&t.some(g=>g.tool.id===l.id&&g.success));if(o.length===0)return;console.log(`
|
|
146
|
+
${m} Configuring AI hooks...`);let i=[];for(let l of o){let g=await n.configureHooks(l,r);if(i.push(g),g.success){let d=g.configuredPath?[g.configuredPath]:g.auxiliaryPaths??[];if(d.length>0){let p=g.configuredPath?he(g.configuredPath,process.cwd()):___default.dirname(d[0]);console.log(` ${h} ${l.displayName} hooks configured at ${p}`);for(let u of d){let f=___default.isAbsolute(u)?he(u,process.cwd()):u;try{await this.git.stageFile(u),console.log(` ${h} Added ${f} to staged changes in git`);}catch{console.log(` ${y} Could not stage ${f} in git`);}}}else console.log(` ${h} ${l.displayName} hooks configured`);}else console.log(` ${y} ${l.displayName}: ${g.error}`);}let a=i.filter(l=>l.success).length;a>0&&console.log(`${h} Hooks configuration complete: ${a} configured`);}buildLanguageChoices(e){return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}]}getInitialLanguages(e){if(!e?.languages)return [];let t={c:"C","c-sharp":"C#",cpp:"C++",go:"Go",json:"JSON",java:"Java",javascript:"JavaScript",php:"PHP",python:"Python",ruby:"Ruby",bash:"Shell (Bash)",typescript:"TypeScript"};return Object.keys(e.languages).filter(n=>e.languages[n]!==void 0).map(n=>t[n]).filter(n=>n!==void 0)}getBranchInitialIndex(e,t){if(t){let n=e.indexOf(t);if(n!==-1)return n}return 0}};var We=class s{constructor(e,t,n,r){this.branch=e;this.languages=t;this.projectId=n;this.exclude=r;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await w.fileIsReadable(e)){let n=await w.readFile(e),r=JSON.parse(n),o=new s(r.branch,r.languages,r.projectId,r.exclude);return o.validate(),o}else throw new Error(`${C} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let n of t.fileExtensions)if(!n.startsWith("."))throw new Error(`Invalid configuration: file extension "${n}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new Error("Not on a Git branch (detached HEAD state)");if(this.branch!==e)throw new Error(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`)}};var Ke=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(`
|
|
141
147
|
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Pt=class extends Ke{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.
|
|
142
|
-
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,r)=>{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?n():r(new Error(`setx failed with code ${a}: ${i}`));}),o.on("error",a=>{r(a);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let r=(await new Promise((o,i)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),
|
|
143
|
-
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),r=`export ${e}="${n}"`;try{for(let o of this.userConfigFiles)await this.writeToConfigFile(o,e,r);process.env[e]=t;}catch(o){throw new Error(`Failed to set environment variable ${e}: ${o}`)}}async writeToConfigFile(e,t,n){let r="";try{r=await
|
|
148
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,r)=>{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?n():r(new Error(`setx failed with code ${a}: ${i}`));}),o.on("error",a=>{r(a);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let r=(await new Promise((o,i)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),l="",g="";a.stdout?.on("data",d=>{l+=d.toString();}),a.stderr?.on("data",d=>{g+=d.toString();}),a.on("close",d=>{d===0?o(l):i(new Error(`reg query failed: ${g}`));}),a.on("error",d=>{i(d);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return r?r[1].trim():void 0}catch{return}}},xt=class extends Ke{userConfigFiles;constructor(){super(),this.userConfigFiles=[_.join(ee.homedir(),".zshenv"),_.join(ee.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.
|
|
149
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),r=`export ${e}="${n}"`;try{for(let o of this.userConfigFiles)await this.writeToConfigFile(o,e,r);process.env[e]=t;}catch(o){throw new Error(`Failed to set environment variable ${e}: ${o}`)}}async writeToConfigFile(e,t,n){let r="";try{r=await w.readFile(e,"utf-8");}catch{}let o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^export ${o}=.*$`,"gm");i.test(r)?r=r.replace(i,n):r=r.trimEnd()+`
|
|
144
150
|
`+n+`
|
|
145
|
-
`,await
|
|
146
|
-
${
|
|
151
|
+
`,await w.writeFile(e,r);}},St=class{static create(){let e=ee.platform();switch(e){case "win32":return new Pt;case "darwin":case "linux":return new xt;default:throw new Error(`Unsupported platform: ${e}`)}}},Ve=class{manager;constructor(){this.manager=St.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 Je=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let r of n.fileExtensions)this.extensionToLanguageMap.set(r,t);}detectLanguage(e){let t=___default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};function Er(){let s=ee.platform();if(s==="darwin")return _.join(ee.homedir(),"Library","Caches","constellation");if(s==="win32"){let e=process.env.LOCALAPPDATA||_.join(ee.homedir(),"AppData","Local");return _.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||_.join(ee.homedir(),".cache");return _.join(e,"constellation")}}var br=Er(),Ir="update-state.json",$r=1440*60*1e3,_e=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??br,this.stateFile=_.join(this.stateDir,Ir);}async load(){if(this.state)return this.state;try{let e=await T.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await T.mkdir(this.stateDir,{recursive:!0}),await T.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>$r}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 T.unlink(this.stateFile),this.state=null;}catch{}}};var Ce=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...n]=this.getUpdateCommand(e);return new Promise(r=>{let o=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});o.on("close",i=>{r(i===0);}),o.on("error",()=>{r(false);});})}};var{prompt:Nr}=Pn,ve=class{async promptForUpdate(e,t,n){console.log(""),console.log(c.cyan("\u2501".repeat(60))),console.log(`${F} ${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: ${n}`)}`),console.log(c.cyan("\u2501".repeat(60))),console.log("");try{let{shouldUpdate:r}=await Nr({type:"confirm",name:"shouldUpdate",message:"Would you like to update now?",initial:!0});return r}catch{return false}}};var Rr="https://registry.npmjs.org",Ye="@constellationdev/cli",jr=5e3,qe=class{cache;packageManager;prompter;constructor(){this.cache=new _e,this.packageManager=new Ce,this.prompter=new ve;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,n=setTimeout(()=>t.abort(),jr);try{let r=await fetch(`${Rr}/${Ye}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Registry returned ${r.status}`);let i=(await r.json()).version;return {current:e,latest:i,hasUpdate:this.isNewerVersion(i,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=i=>i.split("-")[0],r=n(e).split(".").map(Number),o=n(t).split(".").map(Number);for(let i=0;i<3;i++){let a=r[i]||0,l=o[i]||0;if(a>l)return true;if(a<l)return false}return false}async performUpdate(){return console.log(`
|
|
152
|
+
${m} Updating ${Ye}...
|
|
147
153
|
`),await this.packageManager.executeUpdate(Ye)?(console.log(`
|
|
148
154
|
${h} Update complete! Please re-run your command.
|
|
149
155
|
`),true):(console.log(`
|
|
150
156
|
${y} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Ye)}
|
|
151
|
-
`),false)}};async function
|
|
152
|
-
Modified: ${r.modified}, Created: ${r.created}, Deleted: ${r.deleted}, Conflicted: ${r.conflicted}, Staged: ${r.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let r=await this.git.status();if(r.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",r.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${r.conflicted.length} file(s): ${r.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",n.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(console.error("\u274C Pull failed due to merge conflicts"),console.error(' Run "git status" to see conflicted files'),console.error(' Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?console.error("\u274C Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?console.error("\u274C Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?console.error("\u274C Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&console.error("\u274C Pull failed: Uncommitted changes in working directory"),new Error(`Git pull operation failed: ${e.message}`,{cause:e})):new Error(`Git pull operation failed: ${String(e)}`)}}};
|
|
157
|
+
`),false)}};async function Et(s){return new qe().check(s)}var Ar=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];function Lr(){return Ar.some(s=>!!process.env[s])}function Or(){return !!process.stdout.isTTY}function Sn(){return !Lr()&&Or()}var Pe=class{git;constructor(e){let t={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(t);}async getLatestCommitHash(){let e=await this.git.log({maxCount:1});if(!e.latest)throw new Error("No commits found in repository");return e.latest.hash}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},r=t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);for(let o of r){let i=o.split(" ");if(i.length<2)continue;let a=i[0];a==="A"?n.added.push(i[1]):a==="M"?n.modified.push(i[1]):a==="D"?n.deleted.push(i[1]):a.startsWith("R")&&i.length>=3&&n.renamed.push({from:i[1],to:i[2]});}return n}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(n=>n.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,n=e.current;return {clean:t,currentBranch:n}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let r={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw console.error("\u274C Cannot pull: Working directory has uncommitted changes"),console.error(" Details:",JSON.stringify(r,null,2)),e.conflicted.length>0&&console.error(" \u26A0\uFE0F Conflicted files:",e.conflicted.join(", ")),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
|
|
158
|
+
Modified: ${r.modified}, Created: ${r.created}, Deleted: ${r.deleted}, Conflicted: ${r.conflicted}, Staged: ${r.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let r=await this.git.status();if(r.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",r.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${r.conflicted.length} file(s): ${r.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",n.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(console.error("\u274C Pull failed due to merge conflicts"),console.error(' Run "git status" to see conflicted files'),console.error(' Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?console.error("\u274C Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?console.error("\u274C Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?console.error("\u274C Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&console.error("\u274C Pull failed: Uncommitted changes in working directory"),new Error(`Git pull operation failed: ${e.message}`,{cause:e})):new Error(`Git pull operation failed: ${String(e)}`)}}};process.on("uncaughtException",s=>{s instanceof Error&&s.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${C} An unexpected error occurred during the index attempt:
|
|
159
|
+
${s?.message??String(s)}`),process.exit(1);});var Hr=___default.dirname(fileURLToPath(import.meta.url)),Ur=___default.join(Hr,"..","package.json"),zr=JSON.parse(readFileSync(Ur,"utf-8")),En=zr.version,Gr=["help","--help","-h","--version","-V","-v"];if(Sn()){let s=process.argv[2];["auth","help","init","index"].includes(s)?Qe(s):Qe(),Gr.includes(s)||await Et(En)&&process.exit(0);}var bt=process.cwd(),It=new Ve,xe=new Command;xe.name("constellation").description("Connecting stars in your code into intelligent patterns").version(En);xe.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").action(async s=>{try{let t={GitClient:new Pe(bt)};await new ye(t).run({skipMcp:s.skipMcp});}catch(e){console.error(`${C} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});xe.command("auth").description("Configure authentication for the Constellation CLI").action(async()=>{try{let s={Environment:It};await new se(s).run();}catch(s){console.error(`${C} Failed to configure authentication: ${s instanceof Error?s.message:String(s)}`),process.exit(1);}});xe.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)").action(async s=>{try{let e=await We.loadFromFile(___default.join(bt,"constellation.json")),t=new Pe(bt),n=new ze(e),r=new Je(e),o={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:r,Environment:It},i=It.isCI(),a=s.full||!s.incremental&&i,l=s.dirty||!1;!s.full&&!s.incremental&&i&&console.log(`${m} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new ge(o).run(a,l);}catch(e){!(e instanceof E)&&!(e instanceof $)&&console.error(`${C} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});xe.parse();
|