@constellationdev/cli 0.1.6 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +94 -60
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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
|
-
`,
|
|
4
|
-
Caused by: ${l.stack}`,d}}async sendRequest(e,t,n,
|
|
2
|
+
import*as _ from'path';import ___default from'path';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import*as We 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 oe from'os';import oe__default from'os';import {randomBytes}from'crypto';import An from'enquirer';import {execFile,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {performance}from'perf_hooks';import*as k from'fs/promises';import k__default from'fs/promises';import po from'tree-sitter';import Yt from'ignore';import {z}from'zod';import st from'zlib';import {pipeline}from'stream/promises';import jo from'tree-sitter-javascript';import Lo from'tree-sitter-python';import Oo from'tree-sitter-typescript';import {findAll,parse}from'tsconfck';import {parseDocument,isMap,isSeq}from'yaml';import {simpleGit}from'simple-git';var Dn=Object.defineProperty;var A=(s,e)=>()=>(s&&(e=s(s=0)),e);var Dt=(s,e)=>{for(var t in e)Dn(s,t,{get:e[t],enumerable:true});};function Jt(s){return s.replace(/\\/g,"/")}function Re(s){return Jt(s).replace(/^\.?\//,"")}function H(s,e){return Jt(_.relative(s,e))}var q=A(()=>{});async function U(s,e,t,n,o){let r=await t.resolve(s),i=Qt(s,r),a=o(s,r,i),l=i?void 0:Re(r);n[e.toString()]={source:s,resolvedPath:l,isExternal:i,importType:a};}function Qt(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var at,pe=A(()=>{q();at=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function ho(s,e,t,n){let o=s.childForFieldName("source");if(!o)return;let r=o.startPosition.row,i=o.text.replace(/['"]/g,"");await U(i,r,e,t,n);}async function yo(s,e,t,n){let o=s.childForFieldName("source");if(!o)return;let r=o.startPosition.row,i=o.text.replace(/['"]/g,"");await U(i,r,e,t,n);}function Oe(){return {language:"javascript",handlers:new Map([["import_statement",ho],["export_statement",yo]])}}function ct(){return {...Oe(),language:"typescript"}}var lt=A(()=>{pe();});async function _o(s,e,t,n){let o=s.childForFieldName("name");if(!o)return;let r;if(o.type==="aliased_import"){let i=o.childForFieldName("name");r=i?i.text:o.text;}else r=o.text;await U(r,s.startPosition.row,e,t,n);}async function vo(s,e,t,n){let o,r=s.childForFieldName("module_name");if(r)o=r.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);}}o=i||".";}await U(o,s.startPosition.row,e,t,n);}async function Po(s,e,t,n){await U("__future__",s.startPosition.row,e,t,n);}function pt(){return {language:"python",handlers:new Map([["import_statement",_o],["import_from_statement",vo],["future_import_statement",Po]]),classifyImportType:wo}}var wo,Fe=A(()=>{pe();wo=(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 tn,nn=A(()=>{lt();Fe();pe();lt();Fe();tn=[Oe(),ct(),pt()];});var on={};Dt(on,{ImportExtractor:()=>gt});var gt,rn=A(()=>{nn();pe();gt=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??tn)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,o){if(!o)return {};let r=this.languageHandlers.get(n);if(!r)return {};let i=this.classifiers.get(n)??at,a={};return await this.walkAST(e.rootNode,async l=>{let g=r.get(l.type);g&&await g(l,o,a,i);}),a}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let o=e.child(n);o&&await this.walkAST(o,t);}}};});var ge,sn,dt,an,cn,De=A(()=>{ge=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"]),sn=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"]),dt={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"]},an={language:"javascript",textIncludedTypes:sn,fieldNames:dt},cn={language:"typescript",textIncludedTypes:sn,fieldNames:dt};});var xo,ln,pn,ut=A(()=>{xo=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"]),ln={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"]},pn={language:"python",textIncludedTypes:xo,fieldNames:ln,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function gn(s){return de.get(s)}function dn(s){if(!s)return ge;let e=de.get(s);if(!e)return ge;let t=new Set(ge);for(let n of e.textIncludedTypes)t.add(n);return t}function ft(s){if(!s){let t=Array.from(de.values()).map(n=>n.fieldNames);return ue(...t)}let e=de.get(s);if(!e){let t=Array.from(de.values()).map(n=>n.fieldNames);return ue(...t)}return e.fieldNames}var de,un=A(()=>{mt();De();ut();De();De();ut();de=new Map([["javascript",an],["typescript",cn],["python",pn]]);});var Cn={};Dt(Cn,{COMMON_FIELD_NAMES:()=>Ct,JS_TS_FIELD_NAMES:()=>hn,PYTHON_FIELD_NAMES:()=>yn,TEXT_INCLUDED_TYPES:()=>fn,mergeFieldMaps:()=>ue,serializeAST:()=>So,serializeASTStream:()=>bo});function*bo(s,e,t){yield*yt(s,e,t);}function*yt(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)}`),mn(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let o=(t?ft(t):Ct)[s.type]||[],r=new Set,i=true;for(let a of o){let l=s.childForFieldName(a);l&&(i||(yield ","),i=false,r.add(l),yield*yt(l,a,t));}for(let a=0;a<s.childCount;a++){let l=s.child(a);l&&!r.has(l)&&(i||(yield ","),i=false,yield*yt(l,void 0,t));}yield "]";}yield "}";}async function So(s,e,t){let n=ht(s,e,t),o=t?ft(t):Ct,r=[{treeNode:s,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;r.length>0;){let i=r[r.length-1];if(i.childIndex===0&&i.treeNode.childCount>0){let a=o[i.treeNode.type]||[];for(let l of a){let g=i.treeNode.childForFieldName(l);if(g){i.fieldChildren.add(g);let d=ht(g,l,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(d),r.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=ht(a,void 0,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(l),r.push({treeNode:a,serializedNode:l,childIndex:0,fieldChildren:new Set});}}else r.pop();}return n}function ht(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 mn(s,t)&&(n.text=s.text),n}function mn(s,e){if(e){let n=gn(e);if(n?.shouldIncludeText){let r=n.shouldIncludeText(s);if(r===false)return false;if(r===true)return true}return dn(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:fn.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function ue(...s){let e={};for(let t of s)for(let[n,o]of Object.entries(t)){let i=[...e[n]||[]];for(let a of o)i.includes(a)||i.push(a);e[n]=i;}return e}var fn,hn,yn,Ct,mt=A(()=>{un();fn=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"]);hn={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"]},yn={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"]};Ct=ue(hn,yn);});function Mt(s){return base32.encode(Buffer.from(s))}function Bt(s,e,t){let n=`${s}:${e}${t?`:${t}`:""}`;return Mt(n)}var $e=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
|
+
`,o=Buffer.from(n,"utf8");if(!this.push(o))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};function Hn(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:oe.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 Un="\u2714",Gn="\u2717",Wn="\u26A0",zn="\u2139",Kn="\u26A1",Vn="[OK]",Jn="[ERR]",Yn="[WARN]",qn="[INFO]",Xn="[>>]",ce=Hn(),y=c.green(ce?Un:Vn),v=c.red(ce?Gn:Jn),C=c.yellow(ce?Wn:Yn),h=c.blue(ce?zn:qn),F=c.yellow(ce?Kn:Xn);var ke=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 D("Project not found - no previous index exists");default:throw e.status===404?new D("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 D?t:e.status===404?new D("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let r=await this.sendRequest(o,null,"GET");return !r||!r.ok?null:await r.json()}catch(r){if(r instanceof S)throw r;return null}}async deleteFiles(e){for(let t of e){let n=Bt(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,o,r,i){try{let{Readable:a}=await import('stream'),l=new $e(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":o,"x-constellation-index":r?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...i&&{"x-commit-hash":i}},body:g,duplex:"half",dispatcher:d});if(p.status===401)throw new S("Authentication failed");if(p.status===409){let f="Indexing already in progress",P;try{let w=await p.json();f=w?.message||f,P=w?.details?.branchName;}catch{}throw new Y(f,P)}if(p.status===200)try{let f=await p.json();if(f?.status==="current")return console.log(`${y} Index already up to date for ${o} at commit ${f.commitHash||"unknown"}`),!0}catch{}if(p.ok||p.status===202)return !0;let u=`Server returned ${p.status}`;try{let f=await p.json();f?.message&&(u=Array.isArray(f.message)?f.message.join("; "):f.message);}catch{}throw new Error(u)}catch(a){if(a instanceof S||a instanceof Y)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,o={},r=0,i=3,a=1e3,l=250){for(let g=1;g<=i;g++)try{let d=new AbortController,p;r>0&&(p=setTimeout(()=>d.abort(),r));let u={...o,"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 S("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new Te(`${f.statusText} (${f.status})`);return f}catch(d){if(!(d instanceof S)){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 Te){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}`)}},Te=class extends Error{constructor(e){super(e),this.name="RetryableError";}},S=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},D=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},$=class extends Error{constructor(t,n,o){super(t);this.code=n;this.projectId=o;this.name="ProjectValidationError";}},Y=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}};var ot=promisify(execFile);async function Ut(s){if(!s.startsWith("http://")&&!s.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await ot("open",[s]),!0;case "linux":return await ot("xdg-open",[s]),!0;case "win32":return await ot("cmd",["/c","start","",s]),!0;default:return !1}}catch{return false}}var oo=/^ak:[0-9a-f]{32}$/i,ro=`<!DOCTYPE html>
|
|
5
|
+
<html><head><title>Authentication Successful</title></head>
|
|
6
|
+
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;function Gt(){return new Promise((s,e)=>{let t=createServer(),n,o=false;t.listen(0,"127.0.0.1",()=>{let r=t.address();if(!r||typeof r=="string"){t.close(),e(new Error("Failed to bind callback server"));return}s({port:r.port,close(){n&&(clearTimeout(n),n=void 0),t.close();},waitForCallback(i,a=3e5){return new Promise((l,g)=>{n=setTimeout(()=>{n=void 0,o=true,t.close(),g(new Error("Authentication timed out"));},a),t.on("request",(d,p)=>{let u=new URL(d.url??"/",`http://127.0.0.1:${r.port}`);if(u.pathname!=="/callback"){p.writeHead(404,{"Content-Type":"text/plain"}),p.end("Not found");return}let f=u.searchParams.get("key");if(u.searchParams.get("state")!==i){p.writeHead(400,{"Content-Type":"text/plain"}),p.end("Invalid state parameter");return}if(!f||!oo.test(f)){p.writeHead(400,{"Content-Type":"text/plain"}),p.end("Invalid key format");return}if(o)return;o=true;let w=u.searchParams.get("return_url");w?(p.writeHead(302,{Location:w}),p.end()):(p.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),p.end(ro)),n&&(clearTimeout(n),n=void 0),t.close(),l(f);});})}});}),t.on("error",r=>{e(r);});})}function rt(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
7
|
\u2502 ${c.gray("'")} ${c.blueBright(".")} ${c.dim("`")} ${c.yellowBright("'")} ${c.blueBright("+")} ${c.whiteBright(".")} ${c.gray(".")} ${c.yellowBright("'")} ${c.yellowBright("*")} ${c.whiteBright("'")} ${c.blueBright("+")} ${c.gray(".")} ${c.yellowBright("*")} ${c.whiteBright(",")} ${c.gray.dim(".")}\u2502
|
|
6
8
|
\u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
|
|
7
9
|
\u2502 ${c.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${c.gray(".")} ${c.yellowBright("'")} ${c.gray("+")} ${c.gray("\\")} ${c.gray("`")} \u2502
|
|
@@ -27,10 +29,10 @@ ${c.gray(" \\")}
|
|
|
27
29
|
${c.blueBright(" o")}${c.blueBright("----")}${c.yellowBright("o")} ${c.gray("o")}
|
|
28
30
|
${c.gray(" \\ \\ ")}${c.blueBright("/")}
|
|
29
31
|
${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
|
|
30
|
-
`;var
|
|
31
|
-
`),this.env.isCI()){console.error(`${
|
|
32
|
+
`;var M="CONSTELLATION_ACCESS_KEY",Wt="CONSTELLATION_WEB_URL";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:zt}=An,ao=/^ak:[0-9a-f]{32}$/i;function co(s){return ao.test(s)}function lo(s){return s.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var le=class extends B{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${F}Configuring access key authentication...
|
|
33
|
+
`),this.env.isCI()){console.error(`${v} Cannot configure authentication in CI/CD environments
|
|
32
34
|
|
|
33
|
-
The ${
|
|
35
|
+
The ${M} environment variable must be configured
|
|
34
36
|
directly in your pipeline settings:
|
|
35
37
|
|
|
36
38
|
- GitHub Actions: Repository Settings -> Secrets and variables -> Actions
|
|
@@ -38,39 +40,45 @@ ${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
|
|
|
38
40
|
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
39
41
|
- Jenkins: Manage Jenkins -> Credentials
|
|
40
42
|
- CircleCI: Project Settings -> Environment Variables
|
|
41
|
-
`);return}if(await this.env.getKey(
|
|
42
|
-
`),n
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
`);return}if(await this.env.getKey(M)){let{replaceKey:n}=await zt({message:"Replace existing Constellation access key?",name:"replaceKey",type:"confirm",initial:!1});if(!n){console.log(`${y} Keeping existing Constellation access key`);return}}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){let n=t.message??"An unexpected error occurred",o=lo(n);console.error(`${v} Failed to store Constellation access key
|
|
44
|
+
${o}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await zt({message:"Constellation Access Key:",name:"accessKey",type:"password",required:true})).accessKey.trim(),!e){console.log(`${C} Access key cannot be empty.
|
|
45
|
+
`),t++;continue}if(!co(e)){if(t++,t<n)console.log(`${C} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
46
|
+
Attempts remaining: ${n-t}
|
|
47
|
+
`);else {console.error(`${v} Invalid access key format after ${n} attempts.
|
|
48
|
+
Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),{port:t,waitForCallback:n}=await Gt(),r=`${process.env[Wt]||"https://app.constellationdev.io"}/auth/cli?callback_port=${t}&state=${e}`;console.log(`${h} Opening browser for authentication...`),await Ut(r)||console.log(`${C} Could not open browser automatically.
|
|
49
|
+
Please open this URL manually:
|
|
46
50
|
|
|
47
|
-
|
|
51
|
+
${r}
|
|
52
|
+
`),console.log(`${h} Waiting for authentication... (press Ctrl+C to cancel)
|
|
53
|
+
`);try{let a=await n(e);await this.storeKey(a);}catch{console.error(`${v} Authentication timed out.
|
|
54
|
+
Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(M,e),console.log(`${y} Stored access key in ${M} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${h} To activate in this session, run:
|
|
48
55
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
`);let r=
|
|
52
|
-
|
|
53
|
-
${
|
|
54
|
-
${
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
56
|
+
source ${t}
|
|
57
|
+
|
|
58
|
+
New terminal sessions will load it automatically.`);}};var m={async directoryExists(s){try{return (await k__default.stat(s)).isDirectory()}catch{return false}},async fileIsReadable(s){try{return await k__default.access(s,k__default.constants.R_OK),!0}catch{return false}},async readFile(s,e="utf-8"){let t=await k__default.readFile(s,{encoding:e,flag:k__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 k__default.writeFile(s,n,{encoding:t,flag:k__default.constants.O_WRONLY|k__default.constants.O_CREAT|k__default.constants.O_TRUNC});},async getFileStats(s){return await k__default.stat(s)},async getFileHandle(s,e,t){return await k__default.open(s,e,t)}};var Ne=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let o=await n();if(!o)throw new Error(`Failed to load language: ${t}`);let r=new po;r.setLanguage(o);let i=await m.getFileStats(e),a=10*1024*1024;if(i.size<=a){let l=await m.readFile(e),g={bufferSize:1024*1024};return r.parse(l,void 0,g)}else return this.parseWithStream(r,e,i.size)}async parseWithStream(e,t,n){let o=null;try{o=await k.open(t,"r");let r=o.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=We.readSync(r,a,0,i,d);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(r){if(o)try{await o.close();}catch(i){console.error(`Warning: Failed to close file handle for ${t}:`,i);}throw r}finally{if(o)try{await o.close();}catch{}}}};q();var Ae=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Yt();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(r=>!t.ignores(r.relativePath)&&this.matchesLanguageExtension(r,e.languages))}async scanSpecificFiles(e,t){let n=[],o=null;t.exclude&&t.exclude.length>0&&(o=Yt().add(t.exclude));let r=await k__default.realpath(this.rootPath);for(let i of e)try{let a=___default.isAbsolute(i)?i:___default.join(this.rootPath,i),l=await k__default.lstat(a);if(l.isSymbolicLink()){let g=await k__default.realpath(a);if(!g.startsWith(r+___default.sep)&&g!==r){console.warn(`${C} Skipping symlink pointing outside project: ${i} -> ${g}`);continue}let d=await k__default.stat(a);if(!d.isFile())continue;let p=H(this.rootPath,a);if(o&&o.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(o&&o.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(`${C} Skipping inaccessible file: ${i}`);}return n}async loadGitignoreRules(e,t){let n=[],o=t;for(;;){let r=___default.join(o,".gitignore");await m.fileIsReadable(r)&&n.unshift(r);let i=___default.dirname(o);if(i===o)break;o=i;let a=___default.join(o,".git");if(await m.directoryExists(a)){let l=___default.join(o,".gitignore");await m.fileIsReadable(l)&&!n.includes(l)&&n.unshift(l);break}}for(let r of n)try{let i=await m.readFile(r);e.add(i);}catch{console.warn(`${C} Failed to load .gitignore: ${r}`);}e.add(".git");}async walkDirectory(e,t,n){let o=[],r=t||e,i=n||await k__default.realpath(this.rootPath);try{let a=await k__default.readdir(e,{withFileTypes:!0});for(let l of a){let g=___default.join(e,l.name),d=H(r,g);if(l.isDirectory()){if(l.name.startsWith("."))continue;let p=await this.walkDirectory(g,r,i);o.push(...p);}else if(l.isFile()){let p=await k__default.stat(g);o.push({path:g,relativePath:d,language:"",size:p.size});}else if(l.isSymbolicLink())try{let p=await k__default.realpath(g);if(!p.startsWith(i+___default.sep)&&p!==i){console.warn(`${C} Skipping symlink pointing outside project: ${g} -> ${p}`);continue}let u=await k__default.stat(g);if(u.isDirectory()){if(l.name.startsWith("."))continue;let f=await this.walkDirectory(g,r,i);o.push(...f);}else u.isFile()&&o.push({path:g,relativePath:d,language:"",size:u.size});}catch{console.warn(`${C} Skipping invalid symlink: ${g}`);}}}catch(a){console.error(`${v} Error walking directory ${e}:`,a);}return o}matchesLanguageExtension(e,t){let n=___default.extname(e.path).toLowerCase();for(let[o,r]of Object.entries(t))if(r.fileExtensions.includes(n))return e.language=o,true;return false}detectLanguage(e,t){let n=___default.extname(e).toLowerCase();for(let[o,r]of Object.entries(t))if(r.fileExtensions.includes(n))return o;return null}};var go=z.object({source:z.string().min(1,"Import source cannot be empty"),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:z.enum(["relative","workspace","alias","external","builtin"])}),uo=z.record(z.string(),go),qt=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:uo.optional()});var mo=promisify(st.gunzip),je=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=st.createGzip();n.on("data",i=>t.push(i));let o=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),r=Readable.from(e);return await pipeline(r,n),await o,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=st.createGzip();n.on("data",i=>t.push(i));let o=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),r=Readable.from(this.serializeASTChunks(e));return await pipeline(r,n),await o,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await mo(t);return JSON.parse(n.toString("utf-8"))}};var Le=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,o=0,r=0;for(;r<e.length&&n.size<this.concurrency;){let i=o++,a=this.processItem(e[r],r,t).then(l=>({result:l!==null?l.result:null,promiseId:i}));n.set(i,a),r++;}for(;n.size>0;){let i=await Promise.race(n.values());if(n.delete(i.promiseId),i.result!==null&&(yield i.result),r<e.length){let a=o++,l=this.processItem(e[r],r,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,l),r++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};q();var fe=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 Ae(process.cwd()),this.parser=new Ne(this.langRegistry),this.compressor=new je;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let o=n.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false){try{let n=await this.getAccessKey();this.apiClient=new ke(this.config,n),await this.validateProject(),console.log(`${F}Starting indexing procedure...
|
|
59
|
+
`);let o=performance.now();if(t?console.log(`${C} Skipping git branch validation`):await this.validateGitBranch(),t?console.log(`${C} Skipping git status validation`):await this.validateGitStatus(),t?console.log(`${C} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){console.log(`${h} Discovering language build configurations...`);let x=0;for(let[Ie,se]of this.buildConfigManagers.entries()){let b=await se.initialize();x+=b.length;}x>0&&console.log(`${y} Found ${x} configuration file(s)`);}let r=await this.determineIndexScope(e),i=await this.git.getLatestCommitHash();if(r.upToDate){console.log(`
|
|
60
|
+
${y} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${i.substring(0,8)}`);return}if(r.isIncremental&&i){let x=await this.apiClient.getIndexStatus(this.config.branch,i);if(x?.status==="current"||x?.status==="processing"&&x?.commitHash===i){console.log(`${y} Index already up to date for branch ${this.config.branch} at commit ${i.substring(0,8)}`);return}}let a=await this.discoverFiles(r.isIncremental),l=!1,g=()=>{l||console.log(`${h} Uploading metadata, processing, and indexing...`);},d=this.generateASTs(a,g);try{await this.uploadToAPI(d,r.isIncremental,i),l=!0;}catch(x){throw l=!0,x}let f=(performance.now()-o)/1e3,P=Math.floor(f/60),w=(f%60).toFixed(3),ie=P>0?`${P}m ${w}s`:`${w}s`;console.log(`
|
|
61
|
+
${y} Upload completed in ${ie}! Server indexing in progress.`);}catch(n){if(n instanceof $)throw n;if(n instanceof Y)throw console.error(`${v} 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 S)throw console.error(`
|
|
62
|
+
${v} Authentication failed.`),console.log(`${h} Your access key may be invalid or expired. Run 'constellation auth'
|
|
63
|
+
to set or update your access key.`),n;if(n instanceof Error&&n.message==="Access key not configured")throw n;let o=n instanceof Error?n.message:"An unexpected error occurred";throw console.error(`${v} Indexing failed: ${o}`),n}}async getAccessKey(){let e=await this.env.getKey(M);if(!e)throw console.error(`
|
|
64
|
+
${v} Access key not found.`),console.log(`${h} Set the ${M} environment variable or run
|
|
65
|
+
'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){console.log(`${h} Validating project access...`);try{await this.apiClient.getProjectState(),console.log(`${y} Project validated successfully`);}catch(e){if(e instanceof $)throw this.displayProjectValidationError(e),e;if(e instanceof D){console.log(`${y} Project validated (first index)`);return}if(e instanceof S)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
66
|
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(`
|
|
59
|
-
${
|
|
67
|
+
${v} Project not registered
|
|
60
68
|
`),console.error(` The project ID "${n}" in constellation.json`),console.error(` is not associated with your Constellation account.
|
|
61
69
|
`),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
|
|
62
70
|
`);break;case "PROJECT_INACTIVE":console.error(`
|
|
63
|
-
${
|
|
71
|
+
${v} Project is inactive
|
|
64
72
|
`),console.error(` The project "${n}" has been deactivated.
|
|
65
73
|
`),console.error(" To resolve this:"),console.error(" 1. Reactivate the project at https://app.constellationdev.io"),console.error(` 2. Run 'constellation index' again
|
|
66
74
|
`);break;case "INVALID_PROJECT_ID":console.error(`
|
|
67
|
-
${
|
|
75
|
+
${v} Invalid project ID
|
|
68
76
|
`),console.error(` The project ID "${n}" in constellation.json`),console.error(` is not a valid Constellation project identifier.
|
|
69
77
|
`),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
|
|
70
78
|
`);break;default:console.error(`
|
|
71
|
-
${
|
|
72
|
-
`);}}async validateGitBranch(){console.log(`${
|
|
73
|
-
Commit or stash changes first to ensure consistent indexing.`);console.log(`${
|
|
79
|
+
${v} Project validation failed: ${e.message}
|
|
80
|
+
`);}}async validateGitBranch(){console.log(`${h} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),console.log(`${y} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(console.log(`${h} Validating Git status...`),!(await this.git.status()).clean)throw new Error(`Outstanding changes detected.
|
|
81
|
+
Commit or stash changes first to ensure consistent indexing.`);console.log(`${y} Working tree clean`);}async synchronizeChanges(){console.log(`${h} Synchronizing latest changes...`);try{await this.git.pull()&&console.log(`${y} Repository synchronized successfully`);}catch(e){throw console.error(`${v} Failed to synchronize repository`),e instanceof Error&&(e.message.includes("uncommitted changes")?(console.error(`
|
|
74
82
|
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
|
|
75
83
|
`)):e.message.includes("merge conflicts")?(console.error(`
|
|
76
84
|
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
|
|
@@ -78,7 +86,7 @@ To resolve:`),console.error(" 1. Fix the conflicted files manually"),console.er
|
|
|
78
86
|
Please check your internet connection and try again
|
|
79
87
|
`):e.message.includes("Authentication")&&console.error(`
|
|
80
88
|
Please check your git credentials and try again
|
|
81
|
-
`)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${
|
|
89
|
+
`)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${h} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return console.log(`${h} No previous index found - performing full index`),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return n===o?(console.log(`${y} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${h} Last indexed commit: ${n.substring(0,8)}`),console.log(`${h} Current commit: ${o.substring(0,8)}`),console.log(`${h} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof S)throw t;return console.log(`${C} Could not determine last index - performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){console.log(`${h} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)console.log(`${C} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let o=await this.git.getChangedFiles(n.latestCommit),r=[...o.added,...o.modified,...o.renamed.map(a=>a.to)];console.log(`${h} Found ${r.length} changed files`),t=await this.scanner.scanSpecificFiles(r,this.config);let i=[...o.deleted,...o.renamed.map(a=>a.from)];if(i.length>0){let a=o.deleted.length,l=o.renamed.length,g=l>0?`${h} Removing ${a} deleted file(s) and ${l} renamed file(s) from graph`:`${h} Removing ${a} deleted file(s) from graph`;console.log(g),await this.apiClient.deleteFiles(i);}}}catch(n){if(n instanceof S)throw n;console.log(`${C} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else console.log(`${h} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return console.log(`${y} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),o=e.length,r=0,i=0;console.log(`${h} Processing ${o} files...`);let a=await this.git.getLatestCommitHash(),l=o>1e4?5:o>5e3?7:10;l<10&&console.log(`${h} Large project detected - using concurrency of ${l} to optimize memory usage`);let d=new Le(l).run(e,async(p,u)=>{let f=Math.round((u+1)/o*100);console.log(`${h} Analyzing file ${p.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let P=await this.parser.parseFile(p.path,p.language),w=this.langRegistry.getPlugin(p.language),ie;if(w?.getImportResolver){let tt=this.buildConfigManagers.get(p.language),nt=tt?await tt.getConfigForFile(p.path):null,Ft=w.getImportResolver(p.path,nt);if(Ft){let{ImportExtractor:Fn}=await Promise.resolve().then(()=>(rn(),on));ie=await new Fn().extractImportResolutions(P,p.path,p.language,Ft);}}let{serializeASTStream:x}=await Promise.resolve().then(()=>(mt(),Cn)),Ie=x(P.rootNode,void 0,p.language),se=await this.compressor.compressStream(Ie),b={file:this.normalizePathToCanonical(p.relativePath),language:p.language,commit:a,timestamp:n,ast:se,importResolutions:ie},L=qt.safeParse(b);if(!L.success)throw new Error(`AST validation failed: ${L.error.issues[0].message}`);return r++,L.data}catch(P){throw i++,console.error(` ${C} Failed to parse ${p.relativePath}: ${P.message}`,P),P}});for await(let p of d)yield p;i>0?console.log(`${C} Completed parsing with ${i} parsing errors`):console.log(`${y} 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(`${y} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return Re(e)}};var _n=[{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.
|
|
82
90
|
|
|
83
91
|
Mental model:
|
|
84
92
|
- "Where is X defined?" \u2192 {MCP_TOOL_NAME}
|
|
@@ -86,7 +94,7 @@ Mental model:
|
|
|
86
94
|
- "What would break?" \u2192 {MCP_TOOL_NAME}
|
|
87
95
|
- "Find the string 'ERROR_CODE_123'" \u2192 Grep
|
|
88
96
|
|
|
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
|
|
97
|
+
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 wt(){return _n}var vn={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},Eo="code_intel";function Io(s){return vn[s]}var me=class{id="cline";displayName="Cline";mapEventName(e){return vn[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,Eo)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){let o=Io(n.event);if(!o)continue;let r=`.clinerules/hooks/${o}`,i=this.generateScript(n);t.set(r,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
|
|
90
98
|
# Constellation ${e.event} Hook for Cline
|
|
91
99
|
# Generated by constellation-cli - DO NOT EDIT
|
|
92
100
|
#
|
|
@@ -99,7 +107,7 @@ cat << 'CONSTELLATION_EOF'
|
|
|
99
107
|
"contextModification": "${n}"
|
|
100
108
|
}
|
|
101
109
|
CONSTELLATION_EOF
|
|
102
|
-
`}};var
|
|
110
|
+
`}};var $o={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},ko="constellation__code_intel",X=class{id="cursor";displayName="Cursor";mapEventName(e){return $o[e]}generateConfig(e){let t={};for(let n of e){let o=this.mapEventName(n.event);if(!o)continue;t[o]||(t[o]=[]);let r={type:n.type};n.type==="prompt"&&(r.prompt=this.customizePrompt(n)),n.matcher&&(r.matcher=n.matcher),t[o].push(r);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,ko)}};var To={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},No={SessionStart:"startup",SubagentStart:"",PreCompact:""},Ro="code_intel";function Pn(s){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[s]}.sh`}var he=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return To[e]}generateConfig(e){let t={};for(let n of e){let o=this.mapEventName(n.event);if(!o)continue;t[o]||(t[o]=[]);let r=No[n.event]??"",i=Pn(n.event),a=t[o].find(l=>l.matcher===r);a||(a={matcher:r,hooks:[]},t[o].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,Ro)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){if(!this.mapEventName(n.event))continue;let i=`.gemini/hooks/${Pn(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
|
|
103
111
|
# Constellation ${e.event} Hook for Gemini CLI
|
|
104
112
|
# Generated by constellation-cli - DO NOT EDIT
|
|
105
113
|
#
|
|
@@ -122,38 +130,64 @@ cat << 'CONSTELLATION_EOF'
|
|
|
122
130
|
}
|
|
123
131
|
}
|
|
124
132
|
CONSTELLATION_EOF
|
|
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
|
|
133
|
+
`}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 Ao=new Map([["cline",new me],["cursor",new X],["gemini",new he]]);function _t(s){return Ao.get(s)}var ye=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=_t(e.hooksConfig.adapterId);if(!n)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let o=___default.join(this.cwd,e.hooksConfig.filePath),r=n.generateConfig(t),i=Object.keys(r).some(l=>{let g=r[l];return g!=null&&(typeof g!="object"||Object.keys(g).length>0)});if(i){await this.ensureDirectoryExists(o);let l=await this.readConfig(o),g=this.mergeHooksConfig(l,r);await this.writeConfig(o,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?o:void 0,auxiliaryPaths:a}}catch(o){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:o instanceof Error?o.message:String(o)}}}async ensureDirectoryExists(e){let t=___default.dirname(e);await k__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await m.fileIsReadable(e))return {};let n=await m.readFile(e);return JSON.parse(n)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let n=e.hooks??{},o=t.hooks??{},r={...n,...o},i={...e,hooks:r};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,`
|
|
126
134
|
`),n.endsWith(`
|
|
127
135
|
`)||(n+=`
|
|
128
|
-
`),await
|
|
129
|
-
`);
|
|
130
|
-
`)||(o+=`
|
|
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,`
|
|
133
|
-
`),r.endsWith(`
|
|
136
|
+
`),await m.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let o=___default.join(this.cwd,t);await this.ensureDirectoryExists(o);let r=n.replace(/\r\n/g,`
|
|
137
|
+
`);r.endsWith(`
|
|
134
138
|
`)||(r+=`
|
|
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
|
-
|
|
137
|
-
`)
|
|
138
|
-
`)
|
|
139
|
-
|
|
140
|
-
`);}
|
|
141
|
-
`);}if(!await this.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
${
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
139
|
+
`),await m.writeFile(o,r),(t.endsWith(".sh")||r.startsWith("#!"))&&await k__default.chmod(o,493);}}};var G=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};var Z=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(`${C} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,o),o}if(n){if(this.isJavaScriptEnabled)try{let o=await parse(e,{root:this.projectRoot,configName:"jsconfig.json"});return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}throw o}if(this.isTypeScriptEnabled){let o=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return console.warn(`${C} 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();}};q();q();var Be=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),r=await this.resolveSubPath(n,o);if(r)return this.toProjectRelative(r)}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[o,r]of Object.entries(t)){if(o.includes("*")||!Array.isArray(r))continue;let i=r[0];if(!i)continue;let a=_.resolve(n,i),l=await this.findEntryPoint(a);l&&(e[o]=l);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=_.join(this.projectRoot,"package.json"),n=await k.readFile(t,"utf-8"),r=JSON.parse(n).workspaces;if(!r)return e;let i=Array.isArray(r)?r:r.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),o=_.join(this.projectRoot,n);try{let r=await k.readdir(o,{withFileTypes:!0});for(let i of r)i.isDirectory()&&t.push(_.join(o,i.name));}catch{}}else {let n=_.join(this.projectRoot,e);try{(await k.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=_.join(e,"package.json"),n=await k.readFile(t,"utf-8"),o=JSON.parse(n),r=o.name;if(!r)return null;let i=await this.findPackageEntryPoint(e,o);return i?{[r]:i}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return _.join(e,o);if(typeof o=="object"){let r=o["."]||o["./index"];if(typeof r=="string")return _.join(e,r);if(typeof r=="object"){let i=r.import||r.default||r.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 o of n){let r=_.join(e,o);try{if((await k.stat(r)).isFile())return r}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let o=_.join(e,n);try{if((await k.stat(o)).isFile())return o}catch{}}try{if((await k.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),o=[_.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 r of o)try{if((await k.stat(r)).isFile())return r}catch{}return null}toProjectRelative(e){let t=H(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};var Q=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 Be(this.projectRoot,t);let n=e.toLowerCase(),o=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),r=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:r?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),o=await this.findFileWithExtensions(n);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=H(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let r of n){let i=await this.trySubstitution(e,t,r,o);if(i)return i}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,o]=t.split("*");if(!e.startsWith(n)||o&&!e.endsWith(o))return null;let r=n.length,i=o?e.length-o.length:e.length;return e.substring(r,i)}async trySubstitution(e,t,n,o){let r=n.replaceAll("*",o),i=_.resolve(this.tsconfigDir,r);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"],o=n.some(i=>e.endsWith(i)),r=e;if(o&&!t){for(let i of n)if(e.endsWith(i)){r=e.slice(0,-i.length);break}}if(!t)for(let i of this.extensions){let a=r+i;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let i of this.extensions){let a=_.join(r,`index${i}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await k.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await k.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 k.stat(n)).isFile())return n}catch{}let o=_.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await k.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 o=this.matchPathPattern(e,t);if(o!==null){if(typeof n=="string"){let r=await this.tryPackageImportSubstitution(n,o);if(r)return r}if(Array.isArray(n)){for(let r of n)if(typeof r=="string"){let i=await this.tryPackageImportSubstitution(r,o);if(i)return i}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),o=_.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(o)}};var He=class extends G{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new Z(e,t)}getImportResolver(e,t){return new Q(e,t)}};var Ue=class extends G{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new Z(e,t)}getImportResolver(e,t){return new Q(e,t)}};Fe();var Ge=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,"/"),o=await this.tryResolveFile(_.resolve(this.projectRoot,n));return o?_.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),o=t<=1?"":"../".repeat(t-1),r=n?o+n.replace(/\./g,"/"):o.slice(0,-1)||".",i=_.resolve(this.sourceDir,r),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 We.promises.access(n,We.constants.F_OK),n}catch{continue}return null}};var ze=class extends G{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new Ge(e,process.cwd())}};var Ce={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"]},Ke=class{constructor(e){this.config=e;this.registerPlugin(new He),this.registerPlugin(new Ue),this.registerPlugin(new ze);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>jo,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Ce.javascript};typescript={language:()=>Oo.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Ce.typescript};python={language:()=>Lo,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Ce.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};var Fo={stable:"Code",insiders:"Code - Insiders"};function En(s,e){let t=oe__default.homedir(),n=process.platform,o=Fo[s];switch(n){case "darwin":return ___default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return ___default.join(process.env.APPDATA||___default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return ___default.join(t,".config",o,"User/globalStorage",e)}}function In(){let s="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:___default.join(En(t,s),"settings","cline_mcp_settings.json")}))}function $n(){return ___default.join(En("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}function Pt(){let s=oe__default.homedir();return ___default.join(s,".copilot","mcp-config.json")}function kn(){return [{displayName:"Copilot CLI",settingsPath:Pt()}]}var Tn={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Do={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},xt=[{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:Do},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:$n(),isGlobalConfig:true,getGlobalConfigPaths:In,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:Pt(),isGlobalConfig:true,getGlobalConfigPaths:kn,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 bt(s){return xt.find(e=>e.id===s)}var St=null;async function Nn(){if(!St)try{let s=await import('@iarna/toml');St={parse:s.parse,stringify:s.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return St}function Ho(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]!==`
|
|
140
|
+
`;)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 Ve=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 r=await this.readConfig(t,e.format);if(e.configDefaults)for(let[i,a]of Object.entries(e.configDefaults))i in r||(r[i]=a);e.pluginConfig&&(r=this.addPluginToArray(r,e.pluginConfig)),e.skipMcpServer||(r=this.addConstellationServer(r,e),await this.configureEnvPolicy(r,e)),await this.writeConfig(t,r,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let o;return n?o=t:e.permissionsConfig?o=___default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=___default.join(this.cwd,e.marketplaceConfig.filePath):o=t,{tool:e,success:!0,configuredPath:o}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),n=[];for(let{displayName:o,settingsPath:r}of t)try{await this.ensureDirectoryExists(r);let i=await this.readConfig(r,e.format);i=this.addConstellationServer(i,e),await this.writeConfig(r,i,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:r});}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} (${o})`},success:false,error:a});}return n}async ensureDirectoryExists(e){let t=___default.dirname(e);await k__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await m.fileIsReadable(e))return {};let o=await m.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(Ho(o)):(await Nn()).parse(o)}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 o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[o]||typeof n[o]!="object")&&(n[o]={});let r=n[o];if(!r.constellation){let i=t.mcpServerConfigOverride??Tn,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};}r.constellation=a;}return e}async writeConfig(e,t,n){let o;n==="json"||n==="jsonc"?o=JSON.stringify(t,null,2):o=(await Nn()).stringify(t),o=o.replace(/\r\n/g,`
|
|
141
|
+
`),o.endsWith(`
|
|
142
|
+
`)||(o+=`
|
|
143
|
+
`),await m.writeFile(e,o);}async configurePermissions(e){let t=___default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await m.fileIsReadable(t)){let l=await m.readFile(t);n=JSON.parse(l);}}catch{}let o=n;for(let a=0;a<e.allowKeyPath.length-1;a++){let l=e.allowKeyPath[a];(!o[l]||typeof o[l]!="object")&&(o[l]={}),o=o[l];}let r=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(o[r])||(o[r]=[]);let i=o[r];i.includes(e.allowValue)||i.push(e.allowValue),await m.writeFile(t,JSON.stringify(n,null," ")+`
|
|
144
|
+
`);}async configureMarketplace(e){let t=___default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await m.fileIsReadable(t)){let r=await m.readFile(t);n=JSON.parse(r);}}catch{}n=this.deepMerge(n,e.config),await m.writeFile(t,JSON.stringify(n,null," ")+`
|
|
145
|
+
`);}deepMerge(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=e[o];r&&typeof r=="object"&&!Array.isArray(r)&&i&&typeof i=="object"&&!Array.isArray(i)?n[o]=this.deepMerge(i,r):n[o]=r;}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 o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let r=n[o];return r.includes(t.pluginValue)||r.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:o,globalConfigPath:r}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,o),r&&await this.updateGlobalEnvPolicy(r,n,o,t.format);}addToEnvPolicyWhitelist(e,t,n){let o=e;for(let a=0;a<t.length-1;a++){let l=t[a];if(!o[l]||typeof o[l]!="object")return;o=o[l];}let r=t[t.length-1];if(!Array.isArray(o[r]))return;let i=o[r];for(let a of n)i.includes(a)||i.push(a);}async updateGlobalEnvPolicy(e,t,n,o){let r=e.replace(/^~/,oe__default.homedir()),i=await this.readConfig(r,o);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(r,i,o);}};function Et(s){return `name: Constellation Index
|
|
146
|
+
|
|
147
|
+
on:
|
|
148
|
+
push:
|
|
149
|
+
branches: ["${s}"]
|
|
150
|
+
|
|
151
|
+
permissions:
|
|
152
|
+
contents: read
|
|
153
|
+
|
|
154
|
+
jobs:
|
|
155
|
+
index:
|
|
156
|
+
runs-on: ubuntu-latest
|
|
157
|
+
steps:
|
|
158
|
+
- uses: actions/checkout@v4
|
|
159
|
+
|
|
160
|
+
- uses: ShiftinBits/constellation-github@v1
|
|
161
|
+
with:
|
|
162
|
+
access-key: \${{ secrets.CONSTELLATION_ACCESS_KEY }}
|
|
163
|
+
`}function It(s){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${s}"`}]}}}function Je(s){return `include:
|
|
164
|
+
- component: gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1
|
|
165
|
+
inputs:
|
|
166
|
+
access_key: $CONSTELLATION_ACCESS_KEY
|
|
167
|
+
|
|
168
|
+
constellation-index:
|
|
169
|
+
rules:
|
|
170
|
+
- if: $CI_COMMIT_BRANCH == "${s}"
|
|
171
|
+
`}var we=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([m.directoryExists(___default.join(this.gitRoot,".github","workflows")),m.fileIsReadable(___default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return m.fileIsReadable(___default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=___default.join(this.gitRoot,".gitlab-ci.yml");if(!await m.fileIsReadable(e))return false;try{let n=await m.readFile(e),r=parseDocument(n).contents;return isMap(r)&&r.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=___default.join(this.gitRoot,".github","workflows");await k__default.mkdir(t,{recursive:true});let n=___default.join(t,"constellation-index.yml");return await m.writeFile(n,Et(e)),n}async createOrMergeGitLabCI(e){let t=___default.join(this.gitRoot,".gitlab-ci.yml");if(!await m.fileIsReadable(t))return await m.writeFile(t,Je(e)),t;let o=await m.readFile(t),r=parseDocument(o);if(!isMap(r.contents))return await m.writeFile(t,Je(e)),t;let{includeEntry:i,job:a}=It(e);return this.mergeIncludeEntry(r,i),r.set("constellation-index",a),await m.writeFile(t,r.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let o=n.items.filter(r=>{if(isMap(r)){let i=r.get("component");return typeof i!="string"||!i.includes("constellation-gitlab")}return true});n.items=o,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};var{prompt:te}=An;function ne(s,e){let t=___default.normalize(s),n=___default.normalize(e);return t.startsWith(n+___default.sep)?___default.relative(e,s):s}var _e=class extends B{async run(e={}){try{if(console.log(`${F}Initializing project configuration...
|
|
172
|
+
`),!await this.git.isGitAvailable())throw new Error(`${C} Could not find git client installation.
|
|
173
|
+
${h} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=___default.join(process.cwd(),"constellation.json"),o=null,r=await m.fileIsReadable(n);if(r)try{let b=await m.readFile(n);o=JSON.parse(b),console.log(`${h} Found existing constellation.json, current values will be used as defaults.
|
|
174
|
+
`);}catch{console.log(`${C} Existing constellation.json is invalid, starting fresh.
|
|
175
|
+
`);}if(!await this.git.isGitRepository())throw new Error(`${C} Current directory is not a git repository.
|
|
176
|
+
${h} 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(b=>b!==d),u=d?[d,...p]:p,f=this.getBranchInitialIndex(u,o?.branch),P=this.getInitialLanguages(o),w=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:o?.projectId??"",validate:b=>b.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(o),initial:P,result(b){return b.map(L=>this.choices.find(nt=>nt.name===L)?.value??L)}}],x=await new An().prompt(w),Ie={projectId:x.projectId.trim(),branch:x.branch,languages:{...x.languages.reduce((b,L)=>(b[L]={fileExtensions:Ce[L]||[]},b),{})}},se=JSON.stringify(Ie,void 0,2);await m.writeFile(n,se),console.log(`${y} ${r?"Updated":"Initialized"} configuration file at ${ne(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${y} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&a&&await this.configureCICD(x.branch,a);}catch(t){let n=t.message??"An unexpected error occurred";console.error(`${v} Failed to initialize configuration file.
|
|
177
|
+
${n}`);}}async configureMCPServers(){let{configureMcp:e}=await te({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=xt.map(p=>({name:p.displayName,value:p.id})),{selectedTools:n}=await te({type:"multiselect",name:"selectedTools",message:"Select AI coding assistants to configure:",choices:t,result(p){return p.map(u=>this.choices.find(P=>P.name===u)?.value??u)}});if(n.length===0){console.log(`${h} No tools selected, skipping MCP configuration`);return}let o=new Ve(process.cwd()),r=[];for(let p of n){let u=bt(p);if(u)if(console.log(` ${h} Configuring ${u.displayName}...`),u.isGlobalConfig&&u.getGlobalConfigPaths){let f=await o.configureGlobalTool(u),P=false;for(let w of f)r.push(w),w.success?(P=true,console.log(` ${y} ${w.tool.displayName} configured at ${ne(w.configuredPath,process.cwd())}`)):w.error&&console.log(` ${C} ${w.tool.displayName}: ${w.error}`);if(P){let w=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${h} Note: ${u.displayName} uses ${w} (not project-level)`);}if(f.length===0){let w=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${C} ${u.displayName}: ${w}`);}}else {let f=await o.configureTool(u);r.push(f),f.success?(console.log(` ${y} ${u.displayName} configured at ${ne(f.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${y} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${C} ${u.displayName}: ${f.error}`);}}if(r.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(` ${y} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${C} Could not stage .claude/settings.json in git`);}}if(r.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(` ${y} Added .codex/config.toml to staged changes in git`);}catch{}}if(r.find(p=>p.tool.id==="opencode"&&p.success)){let p=___default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),console.log(` ${y} Added opencode.jsonc to staged changes in git`);}catch{}}let g=r.filter(p=>p.success).length,d=r.filter(p=>!p.success).length;console.log(`
|
|
178
|
+
${y} MCP configuration complete: ${g} configured`),d>0&&console.log(`${C} ${d} tool(s) could not be configured`),await this.configureHooks(n,r),console.log(`
|
|
179
|
+
${h} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new ye(process.cwd()),o=wt(),r=e.map(l=>bt(l)).filter(l=>l!==void 0&&l.hooksConfig!==void 0&&t.some(g=>g.tool.id===l.id&&g.success));if(r.length===0)return;console.log(`
|
|
180
|
+
${h} Configuring AI hooks...`);let i=[];for(let l of r){let g=await n.configureHooks(l,o);if(i.push(g),g.success){let d=g.configuredPath?[g.configuredPath]:g.auxiliaryPaths??[];if(d.length>0){let p=g.configuredPath?ne(g.configuredPath,process.cwd()):___default.dirname(d[0]);console.log(` ${y} ${l.displayName} hooks configured at ${p}`);for(let u of d){let f=___default.isAbsolute(u)?ne(u,process.cwd()):u;try{await this.git.stageFile(u),console.log(` ${y} Added ${f} to staged changes in git`);}catch{console.log(` ${C} Could not stage ${f} in git`);}}}else console.log(` ${y} ${l.displayName} hooks configured`);}else console.log(` ${C} ${l.displayName}: ${g.error}`);}let a=i.filter(l=>l.success).length;a>0&&console.log(`${y} Hooks configuration complete: ${a} configured`);}async configureCICD(e,t){let{setupCicd:n}=await te({type:"confirm",name:"setupCicd",message:"Set up a CI/CD pipeline to automatically index your project?",initial:true});if(!n)return;let o=new we(t),r=await o.detectPlatforms(),i;if(r.length===1){let d=r[0]==="github"?"GitHub Actions":"GitLab CI",{useDetected:p}=await te({type:"confirm",name:"useDetected",message:`Detected ${d}. Configure Constellation CI/CD for this platform?`,initial:true});if(!p)return;i=r[0];}else {let d=[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],{platform:p}=await te({type:"select",name:"platform",message:"Select CI/CD platform:",choices:d,result(u){let f=Array.isArray(u)?u[0]:u;return this.choices.find(w=>w.name===f)?.value??f}});i=p;}let a=i==="github"?await o.githubWorkflowExists():await o.gitlabJobExists();if(a){let{overwrite:d}=await te({type:"confirm",name:"overwrite",message:"Constellation CI/CD configuration already exists. Overwrite?",initial:false});if(!d){console.log(`${h} Skipping CI/CD configuration`);return}}let l;try{l=i==="github"?await o.createGitHubWorkflow(e):await o.createOrMergeGitLabCI(e);}catch(d){console.log(`${C} Failed to configure CI/CD pipeline: ${d.message}`);return}let g=ne(l,process.cwd());console.log(i==="github"?`${y} Created ${g}`:`${y} ${a?"Updated":"Created"} ${g} with Constellation indexing`);try{await this.git.stageFile(l),console.log(`${y} Added ${g} to staged changes in git`);}catch{console.log(`${C} Could not stage ${g} in git`);}i==="github"?(console.log(`${h} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${h} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){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 Ye=class s{constructor(e,t,n,o){this.branch=e;this.languages=t;this.projectId=n;this.exclude=o;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await m.fileIsReadable(e)){let n=await m.readFile(e),o=JSON.parse(n),r=new s(o.branch,o.languages,o.projectId,o.exclude);return r.validate(),r}else throw new Error(`${v} 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 qe=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(`
|
|
181
|
+
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Tt=class extends qe{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.
|
|
182
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,o)=>{let r=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),i="";r.stderr?.on("data",a=>{i+=a.toString();}),r.on("close",a=>{a===0?n():o(new Error(`setx failed with code ${a}: ${i}`));}),r.on("error",a=>{o(a);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let o=(await new Promise((r,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?r(l):i(new Error(`reg query failed: ${g}`));}),a.on("error",d=>{i(d);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},Nt=class extends qe{userConfigFiles;constructor(){super(),this.userConfigFiles=[_.join(oe.homedir(),".zshenv"),_.join(oe.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.
|
|
183
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),o=`export ${e}="${n}"`;try{for(let r of this.userConfigFiles)await this.writeToConfigFile(r,e,o);process.env[e]=t;}catch(r){throw new Error(`Failed to set environment variable ${e}: ${r}`)}}async writeToConfigFile(e,t,n){let o="";try{o=await m.readFile(e,"utf-8");}catch{}let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^export ${r}=.*$`,"gm");i.test(o)?o=o.replace(i,n):o=o.trimEnd()+`
|
|
150
184
|
`+n+`
|
|
151
|
-
`,await
|
|
152
|
-
${
|
|
153
|
-
`),await this.packageManager.executeUpdate(
|
|
154
|
-
${
|
|
185
|
+
`,await m.writeFile(e,o);}},Rt=class{static create(){let e=oe.platform();switch(e){case "win32":return new Tt;case "darwin":case "linux":return new Nt;default:throw new Error(`Unsupported platform: ${e}`)}}},Xe=class{manager;constructor(){this.manager=Rt.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 Ze=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let o of n.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=___default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};function zo(){let s=oe.platform();if(s==="darwin")return _.join(oe.homedir(),"Library","Caches","constellation");if(s==="win32"){let e=process.env.LOCALAPPDATA||_.join(oe.homedir(),"AppData","Local");return _.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||_.join(oe.homedir(),".cache");return _.join(e,"constellation")}}var Ko=zo(),Vo="update-state.json",Jo=1440*60*1e3,Pe=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??Ko,this.stateFile=_.join(this.stateDir,Vo);}async load(){if(this.state)return this.state;try{let e=await k.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await k.mkdir(this.stateDir,{recursive:!0}),await k.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>Jo}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 k.unlink(this.stateFile),this.state=null;}catch{}}};var xe=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...n]=this.getUpdateCommand(e);return new Promise(o=>{let r=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});r.on("close",i=>{o(i===0);}),r.on("error",()=>{o(false);});})}};var{prompt:Xo}=An,be=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:o}=await Xo({type:"confirm",name:"shouldUpdate",message:"Would you like to update now?",initial:!0});return o}catch{return false}}};var Zo="https://registry.npmjs.org",Qe="@constellationdev/cli",Qo=5e3,et=class{cache;packageManager;prompter;constructor(){this.cache=new Pe,this.packageManager=new xe,this.prompter=new be;}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(),Qo);try{let o=await fetch(`${Zo}/${Qe}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let i=(await o.json()).version;return {current:e,latest:i,hasUpdate:this.isNewerVersion(i,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=i=>i.split("-")[0],o=n(e).split(".").map(Number),r=n(t).split(".").map(Number);for(let i=0;i<3;i++){let a=o[i]||0,l=r[i]||0;if(a>l)return true;if(a<l)return false}return false}async performUpdate(){return console.log(`
|
|
186
|
+
${h} Updating ${Qe}...
|
|
187
|
+
`),await this.packageManager.executeUpdate(Qe)?(console.log(`
|
|
188
|
+
${y} Update complete! Please re-run your command.
|
|
155
189
|
`),true):(console.log(`
|
|
156
|
-
${
|
|
157
|
-
`),false)}};async function
|
|
158
|
-
Modified: ${
|
|
159
|
-
${s?.message??String(s)}`),process.exit(1);});var
|
|
190
|
+
${C} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Qe)}
|
|
191
|
+
`),false)}};async function At(s){return new et().check(s)}var er=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];function tr(){return er.some(s=>!!process.env[s])}function nr(){return !!process.stdout.isTTY}function Ln(){return !tr()&&nr()}var Se=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:[]},o=t.split(/\r?\n/).map(r=>r.trim()).filter(Boolean);for(let r of o){let i=r.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 o={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw console.error("\u274C Cannot pull: Working directory has uncommitted changes"),console.error(" Details:",JSON.stringify(o,null,2)),e.conflicted.length>0&&console.error(" \u26A0\uFE0F Conflicted files:",e.conflicted.join(", ")),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
|
|
192
|
+
Modified: ${o.modified}, Created: ${o.created}, Deleted: ${o.deleted}, Conflicted: ${o.conflicted}, Staged: ${o.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let o=await this.git.status();if(o.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",o.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${o.conflicted.length} file(s): ${o.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let 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(`${v} An unexpected error occurred during the index attempt:
|
|
193
|
+
${s?.message??String(s)}`),process.exit(1);});var ar=___default.dirname(fileURLToPath(import.meta.url)),cr=___default.join(ar,"..","package.json"),lr=JSON.parse(readFileSync(cr,"utf-8")),On=lr.version,pr=["help","--help","-h","--version","-V","-v"];if(Ln()){let s=process.argv[2];["auth","help","init","index"].includes(s)?rt(s):rt(),pr.includes(s)||await At(On)&&process.exit(0);}var jt=process.cwd(),Lt=new Xe,Ee=new Command;Ee.name("constellation").description("Connecting stars in your code into intelligent patterns").version(On);Ee.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async s=>{try{let t={GitClient:new Se(jt)};await new _e(t).run({skipMcp:s.skipMcp,skipCi:s.skipCi});}catch(e){console.error(`${v} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Ee.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async s=>{try{let e={Environment:Lt};await new le(e).run(s.manual);}catch(e){console.error(`${v} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Ee.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 Ye.loadFromFile(___default.join(jt,"constellation.json")),t=new Se(jt),n=new Ke(e),o=new Ze(e),r={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:o,Environment:Lt},i=Lt.isCI(),a=s.full||!s.incremental&&i,l=s.dirty||!1;!s.full&&!s.incremental&&i&&console.log(`${h} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new fe(r).run(a,l);}catch(e){!(e instanceof S)&&!(e instanceof $)&&console.error(`${v} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Ee.parse();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@constellationdev/cli",
|
|
3
3
|
"description": "Code Intelligence Platform for AI Coding Agents",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.2.0",
|
|
5
5
|
"author": "ShiftinBits Inc",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"type": "module",
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"tree-sitter-typescript": "^0.21.2",
|
|
39
39
|
"tsconfck": "^3.1.6",
|
|
40
40
|
"undici": "^7.22.0",
|
|
41
|
+
"yaml": "^2.8.3",
|
|
41
42
|
"zod": "^3.23.8"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|