@r5n/atlas 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +68 -0
  3. package/dist/cli.js +60 -0
  4. package/package.json +40 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright R5N Labs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/r5n-labs/clis/develop/packages/atlas/assets/logo.svg" width="128" alt="Atlas logo — a globe held aloft">
3
+ </p>
4
+
5
+ # Atlas
6
+
7
+ **Build an environment from the pieces you need.**
8
+
9
+ Combine named profiles for a team, application, environment or machine. Atlas resolves their dotenv files, literal values and secret references, then runs a command with that environment or exports a dotenv file.
10
+
11
+ Requires [Bun](https://bun.sh).
12
+
13
+ ## Quick start
14
+
15
+ Install Atlas, then initialise configuration in your project:
16
+
17
+ ```sh
18
+ bun add -g @r5n/atlas
19
+ atlas init
20
+ ```
21
+
22
+ Define profiles in the generated `.atlas/config.json`:
23
+
24
+ ```json
25
+ {
26
+ "defaults": { "profiles": ["team"], "exportFile": ".env.generated" },
27
+ "profiles": {
28
+ "team": { "vars": { "ORG": "r5n" } },
29
+ "env:dev": {
30
+ "vars": { "NODE_ENV": "development" }
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Run a command or export the resolved environment:
37
+
38
+ ```sh
39
+ atlas run --profile env:dev -- bun --version
40
+ atlas export --profile env:dev
41
+ ```
42
+
43
+ Put child-command flags after `--`. The export uses `.env.generated` from the defaults; add `--out <path>` to choose another file.
44
+
45
+ ## Everyday commands
46
+
47
+ | Task | Command |
48
+ | --- | --- |
49
+ | Initialise project or global config | `atlas init [--global]` |
50
+ | List available profiles | `atlas profiles list` |
51
+ | Inspect a profile | `atlas profiles show <profile>` |
52
+ | Combine profiles for a process | `atlas run --profile app:web,env:dev -- <command...>` |
53
+ | Export a dotenv file | `atlas export --profile app:web,env:dev --out <path>` |
54
+ | Print dotenv to stdout | `atlas export --profile env:dev --stdout` |
55
+
56
+ ## How profiles combine
57
+
58
+ Atlas merges global `~/.atlas/config.json` with the nearest project `.atlas/config.json`. Profiles can extend parents, read dotenv files, set non-secret values and resolve secrets from environment variables or files. Project profiles override global profiles of the same name.
59
+
60
+ The [configuration reference](https://github.com/r5n-labs/clis/blob/develop/packages/atlas/docs/reference.md) explains precedence, inheritance, secret references, dotenv parsing and export limits. Atlas preserves literal `$` references rather than expanding them.
61
+
62
+ Project configuration is applied automatically, and secret file references may point outside the project. Review a repository's `.atlas/config.json` before using Atlas inside it.
63
+
64
+ For source commands, builds and checks, see the [development guide](https://github.com/r5n-labs/clis/blob/develop/packages/atlas/docs/development.md).
65
+
66
+ ## Licence
67
+
68
+ [Apache 2.0](LICENSE).
package/dist/cli.js ADDED
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var Fn=Object.create;var{getPrototypeOf:Nn,defineProperty:pe,getOwnPropertyNames:jn}=Object;var ge=Object.prototype.hasOwnProperty;function Ln(t){return this[t]}var Vn,Un,$e=(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?Fn(Nn(t)):{};let o=e||!t||!t.__esModule||!ge.call(t,"default")?pe(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of jn(t))if(!ge.call(o,a))pe(o,a,{get:Ln.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 Lt=Gn(function(fr,Pe){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}};Pe.exports={cursor:jt,scroll:ns,erase:ss,beep:"\x07"}});import{homedir as er}from"os";import{join as nr}from"path";class B 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 ke,stdin as is}from"process";import rs from"readline";var ye=(()=>{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}})(),be=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,ve=(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,we=/(?:(?![\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,xe=/[\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:""},Ce=(t,e={},n={})=>{let s=e.limit??1/0,i=e.ellipsis??"",r=e?.ellipsisWidth??(i?Ce(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,m=n.wideWidth??2,f=[[Jn,h],[Hn,0],[Bn,a],[Wn,l],[xe,c],[we,m]],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 M=D.codePointAt(0)||0;if(be(M))p=2;else if(ve(M))p=m;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=f.length;S<D;S++){let[M,fe]=f[S];if(M.lastIndex=b,M.test(t)){if(_=M===we?ye(t.slice(b,M.lastIndex)):M===xe?1:M.lastIndex-b,p=_*fe,T+p>R)P=Math.min(P,b+Math.floor((R-T)/fe));if(T+p>s){x=!0;break t}T+=p,C=d,O=b,b=d=M.lastIndex;continue t}}b+=1}return{width:x?R:T,index:x?P:E,truncated:x,ellipsed:x&&s>=r}},Se=Ce;var Xn={limit:1/0,ellipsis:"",ellipsisWidth:0},zn=(t,e={})=>Se(t,Xn,e).width,U=zn;var ct="\x1B",Te="\x9B",Yn=39,Ft="\x07",Re="[",Qn="]",Oe="m",Nt=`${Qn}8;;`,Ae=new RegExp(`(?:\\${Re}(?<code>\\d+)m|\\${Nt}(?<uri>.*)${Ft})`,"y"),Ee=(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},Ie=(t)=>`${ct}${Re}${t}${Oe}`,_e=(t)=>`${ct}${Nt}${t}${Ft}`,Mt=(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,m=U(h);if(a+m<=n)t[t.length-1]+=h;else t.push(h),a=0;if(h===ct||h===Te)i=!0,r=e.startsWith(Nt,u+1);if(i){if(r){if(h===Ft)i=!1,r=!1}else if(h===Oe)i=!1}else if(a+=m,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 m=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 f=U(m);if(n.hard&&f>e){let d=e-l,b=1+Math.floor((f-d-1)/e);if(Math.floor((f-1)/e)<b)a.push("");Mt(a,m,e),l=U(a.at(-1)??"");continue}if(l+f>e&&l&&f){if(n.wordWrap===!1&&l<e){Mt(a,m,e),l=U(a.at(-1)??"");continue}a.push(""),l=0}if(l+f>e&&n.wordWrap===!1){Mt(a,m,e),l=U(a.at(-1)??"");continue}a[a.length-1]+=m,l+=f}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 m=c[h];if(s+=m,!u){if(u=m>="\uD800"&&m<="\uDBFF",u)continue}else u=!1;if(m===ct||m===Te){Ae.lastIndex=h+1;let d=Ae.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
+ `){if(r)s+=_e("");let f=i?Ee(i):void 0;if(i&&f)s+=Ie(f)}else if(m===`
6
+ `){if(i&&Ee(i))s+=Ie(i);if(r)s+=_e(r)}}return s},es=/\r?\n/;function Y(t,e,n){return String(t).normalize().split(es).map((s)=>ts(s,e,n)).join(`
7
+ `)}var N=$e(Lt(),1);function ut(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?ut(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 De(t,e){if(typeof t=="string")return G.aliases.get(t)===e;for(let n of t)if(n!==void 0&&De(n,e))return!0;return!1}function cs(t,e){if(t===e)return;let n=t.split(`
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 yr=globalThis.process.platform.startsWith("win"),Vt=Symbol("clack:cancel");function dt(t){return t===Vt}function lt(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var Ut=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,Gt=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function ht(t,e,n,s=n,i=n,r){let o=Ut(t??ke);return Y(e,o-n.length,{hard:!0,trim:!1}).split(`
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 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 Fe{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=ke,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(Vt);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),lt(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(N.cursor.show),this.output.off("resize",this.render),lt(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(N.cursor.show),this.output.off("resize",this.render),lt(this.input,!1),t(Vt)})})}_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")}De([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
+ `),lt(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Y(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
+ `).length-1;this.output.write(N.cursor.move(-999,t*-1))}render(){let t=Y(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(N.cursor.hide);else{let e=cs(this._prevFrame,t),n=Gt(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(N.cursor.move(0,r-i)),this.output.write(N.erase.lines(1));let o=t.split(`
14
+ `);this.output.write(o[r]),this._prevFrame=t,this.output.write(N.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(N.cursor.move(0,a))}this.output.write(N.erase.down());let o=t.split(`
15
+ `).slice(r);this.output.write(o.join(`
16
+ `)),this._prevFrame=t;return}}this.output.write(N.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}var Ne=class extends Fe{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?ut(s,1,this.options):s,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=ut(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ut(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as y,stripVTControlCharacters as kr}from"util";import L from"process";var Ve=$e(Lt(),1);function ls(){if(L.platform!=="win32")return L.env.TERM!=="linux";return Boolean(L.env.CI)||Boolean(L.env.WT_SESSION)||Boolean(L.env.TERMINUS_SUBLIME)||L.env.ConEmuTask==="{cmd::Cmder}"||L.env.TERM_PROGRAM==="Terminus-Sublime"||L.env.TERM_PROGRAM==="vscode"||L.env.TERM==="xterm-256color"||L.env.TERM==="alacritty"||L.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var us=ls();var I=(t,e)=>us?t:e,ds=I("\u25C6","*"),hs=I("\u25A0","x"),ms=I("\u25B2","x"),Ue=I("\u25C7","o"),fs=I("\u250C","T"),k=I("\u2502","|"),Ht=I("\u2514","\u2014"),Nr=I("\u2510","T"),jr=I("\u2518","\u2014"),ps=I("\u25CF",">"),je=I("\u25CB"," "),Lr=I("\u25FB","[\u2022]"),Vr=I("\u25FC","[+]"),Ur=I("\u25FB","[ ]"),Gr=I("\u25AA","\u2022"),Hr=I("\u2500","-"),Br=I("\u256E","+"),Wr=I("\u251C","+"),Jr=I("\u256F","+"),Kr=I("\u2570","+"),qr=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",ms);case"submit":return y("green",Ue)}},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",Ht)),n}var Le=(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=Ut(s)-r,l=Gt(s),c=y("dim","..."),u=Math.max(l-o,0),h=Math.max(Math.min(i,u),5),m=0;t>=h-3&&(m=Math.max(Math.min(t-h+3,e.length-h),0));let f=h<e.length&&m>0,d=h<e.length&&m+h<e.length,b=Math.min(m+h,e.length),E=[],_=0;f&&_++,d&&_++;let x=m+(f?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=Y(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=()=>Le(E,T,0,p,S),M=()=>Le(E,T,p+1,E.length,S,!0);f?({lineCount:T,removals:C}=D(),T>S&&(d||(S-=1),{lineCount:T,removals:O}=M())):(d||(S-=1),{lineCount:T,removals:O}=M(),T>S&&(S-=1,{lineCount:T,removals:C}=D())),C>0&&(f=!0,E.splice(0,C)),O>0&&(d=!0,E.splice(E.length-O,O))}let R=[];f&&R.push(c);for(let C of E)for(let O of C)R.push(O);return d&&R.push(c),R};var Xr=[`${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 m=0;m<i;m++)o.push(l);let h=Array.isArray(t)?t:t.split(`
18
+ `);if(h.length>0){let[m,...f]=h;m.length>0?o.push(`${c}${m}`):o.push(a?e:"");for(let d of f)d.length>0?o.push(`${u}${d}`):o.push(a?n:"")}s.write(`${o.join(`
19
+ `)}
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",Ue)})},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 ft=(t="",e)=>{let n=e?.output??process.stdout,s=e?.withGuide??G.withGuide?`${y("gray",fs)} `:"";n.write(`${s}${t}
21
+ `)},pt=(t="",e)=>{let n=e?.output??process.stdout,s=e?.withGuide??G.withGuide?`${y("gray",k)}
22
+ ${y("gray",Ht)} `:"";n.write(`${s}${t}
23
+
24
+ `)};var zr={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
+ `)?t.split(`
26
+ `).map((n)=>e(n)).join(`
27
+ `):e(t),Ge=(t)=>{let e=(s,i)=>{if(s===void 0)return"";let r=s.label??String(s.value);switch(i){case"disabled":return`${y("gray",je)} ${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",je)} ${mt(r,(o)=>y("dim",o))}`}},n=t.showInstructions??!0;return new Ne({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=ht(t.output,t.message,r,i),a=`${s?`${y("gray",k)}
28
+ `:""}${o}
29
+ `;switch(this.state){case"submit":{let l=s?`${y("gray",k)} `:"",c=ht(t.output,e(this.options[this.cursor],"selected"),l);return`${a}${c}`}case"cancel":{let l=s?`${y("gray",k)} `:"",c=ht(t.output,e(this.options[this.cursor],"cancelled"),l);return`${a}${c}${s?`
30
+ ${y("gray",k)}`:""}`}default:{let l=s?`${y("cyan",k)} `:"",c=a.split(`
31
+ `).length,u=n?xs(Ss,s):s?[y("cyan",Ht)]:[],h=u.join(`
32
+ `),m=u.length+1;return`${a}${l}${Cs({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:c+m,style:(f,d)=>e(f,f.disabled?"disabled":d?"active":"inactive")}).join(`
33
+ ${l}`)}
34
+ ${h}
35
+ `}}}}).prompt()};var Yr=`${y("gray",k)} `;var Es=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),We=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Is=["bold","dim","italic","underline","reset"],Je={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"},He={"\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 gt(t){return(e)=>Es?`${t}${e}${Je.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 Be({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 He?He[s]:s}var Os=We.reduce((t,e)=>{let n=Be({color:e});if(n)t[e]=gt(n);let s=Be({bright:!0,color:e});if(s)t[`${e}Bright`]=gt(s);return t},{}),Ps=Is.reduce((t,e)=>(t[e]=gt(Je[e]),t),{}),ks=We.reduce((t,e)=>{let n=Ts[e];if(n){let s=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[s]=gt(n)}return t},{}),v={...Os,...Ps,...ks};function js(t){if(dt(t))throw new B;return t}function Ls(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(Ls(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 Bt(t){return Vs(Us.select),js(await Ge({showInstructions:!1,...t}))}var Gs=4;function Q(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)Q(s,e+1)}}function Wt(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 it(t,e){t=t||[],e=e||{};var n,s,i,r,o,a={_:[]},l=0,c=0,u=0,h=t.length;let m=e.alias!==void 0,f=e.unknown!==void 0,d=e.default!==void 0;if(e.alias=e.alias||{},e.string=Wt(e.string),e.boolean=Wt(e.boolean),m)for(n in e.alias){s=e.alias[n]=Wt(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=f?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),f&&!~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],f&&!~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(m)for(n in a){s=e.alias[n]||[];while(s.length>0)a[s.shift()]=a[n]}return a}var Ke=1,Bs=2;function Z(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Jt(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=Z(n);if(i!==n)e.alias[i]=n;if(s.default!==void 0)e.default[n]=s.default}return e}function $t(t,e){if(t in e)return`--${Z(t)}`;let n=Object.entries(e).find(([,s])=>s.alias===t)?.[0];if(n)return`--${Z(n)}`;return t.length===Ke?`-${t}`:`--${Z(t)}`}function qe(t,e,n){let{alias:s}=Jt(e),i=Object.keys(t).find((r)=>!Object.hasOwn(e,r)&&!Object.hasOwn(s,r));if(i!==void 0)throw new g(`Unknown option: ${$t(i,e)}`,n)}function Xe(t,e){for(let[s,i]of Object.entries(t))if(Array.isArray(i))throw new g(`${$t(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=$t(s,e);throw new g(`Invalid number for ${a}: "${r}"`,`Use ${a}=<number> with a finite numeric value`)}n[s]=o}return n}function ze(t,e){let n=Jt(e);Ye(t,n,e,!0);let s=it(t,n),i=s._[0],r=i?t.indexOf(i):-1,o=it(r>=0?t.slice(0,r):t,n),{_:a,...l}=o;qe(l,e,"Place command options after the command name");let{_:c,...u}=s,h=Object.fromEntries(Object.entries(u).filter(([f])=>(f in e)||(f in n.alias))),m=Xe(h,e);return{command:i,flags:m,restArgs:r>=0?t.slice(r+1):[]}}function Kt(t,e={}){let n=Jt(e),s=Ws(t,n);Ye(s,n,e);let i=it(s,n),{_:r,...o}=i;return{args:Xe(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("=",Ke)[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(`${$t(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 qt(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 Xt{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
+ `).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(`--${Z(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 W=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--)W[t.charCodeAt(l)]|=1<<l;for(l=0;l<s;l++){let c=W[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--)W[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++)W[t.charCodeAt(x)]|=1<<x;for(let x=0;x<n;x++){let P=W[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++)W[t.charCodeAt(x)]=0}let c=0,u=-1,h=l*32,m=Math.min(32,s-h)+h;for(let d=h;d<m;d++)W[t.charCodeAt(d)]|=1<<d;let f=s;for(let d=0;d<n;d++){let b=W[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(f+=R>>>s-1&1,f-=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<m;d++)W[t.charCodeAt(d)]=0;return f},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 yt(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
+ Run "${s} --help" for usage.`),process.exit(1)}function bt(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,bt(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 zt="__exit__";class tt{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);yt("subcommand",t,e,this.commandPath)}async handleSubcommandRoute(t,e){await new tt(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}=Kt(t,this.command.args),i=qt(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}=Kt([],this.command.args),e=qt([],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===zt){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 B){if(this.options.isRoot)this.options.onExit?.();return null}throw t}}async executeSubcommand(t){try{await new tt(t,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(e){if(e instanceof B)return;if(e instanceof g){if(A.warn(v.yellow(e.message)),e.hint)A.info(v.dim(e.hint));Q(e);return}throw e}}promptSubcommandSelection(){let{isRoot:t}=this.options,e=t?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:zt}:{hint:"Return to previous menu",label:"Back",value:zt};return Bt({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={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Yt{commands=new Map;metadata;configManager;help;bin;globalArgs={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"}};constructor(t,e){this.configManager=t,this.metadata={...zs,...e},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Xt({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}=ze(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 tt(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(){pt(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 tt(s,r,this.bin).route(e,!1)}catch(r){this.handleError(r)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let t=this.metadata.version?` v${this.metadata.version}`:"";ft(`${v.bgCyan(v.black(` ${this.metadata.name}${t} `))}`)}handleUnknownCommand(t){let e=Array.from(this.commands.keys());yt("command",t,e,this.bin)}handleError(t){if(this.metadata.onError?.(t))return;if(t instanceof B)process.exit(0);if(t instanceof g){if(A.warn(v.yellow(t.message)),t.hint)A.info(v.dim(t.hint));Q(t),process.exit(t.exitCode)}if(t instanceof Error)A.error(v.red(t.message)),Q(t),process.exit(1);console.error(v.red("Error:"),t),process.exit(1)}}class rt{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 H(t){return t}function et(t){return t}import j from"fs";import sn from"path";var vt=(t)=>(t.map=(e)=>vt((n)=>e(t(n))),t.or=(e)=>vt((n)=>{try{return t(n)}catch(s){return e(n)}}),t),en=()=>"bad banditype"();var Qt=(t)=>vt((e)=>typeof e===typeof t?e:en()),Zt=()=>Qt("");var nn=()=>Qt(!0);var te=()=>Qt();var ee=(t)=>vt((e)=>e instanceof t?e:en());var ot=(t)=>ee(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 se(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),s=Ys(t),i=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",r=t.includes(`\r
40
+ `)?`\r
41
+ `:`
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 m=Array.isArray(u);if(u===null||typeof u!=="object"||c.value===null||typeof c.value!=="object"||Array.isArray(c.value)!==m)return l(u,c.start,h.includes(`
43
+ `));let f=m?u.map((p,S)=>String(S)):[...new Set([...c.entries.map((p)=>p.key).filter((p)=>Object.hasOwn(u,p)),...Object.keys(u)])];if(f.length===0)return m?"[]":"{}";let d=c.entries[0],b=c.entries.at(-1);if(!d||!b)return l(u,c.start,h.includes(`
44
+ `));let E=(p)=>m?u[Number(p)]:u[p];if(f.length===c.entries.length&&f.every((p,S)=>p===c.entries[S]?.key)){let p=c.start,S="";for(let D of c.entries)S+=t.slice(p,D.node.start)+a(D.node,E(D.key)),p=D.node.end;return S+t.slice(p,c.end)}let _=t.slice(c.start+1,d.start),x=t.slice(b.node.end,c.end-1),P=c.entries[1],R=P?t.slice(d.node.end,P.start):`,${_.includes(`
45
+ `)?_:o}`,C=m?"":t.slice(d.start,d.node.start).match(/:\s*$/)?.[0]??": ",O=new Map(c.entries.map((p)=>[p.key,p])),T=f.map((p)=>{let S=O.get(p);if(S)return t.slice(S.start,S.node.start)+a(S.node,E(p));return(m?"":JSON.stringify(p)+C)+l(E(p),d.start,_.includes(`
46
+ `))});return`${m?"[":"{"}${_}${T.join(R)}${x}${m?"]":"}"}`}function l(c,u,h){if(!h)return ne(c,o);let m=t.lastIndexOf(`
47
+ `,u-1)+1,f=t.slice(m,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(c,null,i).replaceAll(`
48
+ `,r+f)}return t.slice(0,s.start)+a(s,n)+t.slice(s.end)}function ne(t,e){if(Array.isArray(t))return`[${t.map((i)=>ne(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}${ne(r,e)}`);return`{${e}${s.join(`,${e}`)}${e}}`}function Ys(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 Qs=2,Zs=ee(Object);class ie{config;configPath;defaultConfig;loadError;constructor(t,e){this.configPath=sn.resolve(t),this.defaultConfig=e,this.config=this.loadConfig()}get path(){return this.configPath}get(t){return this.config[t]}set(t,e){this.config={...this.config,[t]:e},this.save()}delete(t){delete this.config[t],this.save()}exists(){return j.existsSync(this.configPath)}getAll(){return structuredClone(this.config)}save(t){if(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()?j.realpathSync(this.configPath):this.configPath,n=`${e}.${crypto.randomUUID()}.tmp`;try{let s=this.exists()?j.statSync(this.configPath).mode:void 0,i=this.exists()?se(j.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,Qs)}
49
+ `;if(j.writeFileSync(n,i,{flag:"wx",mode:s}),s!==void 0)j.chmodSync(n,s);j.renameSync(n,e)}catch(s){throw Error(`Failed to save config to ${this.configPath}`,{cause:s})}finally{j.rmSync(n,{force:!0})}}ensureDirectoryExists(){let t=sn.dirname(this.configPath);if(!j.existsSync(t))try{j.mkdirSync(t,{recursive:!0})}catch(e){throw Error(`Failed to create config directory at ${t}`,{cause:e})}}loadConfig(){if(!j.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let t=j.readFileSync(this.configPath,"utf-8"),e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");let n=Zs(e);return bt(structuredClone(this.defaultConfig),n)}catch(t){return this.loadError=t,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}}var rn="0.6.1";import{mkdir as Vi}from"fs/promises";import{dirname as Ui}from"path";class V extends rt{}import{existsSync as St,readFileSync as mi}from"fs";import{homedir as fi}from"os";import{dirname as ae,join as wn,parse as pi,resolve as ce}from"path";var on="ATLAS",an="atlas",J=".atlas",at="config.json",cn=".env",wt={defaults:{profiles:[],exportFile:".env"},profiles:{}};import{homedir as ln}from"os";import{isAbsolute as ei,resolve as un}from"path";var ni=1;function K(t,e,n){let s=new Set(Object.entries(e).flatMap(([o,a])=>a.alias?[o,a.alias]:[o])),i=Object.keys(t).find((o)=>!s.has(o));if(i===void 0)return;let r=i.length===ni?`-${i}`:`--${i}`;throw new g(`Unknown option: ${r}`,n)}function q(t,e,n){if(t!==void 0&&t.trim().length===0)throw new g(`--${e} must not be empty`,n)}function nt(t,e){return t instanceof Error&&"code"in t&&t.code===e}function st(t,e=process.cwd()){if(t==="~")return ln();if(t.startsWith("~/"))return un(ln(),t.slice(2));if(ei(t))return t;return un(e,t)}function xt(t,e){if(t===void 0)return;let n=si(t);if(n.length===0)throw new g("--profile must include at least one profile",e);return n}function si(t){return t.split(",").map((e)=>e.trim()).filter(Boolean)}var Ct=/^[A-Za-z_][A-Za-z0-9_]*$/;var ii=['"',"'","`"];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(!Ct.test(c))throw Error(`Invalid dotenv key at line ${i}`);let u=a.slice(l+1).trim(),h=ri(u,r,n,s);if(h){e[c]=h.value,s=h.endIndex;continue}e[c]=mn(u)}return e}function hn(t){return Object.keys(t).sort().map((e,n)=>{let s=n+1;if(!Ct.test(e))throw Error(`Invalid dotenv key at entry ${s}`);let i=t[e]??"",r=ui(i,e);if(mn(r)!==i)throw Error(`Unrepresentable dotenv value for key ${e}`);return`${e}=${r}`}).join(`
50
+ `).concat(`
51
+ `)}function ri(t,e,n,s){let i=oe(t[0]);if(i===void 0)return;if(re(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=re(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:fn(o.join(`
52
+ `),i)}}return}function mn(t){let e=oe(t[0]);if(e!==void 0){let n=oi(t,e);if(n!==void 0)return fn(n,e)}return $n(ai(t).trimEnd())}function oe(t){return ii.find((e)=>e===t)}function fn(t,e){return e==='"'?ci(t):$n(t)}function oi(t,e){let n=re(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 re(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 ai(t){let e=t.search(/\s#/);return e<0?t:t.slice(0,e)}function ci(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=li(i);if(r===void 0){e+=s;continue}e+=r,n+=1}return e}function li(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 ui(t,e){if(t.includes("\x00"))throw Error(`Unrepresentable dotenv value for key ${e}`);if(t==="")return"";let n=yn(t);if(di(t))return n;if(!(t.includes(`
54
+ `)||t.includes("\r"))&&!t.includes("'")&&!gn(t,t.length))return`'${n}'`;if(!t.includes('"')&&!t.includes("\\"))return`"${hi(t)}"`;throw Error(`Unrepresentable dotenv value for key ${e}`)}function di(t){if(t.includes(`
55
+ `)||t.includes("\r")||t.includes("#"))return!1;if(t.trim()!==t)return!1;return oe(t[0])===void 0}function yn(t){return t.replace(/\$(?!$)/g,"\\$&")}function hi(t){return yn(t).replace(/\n/g,"\\n").replace(/\r/g,"\\r")}var gi="must be a valid environment variable name matching [A-Za-z_][A-Za-z0-9_]*",$i=new Set(Object.getOwnPropertyNames(Object.prototype)),yi=nn().or(te()),bi=Zt().or(te()),xn=Zt();class F extends Error{_tag="AtlasConfigValidationError"}function vi(t={}){let e=ce(t.cwd??process.cwd()),n=ce(t.home??fi()),s=wn(n,J,at),i=St(s)?s:void 0,r=wi(e,i),o=r?ae(ae(r)):void 0;return{cwd:e,globalPath:i,home:n,projectPath:r,projectRoot:o}}function z(t={}){let e=vi(t),n=bn(e.globalPath,e.home),s=bn(e.projectPath,e.projectRoot),i=X(),r=X();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 At(t,e={}){let n=[...t.config.defaults?.profiles??[],...e.profiles??[]],s=X(),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 f=(Object.hasOwn(t.profileSources,c)?t.profileSources[c]:void 0)??t.projectRoot??t.cwd;for(let d of h.envFiles??[])Object.assign(s,Ri(st(d,f)));Object.assign(s,h.vars??{});for(let[d,b]of Object.entries(h.secrets??{})){let E=Oi(d,b,f,o);if(E!==void 0)s[d]=E}r.add(c),i.push(c)}for(let c of n)a(c,[]);let l=st(t.config.defaults?.exportFile??cn,t.projectRoot??t.cwd);return{env:s,exportFile:l,profiles:i}}function wi(t,e){let n=ce(t),s=pi(n).root;while(!0){let i=wn(n,J,at);if(St(i)&&i!==e)return i;if(n===s)return;n=ae(n)}}function bn(t,e){if(!t||!e)return;let n,s=he(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:xi(n),path:t,rootDir:e}}catch(i){let r=i instanceof F?i.message:"config failed validation";throw new g(`Invalid Atlas config at ${t}: ${r}`)}}function xi(t){let e=_t(t,"config",["$schema","defaults","profiles"]);return ot({$schema:(n)=>Et(n,"$schema"),defaults:(n)=>Ci(n,"defaults"),profiles:(n)=>Si(n,"profiles")})(e)}function Ci(t,e){if(t===void 0)return;let n=_t(t,e,["exportFile","profiles"]);return ot({exportFile:(s)=>Cn(s,`${e}.exportFile`),profiles:(s)=>le(s,`${e}.profiles`)})(n)}function Si(t,e){if(t===void 0)return X();let n=It(t,e),s=X();for(let i of Object.keys(n)){let r=de(e,i);if($i.has(i))throw new F(`${r} must not use a prototype-sensitive profile name`);s[i]=Ai(n[i],r)}return s}function Ai(t,e){let n=_t(t,e,["description","envFiles","extends","secrets","vars"]);return ot({description:(s)=>Et(s,`${e}.description`),envFiles:(s)=>le(s,`${e}.envFiles`),extends:(s)=>le(s,`${e}.extends`),secrets:(s)=>Ii(s,`${e}.secrets`),vars:(s)=>Ei(s,`${e}.vars`)})(n)}function Ei(t,e){if(t===void 0)return;let n=It(t,e),s=X();for(let i of Object.keys(n)){let r=de(e,i);ue(i,r),s[i]=Tt(xn,n[i],r,"must be a string")}return s}function Ii(t,e){if(t===void 0)return;let n=It(t,e),s=X();for(let i of Object.keys(n)){let r=de(e,i);ue(i,r),s[i]=_i(n[i],r)}return s}function _i(t,e){let n=_t(t,e,["env","file","optional","trim"]),s=ot({env:(i)=>Ti(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 F(`${e} must define env or file`);if(s.env!==void 0&&s.file!==void 0)throw new F(`${e} must define only one of env or file`);if(s.env!==void 0&&s.trim!==void 0)throw new F(`${e}.trim only applies to file secrets`);return s}function le(t,e){if(t===void 0)return;if(!Array.isArray(t))throw new F(`${e} must be an array`);return t.map((n,s)=>{let i=`${e}[${s}]`,r=Tt(xn,n,i,"must be a string");return Sn(r,i)})}function Cn(t,e){let n=Et(t,e);return n===void 0?void 0:Sn(n,e)}function Sn(t,e){if(t.trim().length===0)throw new F(`${e} must be a non-empty string`);return t}function Et(t,e){return Tt(bi,t,e,"must be a string")}function Ti(t,e){let n=Et(t,e);if(n===void 0)return;return ue(n,e),n}function vn(t,e){return Tt(yi,t,e,"must be a boolean")}function It(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new F(`${e} must be an object`);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new F(`${e} must be an object`);return t}function _t(t,e,n){let s=It(t,e);for(let i of Object.keys(s))if(!n.includes(i))throw new F(`${e} has unknown key ${JSON.stringify(i)}`);return s}function ue(t,e){if(!Ct.test(t))throw new F(`${e} ${gi}`)}function Tt(t,e,n,s){try{return t(e)}catch{throw new F(`${n} ${s}`)}}function de(t,e){return`${t}[${JSON.stringify(e)}]`}function X(){return Object.create(null)}function Ri(t){if(!St(t))throw new g(`Atlas env file not found: ${t}`,"Create the file or remove it from the profile's envFiles");let e=he(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 Oi(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=st(e.file,n);if(!St(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=he(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 he(t,e){try{return mi(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 Pi}from"crypto";import{link as ki,lstat as Di,open as Mi,rename as Fi,rm as An}from"fs/promises";import{basename as Ni,dirname as ji,join as Li}from"path";var En=384;async function Rt(t,e,n,s="Output file"){let i=await Di(t).catch((a)=>{if(nt(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=Li(ji(t),`.${Ni(t)}.${Pi()}.tmp`),o=null;try{if(o=await Mi(r,"wx",En),await o.chmod(En),await o.writeFile(e,"utf8"),await o.sync(),await o.close(),o=null,n)await Fi(r,t);else await ki(r,t).catch((a)=>{if(nt(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 Gi="Usage: atlas export --profile <name,...>",In=H({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 Ot extends V{name="export";description="Export resolved Atlas env to a dotenv file";args=In;async execute(t){if(K(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");q(t.args.cwd,"cwd","Usage: atlas export --cwd <dir>"),q(t.args.out,"out","Usage: atlas export --out <path>");let e=xt(t.args.profile,Gi),n=t.args.cwd??process.cwd(),s=z({cwd:n}),i=At(s,{profiles:e}),r=hn(i.env);if(t.args.stdout){process.stdout.write(r);return}let o=t.args.out!==void 0?st(t.args.out,s.cwd):i.exportFile;await Vi(Ui(o),{recursive:!0}),await Rt(o,r,t.args.force),A.success(`Wrote ${v.green(o)} using ${i.profiles.length} profile(s)`)}}import{mkdir as Hi}from"fs/promises";import{homedir as Bi}from"os";import{join as _n}from"path";var Tn=H({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 Pt extends V{name="init";description="Create an Atlas config";args=Tn;async execute(t){K(t.args,Tn,"Run 'atlas init --help' for supported options");let e=t.args.global?Bi():process.cwd(),n=_n(e,J,at);await Hi(_n(e,J),{recursive:!0}),await Rt(n,`${JSON.stringify(wt,null,2)}
56
+ `,t.args.force,"Atlas config"),A.success(`Created ${v.green(n)}`)}}var me=H({cwd:{description:"Working directory override",type:"string"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}}),Wi=et({profile:{description:"Profile name",required:!0}});class kt 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=me;async execute(t){kn(t.args.json,()=>{Pn(t.args);let e=z({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=me;positionals=Wi;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=z({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
+ `);return}A.info(`${v.bold(e)}
59
+ ${JSON.stringify(i,null,2)}`)})}}function Pn(t){K(t,me,"Run 'atlas profiles --help' for supported commands"),q(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 Ji}from"fs";import{resolve as Ki}from"path";var Dn=H({cwd:{description:"Working directory override",type:"string"},profile:{alias:"p",description:"Comma-separated profiles to apply",type:"string"}}),qi=127,Xi=126,zi="Put child command flags after --: atlas run -p app -- <cmd> --flags",Yi="Usage: atlas run --profile <name,...> -- <command...>",Qi=et({command:{description:"Command to run",required:!0,variadic:!0}});class Dt extends V{name="run";description="Run a command with resolved Atlas env";args=Dn;positionals=Qi;async execute(t){K(t.args,Dn,zi);let e=t.positionals.command;if(e.length===0)throw new g("Command is required","Usage: atlas run --profile app:web -- <command...>");q(t.args.cwd,"cwd","Usage: atlas run --cwd <dir> -- <command...>");let n=xt(t.args.profile,Yi),s=Ki(t.args.cwd??process.cwd());if(!Ji(s,{throwIfNoEntry:!1})?.isDirectory())throw new g(`Working directory is not a directory: ${s}`,"Usage: atlas run --cwd <dir> -- <command...>");let i=tr(s,n),r=Zi(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 Zi(t,e,n){try{return Bun.spawn(t,{cwd:e,env:n,stderr:"inherit",stdin:"inherit",stdout:"inherit"})}catch(s){if(nt(s,"ENOENT"))throw new g(`Command not found: ${t[0]}`,"Check that it is installed and on PATH",qi);if(nt(s,"EACCES"))throw new g(`Command is not executable: ${t[0]}`,"Check the executable permissions",Xi);throw s}}function tr(t,e){let n=z({cwd:t}),s=At(n,{profiles:e});return{...Object.fromEntries(Object.entries(process.env).filter((r)=>r[1]!==void 0)),...s.env}}class Mn extends Yt{constructor(){super(new ie(nr(er(),J,"cli-state.json"),wt),{bin:an,clearOnStart:!1,description:"Profile-based env composition for apps and environments",name:on,version:rn})}init(){this.registerCommands([new Pt,new kt,new Dt,new Ot])}}var sr=new Mn;sr.run();
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "author": "@ice-chillios",
3
+ "bin": {
4
+ "atlas": "dist/cli.js"
5
+ },
6
+ "description": "Atlas CLI - Profile-based env composition for apps and environments",
7
+ "files": [
8
+ "dist",
9
+ "LICENSE"
10
+ ],
11
+ "keywords": [
12
+ "cli",
13
+ "dotenv",
14
+ "env",
15
+ "config",
16
+ "profiles"
17
+ ],
18
+ "license": "Apache-2.0",
19
+ "main": "dist/cli.js",
20
+ "name": "@r5n/atlas",
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/r5n-labs/clis.git"
28
+ },
29
+ "scripts": {
30
+ "build": "rm -rf dist && bun build.ts",
31
+ "clean": "rm -rf dist node_modules",
32
+ "dev": "bun --bun src/cli.ts",
33
+ "package:dryRun": "bun ../../tools/scripts/publish-package.ts . --dry-run",
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"
37
+ },
38
+ "type": "module",
39
+ "version": "0.6.1"
40
+ }