@r5n/atlas 0.6.5 → 0.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +29 -29
- package/package.json +2 -3
package/dist/cli.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),u=!1;for(let h=0;h<c.length;h++){let f=c[h];if(s+=f,!u){if(u=f>="\uD800"&&f<="\uDBFF",u)continue}else u=!1;if(f===lt||f===Oe){Ie.lastIndex=h+1;let d=Ie.exec(c)?.groups;if(d?.code!==void 0){let b=Number.parseFloat(d.code);i=b===
|
|
3
|
+
var Nn=Object.create;var{getPrototypeOf:Mn,defineProperty:$e,getOwnPropertyNames:Ln}=Object;var ye=Object.prototype.hasOwnProperty;function jn(t){return this[t]}var Vn,Un,be=(t,e,n)=>{var s=t!=null&&typeof t==="object";if(s){var i=e?Vn??=new WeakMap:Un??=new WeakMap,r=i.get(t);if(r)return r}n=t!=null?Nn(Mn(t)):{};let o=e||!t||!t.__esModule||!ye.call(t,"default")?$e(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Ln(t))if(!ye.call(o,a))$e(o,a,{get:jn.bind(t,a),enumerable:!0})}if(s)i.set(t,o);return o};var Gn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Vt=Gn(function(pr,De){var jt={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ns={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},ss={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?jt.up():"");if(t)e+=jt.left;return e}};De.exports={cursor:jt,scroll:ns,erase:ss,beep:"\x07"}});import{join as sr}from"path";class W extends Error{constructor(t="Operation cancelled"){super(t)}}class g extends Error{hint;exitCode;constructor(t,e,n=1){super(t);this.hint=e;this.exitCode=n}}import{stdout as Fe,stdin as is}from"process";import rs from"readline";var ve=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),we=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,xe=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var Hn=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Bn=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ce=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Wn=/\t{1,1000}/y,Se=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Jn=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Kn=/\p{M}+/gu,qn={limit:1/0,ellipsis:""},Ae=(t,e={},n={})=>{let s=e.limit??1/0,i=e.ellipsis??"",r=e?.ellipsisWidth??(i?Ae(i,qn,n).width:0),o=0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.emojiWidth??2,u=2,h=n.regularWidth??1,f=n.wideWidth??2,m=[[Jn,h],[Hn,0],[Bn,a],[Wn,l],[Se,c],[Ce,f]],d=0,b=0,E=t.length,_=0,x=!1,P=E,R=Math.max(0,s-r),C=0,O=0,T=0,p=0;t:while(!0){if(O>C||b>=E&&b>d){let S=t.slice(C,O)||t.slice(d,b);_=0;for(let D of S.replaceAll(Kn,"")){let F=D.codePointAt(0)||0;if(we(F))p=2;else if(xe(F))p=f;else p=h;if(T+p>R)P=Math.min(P,Math.max(C,d)+_);if(T+p>s){x=!0;break t}_+=D.length,T+=p}C=O=0}if(b>=E)break t;for(let S=0,D=m.length;S<D;S++){let[F,ge]=m[S];if(F.lastIndex=b,F.test(t)){if(_=F===Ce?ve(t.slice(b,F.lastIndex)):F===Se?1:F.lastIndex-b,p=_*ge,T+p>R)P=Math.min(P,b+Math.floor((R-T)/ge));if(T+p>s){x=!0;break t}T+=p,C=d,O=b,b=d=F.lastIndex;continue t}}b+=1}return{width:x?R:T,index:x?P:E,truncated:x,ellipsed:x&&s>=r}},Ee=Ae;var Xn={limit:1/0,ellipsis:"",ellipsisWidth:0},zn=(t,e={})=>Ee(t,Xn,e).width,U=zn;var lt="\x1B",Oe="\x9B",Yn=39,Mt="\x07",Pe="[",Qn="]",ke="m",Lt=`${Qn}8;;`,Ie=new RegExp(`(?:\\${Pe}(?<code>\\d+)m|\\${Lt}(?<uri>.*)${Mt})`,"y"),_e=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},Te=(t)=>`${lt}${Pe}${t}${ke}`,Re=(t)=>`${lt}${Lt}${t}${Mt}`,Nt=(t,e,n)=>{let s=e[Symbol.iterator](),i=!1,r=!1,o=t.at(-1),a=o===void 0?0:U(o),l=s.next(),c=s.next(),u=0;while(!l.done){let h=l.value,f=U(h);if(a+f<=n)t[t.length-1]+=h;else t.push(h),a=0;if(h===lt||h===Oe)i=!0,r=e.startsWith(Lt,u+1);if(i){if(r){if(h===Mt)i=!1,r=!1}else if(h===ke)i=!1}else if(a+=f,a===n&&!c.done)t.push(""),a=0;l=c,c=s.next(),u+=h.length}if(o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1)t[t.length-2]+=t.pop()},Zn=(t)=>{let e=t.split(" "),n=e.length;while(n){if(U(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},ts=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let s="",i,r,o=t.split(" "),a=[""],l=0;for(let h=0;h<o.length;h++){let f=o[h];if(n.trim!==!1){let d=a.at(-1)??"",b=d.trimStart();if(d.length!==b.length)a[a.length-1]=b,l=U(b)}if(h!==0){if(l>=e&&(n.wordWrap===!1||n.trim===!1))a.push(""),l=0;if(l||n.trim===!1)a[a.length-1]+=" ",l++}let m=U(f);if(n.hard&&m>e){let d=e-l,b=1+Math.floor((m-d-1)/e);if(Math.floor((m-1)/e)<b)a.push("");Nt(a,f,e),l=U(a.at(-1)??"");continue}if(l+m>e&&l&&m){if(n.wordWrap===!1&&l<e){Nt(a,f,e),l=U(a.at(-1)??"");continue}a.push(""),l=0}if(l+m>e&&n.wordWrap===!1){Nt(a,f,e),l=U(a.at(-1)??"");continue}a[a.length-1]+=f,l+=m}if(n.trim!==!1)a=a.map((h)=>Zn(h));let c=a.join(`
|
|
4
|
+
`),u=!1;for(let h=0;h<c.length;h++){let f=c[h];if(s+=f,!u){if(u=f>="\uD800"&&f<="\uDBFF",u)continue}else u=!1;if(f===lt||f===Oe){Ie.lastIndex=h+1;let d=Ie.exec(c)?.groups;if(d?.code!==void 0){let b=Number.parseFloat(d.code);i=b===Yn?void 0:b}else if(d?.uri!==void 0)r=d.uri.length===0?void 0:d.uri}if(c[h+1]===`
|
|
5
5
|
`){if(r)s+=Re("");let m=i?_e(i):void 0;if(i&&m)s+=Te(m)}else if(f===`
|
|
6
|
-
`){if(i&&_e(i))s+=Te(i);if(r)s+=Re(r)}}return s},
|
|
7
|
-
`)}var
|
|
6
|
+
`){if(i&&_e(i))s+=Te(i);if(r)s+=Re(r)}}return s},es=/\r?\n/;function Q(t,e,n){return String(t).normalize().split(es).map((s)=>ts(s,e,n)).join(`
|
|
7
|
+
`)}var M=be(Vt(),1);function dt(t,e,n){if(!n.some((o)=>!o.disabled))return t;let s=t+e,i=Math.max(n.length-1,0),r=s<0?i:s>i?0:s;return n[r]?.disabled?dt(r,e<0?-1:1,n):r}var os=["up","down","left","right","space","enter","cancel"],as=["January","February","March","April","May","June","July","August","September","October","November","December"],G={actions:new Set(os),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...as],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Ne(t,e){if(typeof t=="string")return G.aliases.get(t)===e;for(let n of t)if(n!==void 0&&Ne(n,e))return!0;return!1}function cs(t,e){if(t===e)return;let n=t.split(`
|
|
8
8
|
`),s=e.split(`
|
|
9
|
-
`),i=Math.max(n.length,s.length),r=[];for(let o=0;o<i;o++)n[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:n.length,numLinesAfter:s.length,numLines:i}}var
|
|
9
|
+
`),i=Math.max(n.length,s.length),r=[];for(let o=0;o<i;o++)n[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:n.length,numLinesAfter:s.length,numLines:i}}var br=globalThis.process.platform.startsWith("win"),Ut=Symbol("clack:cancel");function ht(t){return t===Ut}function ut(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var Gt=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,Ht=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function ft(t,e,n,s=n,i=n,r){let o=Gt(t??Fe);return Q(e,o-n.length,{hard:!0,trim:!1}).split(`
|
|
10
10
|
`).map((a,l,c)=>{let u=r?r(a,l):a;return l===0?`${s}${u}`:l===c.length-1?`${i}${u}`:`${n}${u}`}).join(`
|
|
11
|
-
`)}function
|
|
11
|
+
`)}function Me(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}class Le{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:n=is,output:s=Fe,render:i,signal:r,...o}=t;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=e,this._abortSignal=r,this.input=n,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let n=this._subscribers.get(t)??[];n.push(e),this._subscribers.set(t,n)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let n=this._subscribers.get(t)??[],s=[];for(let i of n)i.cb(...e),i.once&&s.push(()=>n.splice(n.indexOf(i),1));for(let i of s)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Ut);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=rs.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),ut(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(M.cursor.show),this.output.off("resize",this.render),ut(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(M.cursor.show),this.output.off("resize",this.render),ut(this.input,!1),t(Ut)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),e?.name&&(!this._track&&G.aliases.has(e.name)&&this.emit("cursor",G.aliases.get(e.name)),G.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let n=Me(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ne([t,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
12
12
|
`),ut(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Q(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
|
-
`).length-1;this.output.write(
|
|
14
|
-
`);this.output.write(o[r]),this._prevFrame=t,this.output.write(
|
|
13
|
+
`).length-1;this.output.write(M.cursor.move(-999,t*-1))}render(){let t=Q(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(M.cursor.hide);else{let e=cs(this._prevFrame,t),n=Ht(this.output);if(this.restoreCursor(),e){let s=Math.max(0,e.numLinesAfter-n),i=Math.max(0,e.numLinesBefore-n),r=e.lines.find((o)=>o>=s);if(r===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(M.cursor.move(0,r-i)),this.output.write(M.erase.lines(1));let o=t.split(`
|
|
14
|
+
`);this.output.write(o[r]),this._prevFrame=t,this.output.write(M.cursor.move(0,o.length-r-1));return}else if(e.lines.length>1){if(s<i)r=s;else{let a=r-i;a>0&&this.output.write(M.cursor.move(0,a))}this.output.write(M.erase.down());let o=t.split(`
|
|
15
15
|
`).slice(r);this.output.write(o.join(`
|
|
16
|
-
`)),this._prevFrame=t;return}}this.output.write(
|
|
17
|
-
`);E.push(p),_+=p.length}if(_>u){let C=0,O=0,T=_,p=t-x,S=u,D=()=>Ue(E,T,0,p,S),F=()=>Ue(E,T,p+1,E.length,S,!0);m?({lineCount:T,removals:C}=D(),T>S&&(d||(S-=1),{lineCount:T,removals:O}=F())):(d||(S-=1),{lineCount:T,removals:O}=F(),T>S&&(S-=1,{lineCount:T,removals:C}=D())),C>0&&(m=!0,E.splice(0,C)),O>0&&(d=!0,E.splice(E.length-O,O))}let R=[];m&&R.push(c);for(let C of E)for(let O of C)R.push(O);return d&&R.push(c),R};var
|
|
16
|
+
`)),this._prevFrame=t;return}}this.output.write(M.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}var je=class extends Le{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:i})=>i===e.initialValue),s=n===-1?0:n;this.cursor=this.options[s]?.disabled?dt(s,1,this.options):s,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=dt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=dt(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as y,stripVTControlCharacters as Dr}from"util";import j from"process";var Ge=be(Vt(),1);function ls(){if(j.platform!=="win32")return j.env.TERM!=="linux";return Boolean(j.env.CI)||Boolean(j.env.WT_SESSION)||Boolean(j.env.TERMINUS_SUBLIME)||j.env.ConEmuTask==="{cmd::Cmder}"||j.env.TERM_PROGRAM==="Terminus-Sublime"||j.env.TERM_PROGRAM==="vscode"||j.env.TERM==="xterm-256color"||j.env.TERM==="alacritty"||j.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var us=ls();var I=(t,e)=>us?t:e,ds=I("\u25C6","*"),hs=I("\u25A0","x"),fs=I("\u25B2","x"),He=I("\u25C7","o"),ms=I("\u250C","T"),k=I("\u2502","|"),Bt=I("\u2514","\u2014"),Lr=I("\u2510","T"),jr=I("\u2518","\u2014"),ps=I("\u25CF",">"),Ve=I("\u25CB"," "),Vr=I("\u25FB","[\u2022]"),Ur=I("\u25FC","[+]"),Gr=I("\u25FB","[ ]"),Hr=I("\u25AA","\u2022"),Br=I("\u2500","-"),Wr=I("\u256E","+"),Jr=I("\u251C","+"),Kr=I("\u256F","+"),qr=I("\u2570","+"),Xr=I("\u256D","+"),gs=I("\u25CF","\u2022"),$s=I("\u25C6","*"),ys=I("\u25B2","!"),bs=I("\u25A0","x"),vs=(t)=>{switch(t){case"initial":case"active":return y("cyan",ds);case"cancel":return y("red",hs);case"error":return y("yellow",fs);case"submit":return y("green",He)}},ws=(t)=>{switch(t){case"initial":case"active":return y("cyan",k);case"cancel":return y("red",k);case"error":return y("yellow",k);case"submit":return y("green",k)}};function xs(t,e){let n=[`${e?`${y("cyan",k)} `:""}${t.join(" \u2022 ")}`];return e&&n.push(y("cyan",Bt)),n}var Ue=(t,e,n,s,i,r=!1)=>{let o=e,a=0;if(r)for(let l=s-1;l>=n;l--){let c=t[l];if(c&&(o-=c.length),a++,o<=i)break}else for(let l=n;l<s;l++){let c=t[l];if(c&&(o-=c.length),a++,o<=i)break}return{lineCount:o,removals:a}},Cs=({cursor:t,options:e,style:n,output:s=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:r=0,rowPadding:o=4})=>{let a=Gt(s)-r,l=Ht(s),c=y("dim","..."),u=Math.max(l-o,0),h=Math.max(Math.min(i,u),5),f=0;t>=h-3&&(f=Math.max(Math.min(t-h+3,e.length-h),0));let m=h<e.length&&f>0,d=h<e.length&&f+h<e.length,b=Math.min(f+h,e.length),E=[],_=0;m&&_++,d&&_++;let x=f+(m?1:0),P=b-(d?1:0);for(let C=x;C<P;C++){let O=e[C],T=O?n(O,C===t):"",p=Q(T,a,{hard:!0,trim:!1}).split(`
|
|
17
|
+
`);E.push(p),_+=p.length}if(_>u){let C=0,O=0,T=_,p=t-x,S=u,D=()=>Ue(E,T,0,p,S),F=()=>Ue(E,T,p+1,E.length,S,!0);m?({lineCount:T,removals:C}=D(),T>S&&(d||(S-=1),{lineCount:T,removals:O}=F())):(d||(S-=1),{lineCount:T,removals:O}=F(),T>S&&(S-=1,{lineCount:T,removals:C}=D())),C>0&&(m=!0,E.splice(0,C)),O>0&&(d=!0,E.splice(E.length-O,O))}let R=[];m&&R.push(c);for(let C of E)for(let O of C)R.push(O);return d&&R.push(c),R};var zr=[`${y("dim","\u2191/\u2193")} to navigate`,`${y("dim","Space:")} select`,`${y("dim","Enter:")} confirm`];var A={message:(t=[],{symbol:e=y("gray",k),secondarySymbol:n=y("gray",k),output:s=process.stdout,spacing:i=1,withGuide:r}={})=>{let o=[],a=r??G.withGuide,l=a?n:"",c=a?`${e} `:"",u=a?`${n} `:"";for(let f=0;f<i;f++)o.push(l);let h=Array.isArray(t)?t:t.split(`
|
|
18
18
|
`);if(h.length>0){let[f,...m]=h;f.length>0?o.push(`${c}${f}`):o.push(a?e:"");for(let d of m)d.length>0?o.push(`${u}${d}`):o.push(a?n:"")}s.write(`${o.join(`
|
|
19
19
|
`)}
|
|
20
|
-
`)},info:(t,e)=>{A.message(t,{...e,symbol:y("blue",
|
|
20
|
+
`)},info:(t,e)=>{A.message(t,{...e,symbol:y("blue",gs)})},success:(t,e)=>{A.message(t,{...e,symbol:y("green",$s)})},step:(t,e)=>{A.message(t,{...e,symbol:y("green",He)})},warn:(t,e)=>{A.message(t,{...e,symbol:y("yellow",ys)})},warning:(t,e)=>{A.warn(t,e)},error:(t,e)=>{A.message(t,{...e,symbol:y("red",bs)})}};var pt=(t="",e)=>{let n=e?.output??process.stdout,s=e?.withGuide??G.withGuide?`${y("gray",ms)} `:"";n.write(`${s}${t}
|
|
21
21
|
`)},gt=(t="",e)=>{let n=e?.output??process.stdout,s=e?.withGuide??G.withGuide?`${y("gray",k)}
|
|
22
22
|
${y("gray",Bt)} `:"";n.write(`${s}${t}
|
|
23
23
|
|
|
24
|
-
`)};var
|
|
24
|
+
`)};var Yr={light:I("\u2500","-"),heavy:I("\u2501","="),block:I("\u2588","#")};var Ss=[`${y("dim","\u2191/\u2193")} to navigate`,`${y("dim","Enter:")} confirm`],mt=(t,e)=>t.includes(`
|
|
25
25
|
`)?t.split(`
|
|
26
26
|
`).map((n)=>e(n)).join(`
|
|
27
|
-
`):e(t),Be=(t)=>{let e=(s,i)=>{if(s===void 0)return"";let r=s.label??String(s.value);switch(i){case"disabled":return`${y("gray",Ve)} ${mt(r,(o)=>y("gray",o))}${s.hint?` ${y("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${mt(r,(o)=>y("dim",o))}`;case"active":return`${y("green",
|
|
27
|
+
`):e(t),Be=(t)=>{let e=(s,i)=>{if(s===void 0)return"";let r=s.label??String(s.value);switch(i){case"disabled":return`${y("gray",Ve)} ${mt(r,(o)=>y("gray",o))}${s.hint?` ${y("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${mt(r,(o)=>y("dim",o))}`;case"active":return`${y("green",ps)} ${r}${s.hint?` ${y("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${mt(r,(o)=>y(["strikethrough","dim"],o))}`;default:return`${y("dim",Ve)} ${mt(r,(o)=>y("dim",o))}`}},n=t.showInstructions??!0;return new je({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let s=t.withGuide??G.withGuide,i=`${vs(this.state)} `,r=`${ws(this.state)} `,o=ft(t.output,t.message,r,i),a=`${s?`${y("gray",k)}
|
|
28
28
|
`:""}${o}
|
|
29
29
|
`;switch(this.state){case"submit":{let l=s?`${y("gray",k)} `:"",c=ft(t.output,e(this.options[this.cursor],"selected"),l);return`${a}${c}`}case"cancel":{let l=s?`${y("gray",k)} `:"",c=ft(t.output,e(this.options[this.cursor],"cancelled"),l);return`${a}${c}${s?`
|
|
30
30
|
${y("gray",k)}`:""}`}default:{let l=s?`${y("cyan",k)} `:"",c=a.split(`
|
|
31
|
-
`).length,u=n?
|
|
32
|
-
`),f=u.length+1;return`${a}${l}${
|
|
31
|
+
`).length,u=n?xs(Ss,s):s?[y("cyan",Bt)]:[],h=u.join(`
|
|
32
|
+
`),f=u.length+1;return`${a}${l}${Cs({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:c+f,style:(m,d)=>e(m,m.disabled?"disabled":d?"active":"inactive")}).join(`
|
|
33
33
|
${l}`)}
|
|
34
34
|
${h}
|
|
35
|
-
`}}}}).prompt()};var
|
|
35
|
+
`}}}}).prompt()};var Qr=`${y("gray",k)} `;var Es=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Ke=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Is=["bold","dim","italic","underline","reset"],qe={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},_s={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},Ts={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},We={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function $t(t){return(e)=>Es?`${t}${e}${qe.reset}`:e}function Rs(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Je({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),s=typeof n==="string"&&n.length>0&&Rs(n)?n:_s[e];if(!s)return"";return t&&s in We?We[s]:s}var Os=Ke.reduce((t,e)=>{let n=Je({color:e});if(n)t[e]=$t(n);let s=Je({bright:!0,color:e});if(s)t[`${e}Bright`]=$t(s);return t},{}),Ps=Is.reduce((t,e)=>(t[e]=$t(qe[e]),t),{}),ks=Ke.reduce((t,e)=>{let n=Ts[e];if(n){let s=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[s]=$t(n)}return t},{}),v={...Os,...Ps,...ks};function Ls(t){if(ht(t))throw new W;return t}function js(t){return t.map((e)=>e.key?`${v.bold(e.key)} ${v.dim(e.text)}`:v.dim(e.text)).join(v.dim(" \xB7 "))}function Vs(t){A.info(js(t))}var Us={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function Wt(t){return Vs(Us.select),Ls(await Be({showInstructions:!1,...t}))}var Gs=4;function Z(t,e=0){if(e>=Gs)return;let n=[...t instanceof AggregateError?t.errors:[],...t.cause!==void 0?[t.cause]:[]];for(let s of n){if(A.info(v.dim(`caused by: ${s instanceof Error?s.message:String(s)}`)),s instanceof g&&s.hint)A.info(v.dim(` ${s.hint}`));if(s instanceof Error)Z(s,e+1)}}function Jt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Hs(t,e,n,s){var i,r=t[e],o=~s.string.indexOf(e)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~s.boolean.indexOf(e)?n==="false"?!1:n==="true"||(t._.push((i=+n,i*0===0)?i:n),!!n):(i=+n,i*0===0)?i:n;t[e]=r==null?o:Array.isArray(r)?r.concat(o):[r,o]}function rt(t,e){t=t||[],e=e||{};var n,s,i,r,o,a={_:[]},l=0,c=0,u=0,h=t.length;let f=e.alias!==void 0,m=e.unknown!==void 0,d=e.default!==void 0;if(e.alias=e.alias||{},e.string=Jt(e.string),e.boolean=Jt(e.boolean),f)for(n in e.alias){s=e.alias[n]=Jt(e.alias[n]);for(l=0;l<s.length;l++)(e.alias[s[l]]=s.concat(n)).splice(l,1)}for(l=e.boolean.length;l-- >0;){s=e.alias[e.boolean[l]]||[];for(c=s.length;c-- >0;)e.boolean.push(s[c])}for(l=e.string.length;l-- >0;){s=e.alias[e.string[l]]||[];for(c=s.length;c-- >0;)e.string.push(s[c])}if(d){for(n in e.default)if(r=typeof e.default[n],s=e.alias[n]=e.alias[n]||[],e[r]!==void 0){e[r].push(n);for(l=0;l<s.length;l++)e[r].push(s[l])}}let b=m?Object.keys(e.alias):[];for(l=0;l<h;l++){if(i=t[l],i==="--"){a._=a._.concat(t.slice(++l));break}for(c=0;c<i.length;c++)if(i.charCodeAt(c)!==45)break;if(c===0)a._.push(i);else if(i.substring(c,c+3)==="no-"){if(r=i.substring(c+3),m&&!~b.indexOf(r))return e.unknown(i);a[r]=!1}else{for(u=c+1;u<i.length;u++)if(i.charCodeAt(u)===61)break;r=i.substring(c,u),o=i.substring(++u)||(l+1===h||(""+t[l+1]).charCodeAt(0)===45||t[++l]),s=c===2?[r]:r;for(u=0;u<s.length;u++){if(r=s[u],m&&!~b.indexOf(r))return e.unknown("-".repeat(c)+r);Hs(a,r,u+1<s.length||o,e)}}}if(d){for(n in e.default)if(a[n]===void 0)a[n]=e.default[n]}if(f)for(n in a){s=e.alias[n]||[];while(s.length>0)a[s.shift()]=a[n]}return a}var Xe=1,Bs=2;function tt(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Kt(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[n,s]of Object.entries(t)){if(s.type==="boolean")e.boolean.push(n);else e.string.push(n);if(s.alias)e.alias[s.alias]=n;let i=tt(n);if(i!==n)e.alias[i]=n;if(s.default!==void 0)e.default[n]=s.default}return e}function yt(t,e){if(t in e)return`--${tt(t)}`;let n=Object.entries(e).find(([,s])=>s.alias===t)?.[0];if(n)return`--${tt(n)}`;return t.length===Xe?`-${t}`:`--${tt(t)}`}function H(t,e,n){let{alias:s}=Kt(e),i=Object.keys(t).find((r)=>!Object.hasOwn(e,r)&&!Object.hasOwn(s,r));if(i!==void 0)throw new g(`Unknown option: ${yt(i,e)}`,n)}function ze(t,e){for(let[s,i]of Object.entries(t))if(Array.isArray(i))throw new g(`${yt(s,e)} can only be provided once`);let n={...t};for(let[s,i]of Object.entries(e)){if(i.type!=="number")continue;let r=t[s];if(r===void 0)continue;let o=Number(r);if(typeof r==="boolean"||typeof r==="string"&&r.trim().length===0||!Number.isFinite(o)){let a=yt(s,e);throw new g(`Invalid number for ${a}: "${r}"`,`Use ${a}=<number> with a finite numeric value`)}n[s]=o}return n}function qt(t,e){let n=Kt(e);Ye(t,n,e,!0);let s=rt(t,n),i=s._[0],r=i?t.indexOf(i):-1,o=rt(r>=0?t.slice(0,r):t,n),{_:a,...l}=o;H(l,e,"Place command options after the command name");let{_:c,...u}=s,h=Object.fromEntries(Object.entries(u).filter(([m])=>(m in e)||(m in n.alias))),f=ze(h,e);return{command:i,flags:f,restArgs:r>=0?t.slice(r+1):[]}}function Xt(t,e={}){let n=Kt(e),s=Ws(t,n);Ye(s,n,e);let i=rt(s,n),{_:r,...o}=i;return{args:ze(o,e),rawPositionals:r}}function Ye(t,e,n,s=!1){let i=new Set;for(let r of t){if(r==="--")break;let o=r.match(/^-+/)?.[0];if(!o)continue;let a=r.slice(o.length),l=a.split("=",Xe)[0]??"",c=a.startsWith("no-")?[a.slice(3)]:o.length===Bs?[l]:[...l];for(let u of c){let h=Object.hasOwn(e.alias,u)?e.alias[u]??u:u;if(s&&!Object.hasOwn(n,h))continue;if(i.has(h))throw new g(`${yt(h,n)} can only be provided once`);i.add(h)}}}function Ws(t,e){let n=!0;return t.map((s)=>{if(s==="--")n=!1;if(!n)return s;return s.replace(/^--(no-[^=]+)(=.*)?$/,(i,r,o)=>{let a=e.alias[r];return a&&e.boolean.includes(a)?`--${a}${o??""}`:i})})}function zt(t,e){let n={},s=Object.entries(e);for(let[i,[r,o]]of s.entries())n[r]=o.variadic?t.slice(i):t[i];return n}function Qe(t,e){for(let[n,s]of Object.entries(e)){if(!s.required)continue;let i=t[n];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${n}${s.variadic?"...":""}>`}return null}var Js=(t)=>t,w={arg:v.magenta,cmd:v.cyan,default:v.bold,desc:Js,flag:v.green,header:(t)=>v.bold(v.yellow(t)),hint:v.dim,name:(t)=>v.bold(v.cyan(t)),placeholder:v.magenta};class Yt{metadata;commands;globalArgs;constructor(t,e,n){this.metadata=t;this.commands=e;this.globalArgs=n}version(){return`${w.name(this.metadata.name)} ${w.hint(this.metadata.version??"0.0.0")}`}global(){let t=[],{name:e,bin:n,version:s,description:i}=this.metadata;if(t.push(`${w.name(e)}${s?` ${w.hint(`v${s}`)}`:""}`),i)t.push(w.desc(i));t.push(""),t.push(w.header("Usage:")),t.push(` ${w.cmd(n)} ${w.placeholder("[command]")} ${w.placeholder("[options]")}`),t.push(""),t.push(w.header("Commands:"));let r=Array.from(this.commands.values()).map((o)=>[` ${w.cmd(o.name)}`,w.desc(o.description)]);return t.push(...this.formatColumns(r)),t.push(""),t.push(w.header("Options:")),t.push(...this.formatArgDefs(this.globalArgs)),t.push(""),t.push(`${w.hint("Run")} ${w.cmd(`${n} <command> --help`)} ${w.hint("for command details.")}`),t.join(`
|
|
36
36
|
`).trimEnd()}command(t,e){let n=[],s=e??this.metadata.bin,i=`${s} ${t.name}`,r=`${w.cmd(s)} ${w.cmd(t.name)}`;n.push(w.name(i)),n.push(w.desc(t.description)),n.push(""),n.push(w.header("Usage:"));let o=this.formatPositionalUsage(t.positionals);if(t.hasSubcommands())n.push(` ${r} ${w.placeholder("<subcommand>")} ${w.placeholder("[options]")}`);else{let c=[r];if(o)c.push(o);c.push(w.placeholder("[options]")),n.push(` ${c.join(" ")}`)}if(t.prompts&&Object.keys(t.positionals).length>0)n.push(` ${w.hint("Omit positional arguments to run interactively.")}`);if(n.push(""),t.hasSubcommands()){n.push(w.header("Subcommands:"));let c=t.getSubcommands().map((u)=>[` ${w.cmd(u.name)}`,w.desc(u.description)]);n.push(...this.formatColumns(c)),n.push("")}if(Object.entries(t.positionals).length>0)n.push(w.header("Arguments:")),n.push(...this.formatPositionalDefs(t.positionals)),n.push("");if(Object.entries(t.args).length>0)n.push(w.header("Options:")),n.push(...this.formatArgDefs(t.args));return n.join(`
|
|
37
|
-
`).trimEnd()}formatPositionalUsage(t){return Object.entries(t).map(([e,n])=>{let s=n.variadic?`${e}...`:e;return n.required?w.arg(`<${s}>`):w.arg(`[${s}]`)}).join(" ")}formatPositionalDefs(t){let e=Object.entries(t).map(([n,s])=>{let i=s.variadic?`${n}...`:n,r=w.desc(s.description??""),o=s.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${r}${o}`]});return this.formatColumns(e)}formatArgDefs(t){let e=[];for(let[n,s]of Object.entries(t)){let i=s.alias?`${w.flag(`-${s.alias}`)}, `:" ",r=s.type==="boolean"?"":` ${w.placeholder(`<${s.type==="number"?"number":"value"}>`)}`,o=`${i}${w.flag(`--${tt(n)}`)}${r}`,a=w.desc(s.description??""),l=this.formatDefault(s),c=l===void 0?"":` (default: ${w.default(l)})`;e.push([` ${o}`,`${a}${c}`])}return this.formatColumns(e)}formatDefault(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}formatColumns(t){if(t.length===0)return[];let e=Math.max(...t.map(([s])=>this.stripAnsi(s).length)),n=2;return t.map(([s,i])=>{let r=e-this.stripAnsi(s).length+n;return`${s}${" ".repeat(r)}${i}`})}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}}var J=new Uint32Array(65536),
|
|
37
|
+
`).trimEnd()}formatPositionalUsage(t){return Object.entries(t).map(([e,n])=>{let s=n.variadic?`${e}...`:e;return n.required?w.arg(`<${s}>`):w.arg(`[${s}]`)}).join(" ")}formatPositionalDefs(t){let e=Object.entries(t).map(([n,s])=>{let i=s.variadic?`${n}...`:n,r=w.desc(s.description??""),o=s.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${r}${o}`]});return this.formatColumns(e)}formatArgDefs(t){let e=[];for(let[n,s]of Object.entries(t)){let i=s.alias?`${w.flag(`-${s.alias}`)}, `:" ",r=s.type==="boolean"?"":` ${w.placeholder(`<${s.type==="number"?"number":"value"}>`)}`,o=`${i}${w.flag(`--${tt(n)}`)}${r}`,a=w.desc(s.description??""),l=this.formatDefault(s),c=l===void 0?"":` (default: ${w.default(l)})`;e.push([` ${o}`,`${a}${c}`])}return this.formatColumns(e)}formatDefault(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}formatColumns(t){if(t.length===0)return[];let e=Math.max(...t.map(([s])=>this.stripAnsi(s).length)),n=2;return t.map(([s,i])=>{let r=e-this.stripAnsi(s).length+n;return`${s}${" ".repeat(r)}${i}`})}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}}var J=new Uint32Array(65536),Ks=(t,e)=>{let n=t.length,s=e.length,i=1<<n-1,r=-1,o=0,a=n,l=n;while(l--)J[t.charCodeAt(l)]|=1<<l;for(l=0;l<s;l++){let c=J[e.charCodeAt(l)],u=c|o;if(c|=(c&r)+r^r,o|=~(c|r),r&=c,o&i)a++;if(r&i)a--;o=o<<1|1,r=r<<1|~(u|o),o&=u}l=n;while(l--)J[t.charCodeAt(l)]=0;return a},qs=(t,e)=>{let n=e.length,s=t.length,i=[],r=[],o=Math.ceil(n/32),a=Math.ceil(s/32);for(let d=0;d<o;d++)r[d]=-1,i[d]=0;let l=0;for(;l<a-1;l++){let d=0,b=-1,E=l*32,_=Math.min(32,s)+E;for(let x=E;x<_;x++)J[t.charCodeAt(x)]|=1<<x;for(let x=0;x<n;x++){let P=J[e.charCodeAt(x)],R=r[x/32|0]>>>x&1,C=i[x/32|0]>>>x&1,O=P|d,T=((P|C)&b)+b^b|P|C,p=d|~(T|b),S=b&T;if(p>>>31^R)r[x/32|0]^=1<<x;if(S>>>31^C)i[x/32|0]^=1<<x;p=p<<1|R,S=S<<1|C,b=S|~(O|p),d=p&O}for(let x=E;x<_;x++)J[t.charCodeAt(x)]=0}let c=0,u=-1,h=l*32,f=Math.min(32,s-h)+h;for(let d=h;d<f;d++)J[t.charCodeAt(d)]|=1<<d;let m=s;for(let d=0;d<n;d++){let b=J[e.charCodeAt(d)],E=r[d/32|0]>>>d&1,_=i[d/32|0]>>>d&1,x=b|c,P=((b|_)&u)+u^u|b|_,R=c|~(P|u),C=u&P;if(m+=R>>>s-1&1,m-=C>>>s-1&1,R>>>31^E)r[d/32|0]^=1<<d;if(C>>>31^_)i[d/32|0]^=1<<d;R=R<<1|E,C=C<<1|_,u=C|~(x|R),c=R&x}for(let d=h;d<f;d++)J[t.charCodeAt(d)]=0;return m},Xs=(t,e)=>{if(t.length<e.length){let n=e;e=t,t=n}if(e.length===0)return t.length;if(t.length<=32)return Ks(t,e);return qs(t,e)},Ze=(t,e)=>{let n=1/0,s=0;for(let i=0;i<e.length;i++){let r=Xs(t,e[i]);if(r<n)n=r,s=i}return e[s]};function bt(t,e,n,s){let i=Ze(e,n);if(console.error(v.red(`Unknown ${t}: ${e}`)),i)console.error(v.yellow(`Did you mean "${i}"?`));console.error(`
|
|
38
38
|
Run "${s} --help" for usage.`),process.exit(1)}function vt(t,e){if(Array.isArray(e))return[...e];if(!tn(t)||!tn(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,s])=>[n,vt(Object.hasOwn(t,n)?t[n]:void 0,s)])])}function tn(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Qt="__exit__";class et{command;env;prefix;options;selections;constructor(t,e,n,s={}){this.command=t;this.env=e;this.prefix=n;this.options=s;this.selections=s.selections??new Map}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(t,e){if(e&&process.stdout.isTTY!==!0)throw new g("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(e)await this.routeInteractive();else await this.routeDirect(t)}async routeDirect(t){let[e,...n]=t;if(e&&this.command.hasSubcommands()){let s=this.command.getSubcommand(e);if(s){await this.handleSubcommandRoute(s,n);return}if(!e.startsWith("-")){this.handleUnknownSubcommand(e);return}}await this.executeCommand(t)}handleUnknownSubcommand(t){let e=this.command.getSubcommands().map((n)=>n.name);bt("subcommand",t,e,this.commandPath)}async handleSubcommandRoute(t,e){await new et(t,this.env,this.commandPath).route(e,!1)}async executeCommand(t){if(this.isHelpRequest(t)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:n,rawPositionals:s}=Xt(t,this.command.args),i=zt(s,this.command.positionals),r=Qe(i,this.command.positionals);if(r)A.error(r),console.error(`
|
|
39
|
-
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&s.length===0&&process.stdout.isTTY===!0,a=this.buildContext(i,n,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:t}=Xt([],this.command.args),e=zt([],this.command.positionals),n=this.buildContext(e,t,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let t=await this.promptSubcommandSelectionOrBack();if(t===null)return;if(t===Qt){this.options.onExit?.();return}let e=this.command.getSubcommand(t);if(e)this.selections.set(this.commandPath,t),await this.executeSubcommand(e)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(t){if(t instanceof W){if(this.options.isRoot)this.options.onExit?.();return null}throw t}}async executeSubcommand(t){try{await new et(t,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(e){if(e instanceof W)return;if(e instanceof g){if(A.warn(v.yellow(e.message)),e.hint)A.info(v.dim(e.hint));Z(e);return}throw e}}promptSubcommandSelection(){let{isRoot:t}=this.options,e=t?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Qt}:{hint:"Return to previous menu",label:"Back",value:Qt};return Wt({message:t?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,initialValue:this.selections.get(this.commandPath),options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),e]})}buildContext(t,e,n){return{...this.env,args:e,interactive:n,positionals:t}}isHelpRequest(t){let e=t.indexOf("--"),n=e<0?t:t.slice(0,e);return n.includes("--help")||n.includes("-h")}printHelp(t){let e=t===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(t,e))}}var
|
|
39
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&s.length===0&&process.stdout.isTTY===!0,a=this.buildContext(i,n,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:t}=Xt([],this.command.args),e=zt([],this.command.positionals),n=this.buildContext(e,t,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let t=await this.promptSubcommandSelectionOrBack();if(t===null)return;if(t===Qt){this.options.onExit?.();return}let e=this.command.getSubcommand(t);if(e)this.selections.set(this.commandPath,t),await this.executeSubcommand(e)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(t){if(t instanceof W){if(this.options.isRoot)this.options.onExit?.();return null}throw t}}async executeSubcommand(t){try{await new et(t,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(e){if(e instanceof W)return;if(e instanceof g){if(A.warn(v.yellow(e.message)),e.hint)A.info(v.dim(e.hint));Z(e);return}throw e}}promptSubcommandSelection(){let{isRoot:t}=this.options,e=t?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Qt}:{hint:"Return to previous menu",label:"Back",value:Qt};return Wt({message:t?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,initialValue:this.selections.get(this.commandPath),options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),e]})}buildContext(t,e,n){return{...this.env,args:e,interactive:n,positionals:t}}isHelpRequest(t){let e=t.indexOf("--"),n=e<0?t:t.slice(0,e);return n.includes("--help")||n.includes("-h")}printHelp(t){let e=t===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(t,e))}}var zs="--",en="--help",Ys=new Set([en,"-h"]),Qs={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"},Zs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};class Zt{commands=new Map;metadata;configManager;help;bin;globalArgs={...Zs};constructor(t,e){this.configManager=t,this.metadata={...Qs,...e},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Yt({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(t){for(let e of t)e.init?.(),this.commands.set(e.name,e)}async run(t=process.argv.slice(2)){try{let{command:e,flags:n,restArgs:s}=qt(t,this.globalArgs);if(n.version&&!e)return console.log(this.help.version());if(n.interactive&&!e)return await this.runInteractive();if(!e)return console.log(this.help.global());if(e==="help")return this.printHelpFor(s[0]);await this.runDirect(e,s,!!n.help)}catch(e){this.handleError(e)}}printHelpFor(t){if(!t)return console.log(this.help.global());let e=this.commands.get(t);if(!e)return this.handleUnknownCommand(t);console.log(this.help.command(e))}async runInteractive(){this.showIntro();let t=this.createVirtualRootCommand(),e={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new et(t,e,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(s){this.handleError(s)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(t)=>this.commands.get(t),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){gt(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(t,e,n){let s=this.commands.get(t);if(!s)return this.handleUnknownCommand(t);let i=e.length>0&&!e[0]?.startsWith("-");if(n&&!i)return console.log(this.help.command(s));try{let r={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new et(s,r,this.bin).route(n?ti(e):e,!1)}catch(r){this.handleError(r)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let t=this.metadata.version?` v${this.metadata.version}`:"";pt(`${v.bgCyan(v.black(` ${this.metadata.name}${t} `))}`)}handleUnknownCommand(t){let e=Array.from(this.commands.keys());bt("command",t,e,this.bin)}handleError(t){if(this.metadata.onError?.(t))return;if(t instanceof W)process.exit(0);if(t instanceof g){if(A.warn(v.yellow(t.message)),t.hint)A.info(v.dim(t.hint));Z(t),process.exit(t.exitCode)}if(t instanceof Error)A.error(v.red(t.message)),Z(t),process.exit(1);console.error(v.red("Error:"),t),process.exit(1)}}function ti(t){let e=t.indexOf(zs),n=e<0?t:t.slice(0,e);if(n.some((s)=>Ys.has(s)))return t;return[...n,en,...e<0?[]:t.slice(e)]}class ot{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(t){for(let e of t)e.init?.(),this.subcommands.set(e.name,e)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(t){return this.subcommands.get(t)}getSubcommands(){return Array.from(this.subcommands.values())}}function B(t){return t}function nt(t){return t}import L from"fs";import rn from"path";var wt=(t)=>(t.map=(e)=>wt((n)=>e(t(n))),t.or=(e)=>wt((n)=>{try{return t(n)}catch(s){return e(n)}}),t),nn=()=>"bad banditype"();var te=(t)=>wt((e)=>typeof e===typeof t?e:nn()),ee=()=>te("");var sn=()=>te(!0);var ne=()=>te();var se=(t)=>wt((e)=>e instanceof t?e:nn());var at=(t)=>se(Object).map((e)=>{let n={};for(let s in t){let i=t[s](e[s]);i!==void 0&&(n[s]=i)}return n});function re(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),s=ei(t),i=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",r=t.includes(`\r
|
|
40
40
|
`)?`\r
|
|
41
41
|
`:`
|
|
42
42
|
`,o=/\s/.test(t[s.start+1]??"")||s.entries.some((c)=>/:\s+$/.test(t.slice(c.start,c.node.start)))?" ":"";function a(c,u){let h=t.slice(c.start,c.end);if(JSON.stringify(c.value)===JSON.stringify(u))return h;let f=Array.isArray(u);if(u===null||typeof u!=="object"||c.value===null||typeof c.value!=="object"||Array.isArray(c.value)!==f)return l(u,c.start,h.includes(`
|
|
@@ -45,16 +45,16 @@ Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command
|
|
|
45
45
|
`)?_:o}`,C=f?"":t.slice(d.start,d.node.start).match(/:\s*$/)?.[0]??": ",O=new Map(c.entries.map((p)=>[p.key,p])),T=m.map((p)=>{let S=O.get(p);if(S)return t.slice(S.start,S.node.start)+a(S.node,E(p));return(f?"":JSON.stringify(p)+C)+l(E(p),d.start,_.includes(`
|
|
46
46
|
`))});return`${f?"[":"{"}${_}${T.join(R)}${x}${f?"]":"}"}`}function l(c,u,h){if(!h)return ie(c,o);let f=t.lastIndexOf(`
|
|
47
47
|
`,u-1)+1,m=t.slice(f,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(c,null,i).replaceAll(`
|
|
48
|
-
`,r+m)}return t.slice(0,s.start)+a(s,n)+t.slice(s.end)}function ie(t,e){if(Array.isArray(t))return`[${t.map((i)=>ie(i,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let n=Object.entries(t);if(n.length===0)return"{}";let s=n.map(([i,r])=>`${JSON.stringify(i)}:${e}${ie(r,e)}`);return`{${e}${s.join(`,${e}`)}${e}}`}function
|
|
49
|
-
`;if(L.writeFileSync(n,i,{flag:"wx",mode:s}),s!==void 0)L.chmodSync(n,s);L.renameSync(n,e)}catch(s){throw Error(`Failed to save config to ${this.configPath}`,{cause:s})}finally{L.rmSync(n,{force:!0})}}assertLoaded(){if(this.loadFailure)throw this.loadFailure}ensureDirectoryExists(){let t=
|
|
48
|
+
`,r+m)}return t.slice(0,s.start)+a(s,n)+t.slice(s.end)}function ie(t,e){if(Array.isArray(t))return`[${t.map((i)=>ie(i,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let n=Object.entries(t);if(n.length===0)return"{}";let s=n.map(([i,r])=>`${JSON.stringify(i)}:${e}${ie(r,e)}`);return`{${e}${s.join(`,${e}`)}${e}}`}function ei(t){let e=t.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=e.next().value;function s(){if(!n)throw Error("Unexpected end of JSON");let r=n;return n=e.next().value,r}function i(){let r=s(),o=[],a=r[0]==="{";if(!a&&r[0]!=="[")return{end:r.index+r[0].length,entries:o,start:r.index,value:JSON.parse(r[0])};let l=a?"}":"]";while(n&&n[0]!==l){let u=n.index,h=a?JSON.parse(s()[0]):String(o.length);if(a)s();if(o.push({key:h,node:i(),start:u}),n?.[0]===",")s()}let c=s().index+1;return{end:c,entries:o,start:r.index,value:JSON.parse(t.slice(r.index,c))}}return i()}var ni=2,si=se(Object);class oe{config;configPath;defaultConfig;loadError;loadFailure;constructor(t,e,n={}){this.configPath=rn.resolve(t),this.defaultConfig=e,this.config=this.loadConfig(n)}get path(){return this.configPath}get failure(){return this.loadFailure}get(t){return this.assertLoaded(),this.config[t]}set(t,e){this.assertLoaded(),this.config={...this.config,[t]:e},this.save()}delete(t){this.assertLoaded(),delete this.config[t],this.save()}exists(){return L.existsSync(this.configPath)}getAll(){return this.assertLoaded(),structuredClone(this.config)}save(t){if(this.assertLoaded(),this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(t)this.config={...t};this.ensureDirectoryExists();let e=this.exists()?L.realpathSync(this.configPath):this.configPath,n=`${e}.${crypto.randomUUID()}.tmp`;try{let s=this.exists()?L.statSync(this.configPath).mode:void 0,i=this.exists()?re(L.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,ni)}
|
|
49
|
+
`;if(L.writeFileSync(n,i,{flag:"wx",mode:s}),s!==void 0)L.chmodSync(n,s);L.renameSync(n,e)}catch(s){throw Error(`Failed to save config to ${this.configPath}`,{cause:s})}finally{L.rmSync(n,{force:!0})}}assertLoaded(){if(this.loadFailure)throw this.loadFailure}ensureDirectoryExists(){let t=rn.dirname(this.configPath);if(!L.existsSync(t))try{L.mkdirSync(t,{recursive:!0})}catch(e){throw Error(`Failed to create config directory at ${t}`,{cause:e})}}loadConfig({parse:t,strict:e}){if(!e&&!L.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let n=this.readConfigFile();if(n===void 0)return structuredClone(this.defaultConfig);let s=JSON.parse(n);if(Array.isArray(s))throw Error("Config must be an object");let i=vt(structuredClone(this.defaultConfig),si(s));return t?t(i):i}catch(n){if(e){let s=n instanceof Error?n.message:String(n);return this.loadFailure=Error(`Cannot read config at ${this.configPath}: ${s}`,{cause:n}),structuredClone(this.defaultConfig)}return this.loadError=n,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}readConfigFile(){try{return L.readFileSync(this.configPath,"utf-8")}catch(t){if(t.code==="ENOENT")return;throw t}}}var on="0.6.6";import{mkdir as Hi}from"fs/promises";import{dirname as Bi}from"path";class V extends ot{}import{existsSync as At,readFileSync as $i}from"fs";import{dirname as le,join as wn,parse as yi,resolve as ue}from"path";var an="ATLAS",cn="atlas",K=".atlas",ct="config.json",ln=".env",xt={defaults:{profiles:[],exportFile:".env"},profiles:{}};import{homedir as ri}from"os";import{isAbsolute as oi,resolve as un}from"path";function X(t,e,n){if(t!==void 0&&t.trim().length===0)throw new g(`--${e} must not be empty`,n)}function st(t,e){return t instanceof Error&&"code"in t&&t.code===e}function q(){return process.env.HOME||ri()}function it(t,e=process.cwd()){if(t==="~")return q();if(t.startsWith("~/"))return un(q(),t.slice(2));if(oi(t))return t;return un(e,t)}function Ct(t,e){if(t===void 0)return;let n=ai(t);if(n.length===0)throw new g("--profile must include at least one profile",e);return n}function ai(t){return t.split(",").map((e)=>e.trim()).filter(Boolean)}var St=/^[A-Za-z_][A-Za-z0-9_]*$/;var ci=['"',"'","`"];function dn(t){let e=Object.create(null),n=t.split(/\r?\n/);for(let s=0;s<n.length;s+=1){let i=s+1,r=n[s]??"",o=r.trim();if(!o||o.startsWith("#"))continue;let a=o.startsWith("export ")?o.slice(7).trimStart():o,l=a.indexOf("=");if(l<0)throw Error(`Invalid dotenv syntax at line ${i}: expected KEY=VALUE`);let c=a.slice(0,l).trim();if(!St.test(c))throw Error(`Invalid dotenv key at line ${i}`);let u=a.slice(l+1).trim(),h=li(u,r,n,s);if(h){e[c]=h.value,s=h.endIndex;continue}e[c]=fn(u)}return e}function hn(t){return Object.keys(t).sort().map((e,n)=>{let s=n+1;if(!St.test(e))throw Error(`Invalid dotenv key at entry ${s}`);let i=t[e]??"",r=mi(i,e);if(fn(r)!==i)throw Error(`Unrepresentable dotenv value for key ${e}`);return`${e}=${r}`}).join(`
|
|
50
50
|
`).concat(`
|
|
51
|
-
`)}function
|
|
52
|
-
`),i)}}return}function
|
|
53
|
-
`;if(t==="r")return"\r";if(t==="t")return"\t";if(t==='"')return'"';if(t==="\\")return"\\";if(t==="$")return"$";return}function
|
|
54
|
-
`)||t.includes("\r"))&&!t.includes("'")&&!
|
|
55
|
-
`)||t.includes("\r")||t.includes("#"))return!1;if(t.trim()!==t)return!1;return ce(t[0])===void 0}function
|
|
56
|
-
`,t.args.force,"Atlas config"),A.success(`Created ${v.green(n)}`)}}var pe=B({cwd:{description:"Working directory override",type:"string"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}}),
|
|
57
|
-
`);return}if(n.length===0){A.info("No Atlas profiles configured");return}for(let s of n){let i=e.config.profiles[s],r=i?.description?v.dim(` - ${i.description}`):"";A.info(`${v.cyan(s)}${r}`)}})}}class
|
|
51
|
+
`)}function li(t,e,n,s){let i=ce(t[0]);if(i===void 0)return;if(ae(t,i,1)!==-1)return;let r=e.indexOf(i),o=[e.slice(r+1)];for(let a=s+1;a<n.length;a+=1){let l=n[a]??"",c=ae(l,i,0);if(c===-1){o.push(l);continue}if(!pn(l,c+1))return;return o.push(l.slice(0,c)),{endIndex:a,value:mn(o.join(`
|
|
52
|
+
`),i)}}return}function fn(t){let e=ce(t[0]);if(e!==void 0){let n=ui(t,e);if(n!==void 0)return mn(n,e)}return $n(di(t).trimEnd())}function ce(t){return ci.find((e)=>e===t)}function mn(t,e){return e==='"'?hi(t):$n(t)}function ui(t,e){let n=ae(t,e,1);if(n===-1)return;if(!pn(t,n+1))return;return t.slice(1,n)}function pn(t,e){let n=t.slice(e).trimStart();return!n||n.startsWith("#")}function ae(t,e,n){for(let s=n;s<t.length;s+=1)if(t[s]===e&&!gn(t,s))return s;return-1}function gn(t,e){let n=0;for(let s=e-1;t[s]==="\\";s-=1)n+=1;return n%2===1}function di(t){let e=t.search(/\s#/);return e<0?t:t.slice(0,e)}function hi(t){let e="";for(let n=0;n<t.length;n+=1){let s=t[n];if(s!=="\\"||n+1>=t.length){e+=s;continue}let i=t[n+1],r=fi(i);if(r===void 0){e+=s;continue}e+=r,n+=1}return e}function fi(t){if(t==="n")return`
|
|
53
|
+
`;if(t==="r")return"\r";if(t==="t")return"\t";if(t==='"')return'"';if(t==="\\")return"\\";if(t==="$")return"$";return}function $n(t){let e="";for(let n=0;n<t.length;n+=1){if(t[n]==="\\"&&t[n+1]==="$"){e+="$",n+=1;continue}e+=t[n]}return e}function mi(t,e){if(t.includes("\x00"))throw Error(`Unrepresentable dotenv value for key ${e}`);if(t==="")return"";let n=yn(t);if(pi(t))return n;if(!(t.includes(`
|
|
54
|
+
`)||t.includes("\r"))&&!t.includes("'")&&!gn(t,t.length))return`'${n}'`;if(!t.includes('"')&&!t.includes("\\"))return`"${gi(t)}"`;throw Error(`Unrepresentable dotenv value for key ${e}`)}function pi(t){if(t.includes(`
|
|
55
|
+
`)||t.includes("\r")||t.includes("#"))return!1;if(t.trim()!==t)return!1;return ce(t[0])===void 0}function yn(t){return t.replace(/\$(?!$)/g,"\\$&")}function gi(t){return yn(t).replace(/\n/g,"\\n").replace(/\r/g,"\\r")}var bi="must be a valid environment variable name matching [A-Za-z_][A-Za-z0-9_]*",vi=new Set(Object.getOwnPropertyNames(Object.prototype)),wi=sn().or(ne()),xi=ee().or(ne()),xn=ee();class N extends Error{_tag="AtlasConfigValidationError"}function Ci(t={}){let e=ue(t.cwd??process.cwd()),n=ue(t.home??q()),s=wn(n,K,ct),i=At(s)?s:void 0,r=Si(e,i),o=r?le(le(r)):void 0;return{cwd:e,globalPath:i,home:n,projectPath:r,projectRoot:o}}function Y(t={}){let e=Ci(t),n=bn(e.globalPath,e.home),s=bn(e.projectPath,e.projectRoot),i=z(),r=z();for(let a of[n,s]){if(!a)continue;for(let[l,c]of Object.entries(a.config.profiles))r[l]=c,i[l]=a.rootDir}return{config:{defaults:{...n?.config.defaults,...s?.config.defaults,profiles:[...n?.config.defaults?.profiles??[],...s?.config.defaults?.profiles??[]]},profiles:r},cwd:e.cwd,globalPath:e.globalPath,home:e.home,profileSources:i,projectPath:e.projectPath,projectRoot:e.projectRoot}}function Et(t,e={}){let n=[...t.config.defaults?.profiles??[],...e.profiles??[]],s=z(),i=[],r=new Set,o=e.env??process.env;function a(c,u){if(r.has(c))return;let h=Object.hasOwn(t.config.profiles,c)?t.config.profiles[c]:void 0;if(!h)throw new g(`Unknown Atlas profile: ${c}`,"Run 'atlas profiles list'");if(u.includes(c))throw new g(`Profile inheritance cycle: ${[...u,c].join(" -> ")}`);for(let d of h.extends??[])a(d,[...u,c]);let m=(Object.hasOwn(t.profileSources,c)?t.profileSources[c]:void 0)??t.projectRoot??t.cwd;for(let d of h.envFiles??[])Object.assign(s,ki(it(d,m)));Object.assign(s,h.vars??{});for(let[d,b]of Object.entries(h.secrets??{})){let E=Di(d,b,m,o);if(E!==void 0)s[d]=E}r.add(c),i.push(c)}for(let c of n)a(c,[]);let l=it(t.config.defaults?.exportFile??ln,t.projectRoot??t.cwd);return{env:s,exportFile:l,profiles:i}}function Si(t,e){let n=ue(t),s=yi(n).root;while(!0){let i=wn(n,K,ct);if(At(i)&&i!==e)return i;if(n===s)return;n=le(n)}}function bn(t,e){if(!t||!e)return;let n,s=me(t,`Atlas config ${t}`);try{n=JSON.parse(s)}catch(i){if(i instanceof SyntaxError)throw new g(`Invalid JSON in Atlas config ${t}`,"Fix the JSON syntax in the config file");throw i}try{return{config:Ai(n),path:t,rootDir:e}}catch(i){let r=i instanceof N?i.message:"config failed validation";throw new g(`Invalid Atlas config at ${t}: ${r}`)}}function Ai(t){let e=Tt(t,"config",["$schema","defaults","profiles"]);return at({$schema:(n)=>It(n,"$schema"),defaults:(n)=>Ei(n,"defaults"),profiles:(n)=>Ii(n,"profiles")})(e)}function Ei(t,e){if(t===void 0)return;let n=Tt(t,e,["exportFile","profiles"]);return at({exportFile:(s)=>Cn(s,`${e}.exportFile`),profiles:(s)=>de(s,`${e}.profiles`)})(n)}function Ii(t,e){if(t===void 0)return z();let n=_t(t,e),s=z();for(let i of Object.keys(n)){let r=fe(e,i);if(vi.has(i))throw new N(`${r} must not use a prototype-sensitive profile name`);s[i]=_i(n[i],r)}return s}function _i(t,e){let n=Tt(t,e,["description","envFiles","extends","secrets","vars"]);return at({description:(s)=>It(s,`${e}.description`),envFiles:(s)=>de(s,`${e}.envFiles`),extends:(s)=>de(s,`${e}.extends`),secrets:(s)=>Ri(s,`${e}.secrets`),vars:(s)=>Ti(s,`${e}.vars`)})(n)}function Ti(t,e){if(t===void 0)return;let n=_t(t,e),s=z();for(let i of Object.keys(n)){let r=fe(e,i);he(i,r),s[i]=Rt(xn,n[i],r,"must be a string")}return s}function Ri(t,e){if(t===void 0)return;let n=_t(t,e),s=z();for(let i of Object.keys(n)){let r=fe(e,i);he(i,r),s[i]=Oi(n[i],r)}return s}function Oi(t,e){let n=Tt(t,e,["env","file","optional","trim"]),s=at({env:(i)=>Pi(i,`${e}.env`),file:(i)=>Cn(i,`${e}.file`),optional:(i)=>vn(i,`${e}.optional`),trim:(i)=>vn(i,`${e}.trim`)})(n);if(s.env===void 0&&s.file===void 0)throw new N(`${e} must define env or file`);if(s.env!==void 0&&s.file!==void 0)throw new N(`${e} must define only one of env or file`);if(s.env!==void 0&&s.trim!==void 0)throw new N(`${e}.trim only applies to file secrets`);return s}function de(t,e){if(t===void 0)return;if(!Array.isArray(t))throw new N(`${e} must be an array`);return t.map((n,s)=>{let i=`${e}[${s}]`,r=Rt(xn,n,i,"must be a string");return Sn(r,i)})}function Cn(t,e){let n=It(t,e);return n===void 0?void 0:Sn(n,e)}function Sn(t,e){if(t.trim().length===0)throw new N(`${e} must be a non-empty string`);return t}function It(t,e){return Rt(xi,t,e,"must be a string")}function Pi(t,e){let n=It(t,e);if(n===void 0)return;return he(n,e),n}function vn(t,e){return Rt(wi,t,e,"must be a boolean")}function _t(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new N(`${e} must be an object`);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new N(`${e} must be an object`);return t}function Tt(t,e,n){let s=_t(t,e);for(let i of Object.keys(s))if(!n.includes(i))throw new N(`${e} has unknown key ${JSON.stringify(i)}`);return s}function he(t,e){if(!St.test(t))throw new N(`${e} ${bi}`)}function Rt(t,e,n,s){try{return t(e)}catch{throw new N(`${n} ${s}`)}}function fe(t,e){return`${t}[${JSON.stringify(e)}]`}function z(){return Object.create(null)}function ki(t){if(!At(t))throw new g(`Atlas env file not found: ${t}`,"Create the file or remove it from the profile's envFiles");let e=me(t,`Atlas env file ${t}`);try{return dn(e)}catch(n){let s=n instanceof Error?n.message:"env file failed to parse";throw new g(`Invalid dotenv file ${t}: ${s}`,"Fix the reported line in the env file")}}function Di(t,e,n,s){if(e.env){let i=Object.hasOwn(s,e.env)?s[e.env]:void 0;if(i!==void 0)return i;if(e.optional)return;throw new g(`Missing required secret ${t}: env ${e.env} is not set`,`Set ${e.env} or mark the secret optional`)}if(e.file){let i=it(e.file,n);if(!At(i)){if(e.optional)return;throw new g(`Missing required secret ${t}: file ${i} does not exist`,"Create the file or mark the secret optional")}let r=me(i,`secret file ${i} for ${t}`);return e.trim===!1?r:r.trim()}if(e.optional)return;throw new g(`Missing required secret ${t}: secret ref must define env or file`)}function me(t,e){try{return $i(t,"utf8")}catch(n){let s=new g(`Failed to read ${e}`,"Check that the path is a readable file");throw s.cause=n,s}}import{randomUUID as Fi}from"crypto";import{link as Ni,lstat as Mi,open as Li,rename as ji,rm as An}from"fs/promises";import{basename as Vi,dirname as Ui,join as Gi}from"path";var En=384;async function Ot(t,e,n,s="Output file"){let i=await Mi(t).catch((a)=>{if(st(a,"ENOENT"))return null;throw a});if(i&&!i.isFile()&&!i.isSymbolicLink())throw new g(`Output path is not a regular file: ${t}`);let r=Gi(Ui(t),`.${Vi(t)}.${Fi()}.tmp`),o=null;try{if(o=await Li(r,"wx",En),await o.chmod(En),await o.writeFile(e,"utf8"),await o.sync(),await o.close(),o=null,n)await ji(r,t);else await Ni(r,t).catch((a)=>{if(st(a,"EEXIST"))throw new g(`${s} already exists: ${t}`,"Use --force to overwrite it");throw a}),await An(r)}catch(a){throw await o?.close().catch(()=>{return}),await An(r,{force:!0}).catch(()=>{return}),a}}var Wi="Usage: atlas export --profile <name,...>",In=B({cwd:{description:"Working directory override",type:"string"},force:{alias:"f",default:!1,description:"Overwrite an existing file",type:"boolean"},out:{alias:"o",description:"Output .env path",type:"string"},profile:{alias:"p",description:"Comma-separated profiles to apply",type:"string"},stdout:{default:!1,description:"Print to stdout instead of writing a file",type:"boolean"}});class Pt extends V{name="export";description="Export resolved Atlas env to a dotenv file";args=In;async execute(t){if(H(t.args,In,"Run 'atlas export --help' for supported options"),t.args.stdout&&t.args.out!==void 0)throw new g("--stdout cannot be combined with --out","Use --stdout to print, or --out <path> to write a file");X(t.args.cwd,"cwd","Usage: atlas export --cwd <dir>"),X(t.args.out,"out","Usage: atlas export --out <path>");let e=Ct(t.args.profile,Wi),n=t.args.cwd??process.cwd(),s=Y({cwd:n}),i=Et(s,{profiles:e}),r=hn(i.env);if(t.args.stdout){process.stdout.write(r);return}let o=t.args.out!==void 0?it(t.args.out,s.cwd):i.exportFile;await Hi(Bi(o),{recursive:!0}),await Ot(o,r,t.args.force),A.success(`Wrote ${v.green(o)} using ${i.profiles.length} profile(s)`)}}import{mkdir as Ji}from"fs/promises";import{join as _n}from"path";var Tn=B({force:{alias:"f",default:!1,description:"Overwrite an existing config",type:"boolean"},global:{alias:"g",default:!1,description:"Write ~/.atlas/config.json",type:"boolean"}});class kt extends V{name="init";description="Create an Atlas config";args=Tn;async execute(t){H(t.args,Tn,"Run 'atlas init --help' for supported options");let e=t.args.global?q():process.cwd(),n=_n(e,K,ct);await Ji(_n(e,K),{recursive:!0}),await Ot(n,`${JSON.stringify(xt,null,2)}
|
|
56
|
+
`,t.args.force,"Atlas config"),A.success(`Created ${v.green(n)}`)}}var pe=B({cwd:{description:"Working directory override",type:"string"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}}),Ki=nt({profile:{description:"Profile name",required:!0}});class Dt extends V{name="profiles";description="Inspect Atlas profiles";init(){this.registerSubcommands([new Rn,new On])}}class Rn extends V{name="list";description="List available profiles";args=pe;async execute(t){kn(t.args.json,()=>{Pn(t.args);let e=Y({cwd:t.args.cwd??process.cwd()}),n=Object.keys(e.config.profiles).sort();if(t.args.json){process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
57
|
+
`);return}if(n.length===0){A.info("No Atlas profiles configured");return}for(let s of n){let i=e.config.profiles[s],r=i?.description?v.dim(` - ${i.description}`):"";A.info(`${v.cyan(s)}${r}`)}})}}class On extends V{name="show";description="Show one Atlas profile";args=pe;positionals=Ki;async execute(t){kn(t.args.json,()=>{Pn(t.args);let e=t.positionals.profile;if(!e)throw new g("Profile name is required","Usage: atlas profiles show <profile>");let s=Y({cwd:t.args.cwd??process.cwd()}).config.profiles,i=Object.hasOwn(s,e)?s[e]:void 0;if(!i){let r=`Unknown Atlas profile: ${e}`;throw new g(r,"Run 'atlas profiles list'")}if(t.args.json){process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
58
58
|
`);return}A.info(`${v.bold(e)}
|
|
59
|
-
${JSON.stringify(i,null,2)}`)})}}function
|
|
60
|
-
`),process.exitCode=n.exitCode}}import{statSync as
|
|
59
|
+
${JSON.stringify(i,null,2)}`)})}}function Pn(t){H(t,pe,"Run 'atlas profiles --help' for supported commands"),X(t.cwd,"cwd","Usage: atlas profiles <list|show> --cwd <dir>")}function kn(t,e){try{e()}catch(n){if(!t||!(n instanceof g))throw n;process.stderr.write(`${JSON.stringify({error:n.message})}
|
|
60
|
+
`),process.exitCode=n.exitCode}}import{statSync as qi}from"fs";import{resolve as Xi}from"path";var Dn=B({cwd:{description:"Working directory override",type:"string"},profile:{alias:"p",description:"Comma-separated profiles to apply",type:"string"}}),zi=127,Yi=126,Qi="Put child command flags after --: atlas run -p app -- <cmd> --flags",Zi="Usage: atlas run --profile <name,...> -- <command...>",tr=nt({command:{description:"Command to run",required:!0,variadic:!0}});class Ft extends V{name="run";description="Run a command with resolved Atlas env";args=Dn;positionals=tr;async execute(t){H(t.args,Dn,Qi);let e=t.positionals.command;if(e.length===0)throw new g("Command is required","Usage: atlas run --profile app:web -- <command...>");X(t.args.cwd,"cwd","Usage: atlas run --cwd <dir> -- <command...>");let n=Ct(t.args.profile,Zi),s=Xi(t.args.cwd??process.cwd());if(!qi(s,{throwIfNoEntry:!1})?.isDirectory())throw new g(`Working directory is not a directory: ${s}`,"Usage: atlas run --cwd <dir> -- <command...>");let i=nr(s,n),r=er(e,s,i),o=()=>r.kill("SIGINT"),a=()=>r.kill("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",a);let l;try{l=await r.exited}finally{process.off("SIGINT",o),process.off("SIGTERM",a)}if(l!==0)process.exit(l)}}function er(t,e,n){try{return Bun.spawn(t,{cwd:e,env:n,stderr:"inherit",stdin:"inherit",stdout:"inherit"})}catch(s){if(st(s,"ENOENT"))throw new g(`Command not found: ${t[0]}`,"Check that it is installed and on PATH",zi);if(st(s,"EACCES"))throw new g(`Command is not executable: ${t[0]}`,"Check the executable permissions",Yi);throw s}}function nr(t,e){let n=Y({cwd:t}),s=Et(n,{profiles:e});return{...Object.fromEntries(Object.entries(process.env).filter((r)=>r[1]!==void 0)),...s.env}}class Fn extends Zt{constructor(){super(new oe(sr(q(),K,"cli-state.json"),xt),{bin:cn,clearOnStart:!1,description:"Profile-based env composition for apps and environments",name:an,version:on})}init(){this.registerCommands([new kt,new Dt,new Ft,new Pt])}}var ir=new Fn;ir.run();
|
package/package.json
CHANGED
|
@@ -32,9 +32,8 @@
|
|
|
32
32
|
"dev": "bun --bun src/cli.ts",
|
|
33
33
|
"package:dryRun": "bun ../../tools/scripts/publish-package.ts . --dry-run",
|
|
34
34
|
"package:prepare": "NODE_ENV=production bun run build && bun ../../tools/scripts/prepare-publish.ts .",
|
|
35
|
-
"package:publish": "bun ../../tools/scripts/publish-package.ts ."
|
|
36
|
-
"type-check": "bun --bun tsc --noEmit"
|
|
35
|
+
"package:publish": "bun ../../tools/scripts/publish-package.ts ."
|
|
37
36
|
},
|
|
38
37
|
"type": "module",
|
|
39
|
-
"version": "0.6.
|
|
38
|
+
"version": "0.6.6"
|
|
40
39
|
}
|