@r5n/hydra 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,182 +1,115 @@
1
1
  # Hydra
2
2
 
3
- <div align="center">
3
+ Spawn and manage local self-hosted GitHub Actions runners.
4
4
 
5
- [![npm version](https://img.shields.io/npm/v/@r5n/hydra.svg)](https://www.npmjs.com/package/@r5n/hydra)
6
- [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](./LICENSE)
7
- ![Bundle Size](https://img.shields.io/badge/bundle_size-~110KB-green.svg)
5
+ [![npm version](https://img.shields.io/npm/v/@r5n/hydra.svg)](https://www.npmjs.com/package/@r5n/hydra) [![License](https://img.shields.io/npm/l/@r5n/hydra.svg)](./LICENSE)
8
6
 
9
- Manage GitHub Actions self-hosted runners.
7
+ Hydra registers runners against a GitHub repository or organization and runs them as background processes on the machine it runs on. All state lives in a `.hydra/` directory relative to your current working directory, so each directory you run it from is its own isolated runner fleet.
10
8
 
11
- </div>
9
+ ## Requirements
12
10
 
13
- ## Quick Start
11
+ - Bun (the published CLI runs on Bun)
12
+ - `gh` CLI, installed and authenticated (`gh auth login`) — Hydra mints runner registration and removal tokens via `gh api`; it never asks for or stores a token itself. Repository runners need admin access to the repository; organization runners need the `admin:org` scope.
13
+ - `bash`, `curl`, `tar`
14
+ - macOS (Apple Silicon) or Linux (x64). A `win-x64` runner download mapping exists in the code, but registration and startup shell out to `bash config.sh` / `bash run.sh`, so Windows is not actually supported.
15
+
16
+ ## Install
14
17
 
15
18
  ```bash
16
- # Install
17
19
  bun add -g @r5n/hydra
18
-
19
- # Initialize config
20
- hydra init
21
-
22
- # Create runners
23
- hydra create -t $TOKEN -u https://github.com/org/repo -m 3
24
-
25
- # Check status
26
- hydra status -t $TOKEN -u https://github.com/org/repo
27
20
  ```
28
21
 
29
- ## Why?
22
+ ## Quick start
30
23
 
31
- Setting up self-hosted runners manually is tedious. Hydra automates it:
24
+ ```bash
25
+ mkdir ~/runners && cd ~/runners
26
+ hydra init https://github.com/owner/repo -c 2
27
+ hydra create
28
+ hydra start
29
+ hydra status
30
+ ```
32
31
 
33
- - Create multiple runners in parallel
34
- - Reusable profile configs
35
- - Monitor runner status
36
- - Cross-platform (macOS, Linux, Windows)
32
+ Bare `hydra` prints help. `hydra -i` opens an interactive menu that walks through the same commands with prompts. `hydra help <command>` or `hydra <command> --help` shows per-command usage.
37
33
 
38
34
  ## Commands
39
35
 
40
- ### `hydra init`
36
+ ### init
41
37
 
42
- Create a config file with profiles.
38
+ `hydra init [url]` writes a profile to `.hydra/config.json`. The first profile becomes the default. Run with no arguments it opens an interactive form; when any positional or piped input is involved the URL is required.
43
39
 
44
- ```bash
45
- hydra init # Interactive
46
- hydra init --toml # Use TOML format
47
- ```
40
+ - `-p, --profile` profile name (default: `default`)
41
+ - `-n, --name` base name for runners (default: `runner`)
42
+ - `-c, --runners` number of runners (default: 1)
43
+ - `-l, --labels` comma-separated extra labels
44
+ - `-f, --force` overwrite an existing profile
48
45
 
49
- ### `hydra create`
46
+ ### create
50
47
 
51
- Create and register new runners.
48
+ `hydra create [profile] [count]` downloads the latest `actions/runner` release (once per version, shared across runners), then registers runners named `<name>-1`, `<name>-2`, … It tops up to the target count: if the profile already has enough runners recorded, it does nothing. `count` overrides the profile's `numberOfMachines`.
52
49
 
53
- ```bash
54
- # Basic
55
- hydra create -t TOKEN -u REPO_URL
50
+ ### start / stop
56
51
 
57
- # Multiple with labels
58
- hydra create -t TOKEN -u REPO_URL -m 5 -l "docker,gpu"
52
+ `hydra start [profile] [ids...]` launches each runner's `run.sh` as a detached background process and records its pid. `hydra stop [profile] [ids...]` kills them. Omit the ids to target every runner in the profile; omit the profile to use the default. Runners do not survive a reboot — run `hydra start` again.
59
53
 
60
- # Using profile
61
- hydra create -p production -t TOKEN
62
- ```
54
+ ### status
63
55
 
64
- **Options:**
65
- - `-t, --token` — GitHub PAT (required)
66
- - `-u, --url` — Repo/org URL (required)
67
- - `-m, --numberOfMachines` — Number of runners (default: 1)
68
- - `-n, --name` — Runner name prefix
69
- - `-l, --labels` — Comma-separated labels
70
- - `-d, --directory` — Runners directory
71
- - `-o, --os` — OS: osx, linux, windows
72
- - `-p, --profile` — Use config profile
56
+ `hydra status` lists every profile's runners with their state (`running` with pid, `registered`, or `unknown`). State is determined locally from pid liveness and the runner's `.runner` file; no API calls.
73
57
 
74
- ### `hydra run`
58
+ ### logs
75
59
 
76
- Start existing runners.
60
+ `hydra logs [id]` tails the newest job log (`Worker_*.log`) from the runner's `_diag` directory. If no job has run yet it falls back to the runner daemon log with a warning. The id can be omitted when there is exactly one runner.
77
61
 
78
- ```bash
79
- hydra run -t TOKEN -u REPO_URL -m 3
80
- hydra run -p production -t TOKEN
81
- ```
62
+ - `-n, --lines` lines to tail (default: 100)
63
+ - `-r, --runner` show the runner daemon log (`Runner_*.log`) instead of the job log
64
+ - `-l, --list` list available log files with timestamps and sizes
65
+ - `-o, --open` open the log in `$EDITOR` (falls back to `open` on macOS)
82
66
 
83
- ### `hydra remove`
67
+ ### update
84
68
 
85
- Remove runners and unregister from GitHub.
69
+ `hydra update` checks the latest `actions/runner` release, and if it differs from the installed version, swaps the binaries for every runner. Runners that were running are stopped, updated, and restarted.
86
70
 
87
- ```bash
88
- hydra remove -t TOKEN -u REPO_URL -m 3
89
- hydra remove -p production -t TOKEN -f # Force without unregistering
90
- ```
71
+ ### remove
91
72
 
92
- ### `hydra status`
73
+ `hydra remove [profile] [ids...]` stops the runners, deregisters them from GitHub, and deletes their directories.
93
74
 
94
- Check runner status.
75
+ ### profile
95
76
 
96
- ```bash
97
- hydra status -t TOKEN -u REPO_URL
98
- hydra status -p production -t TOKEN --json
99
- ```
77
+ - `hydra profile list` — profiles with URL, OS, and created/running counts
78
+ - `hydra profile default <name>` — set the default profile
79
+ - `hydra profile remove <name>` — remove a profile; if it has runners, stops and deregisters them first (after confirmation)
100
80
 
101
81
  ## Configuration
102
82
 
103
- ### Profiles
104
-
105
- Save common configs in `hydra.json` or `hydra.toml`:
83
+ `.hydra/config.json`, resolved relative to the working directory. Hydra writes it; the `profiles` section is safe to edit by hand:
106
84
 
107
85
  ```json
108
86
  {
87
+ "defaultProfile": "default",
109
88
  "profiles": {
110
- "production": {
111
- "url": "https://github.com/org/repo",
112
- "name": "prod-runner",
113
- "numberOfMachines": 3,
114
- "labels": "linux,docker",
115
- "directory": "/opt/runners",
116
- "os": "linux"
117
- },
118
- "dev": {
119
- "url": "https://github.com/org/dev-repo",
120
- "name": "dev-runner",
89
+ "default": {
90
+ "url": "https://github.com/owner/repo",
91
+ "name": "runner",
121
92
  "numberOfMachines": 2,
122
- "labels": "test"
93
+ "labels": "macOS,ARM64",
94
+ "directory": ".hydra/runners",
95
+ "os": "osx",
96
+ "provider": "github",
97
+ "overwrite": false,
98
+ "run": false
123
99
  }
124
100
  },
125
- "defaultProfile": "production"
101
+ "runners": []
126
102
  }
127
103
  ```
128
104
 
129
- Then use with `-p`:
105
+ `os` is one of `osx` | `linux` | `windows` (auto-detected by `init`). An optional `runnerGroup` string is passed through to `config.sh --runnergroup`; runner groups only apply to organization runners. The `runners` array is Hydra's record of what it created — leave it alone.
130
106
 
131
- ```bash
132
- hydra create -p production -t $TOKEN
133
- hydra status -p dev -t $TOKEN
134
- ```
135
-
136
- ### Environment Variables
137
-
138
- - `GITHUB_PERSONAL_ACCESS_TOKEN` — Default token
139
- - `HYDRA_CONFIG` — Config file path
140
-
141
- ## Token Permissions
142
-
143
- - **Repository runners:** `repo` scope
144
- - **Organization runners:** `admin:org` scope
145
-
146
- Never commit tokens. Use environment variables or pass via `-t`.
147
-
148
- ## Examples
149
-
150
- ```bash
151
- # Development setup
152
- hydra create -p dev -t $TOKEN -m 2
107
+ The `url` is either a repository URL (`https://github.com/owner/repo`) or an organization URL (`https://github.com/org`). Repository URLs mint tokens from the repository endpoint (requires repo admin); organization URLs use the organization endpoint (requires the `admin:org` scope).
153
108
 
154
- # Production with specific labels
155
- hydra create -p prod -t $TOKEN -l "deploy,production"
109
+ ## How it works
156
110
 
157
- # Monitor all runners
158
- hydra status -p prod -t $TOKEN --json | jq '.[] | select(.status == "offline")'
159
-
160
- # Cleanup
161
- hydra remove -p dev -t $TOKEN
162
- ```
163
-
164
- ## Troubleshooting
165
-
166
- **Invalid token error:**
167
- - Check token has `repo` or `admin:org` scope
168
- - Verify token isn't expired
169
-
170
- **Runner config failed:**
171
- - Check network connectivity
172
- - Verify GitHub URL format
173
- - Ensure write permissions in runner directory
174
-
175
- **Debug mode:**
176
- ```bash
177
- DEBUG=* hydra create -t TOKEN -u URL
178
- ```
111
+ Runner binaries are downloaded once per version into `.hydra/shared/github/<version>`. Each runner directory under `.hydra/runners/<id>` gets hardlinks for `bin`, a symlink for `externals`, and its own copies of the shell scripts, so ten runners cost roughly one copy of the runner distribution on disk. Start/stop is plain process management: a detached `bash run.sh` plus a pid file per runner.
179
112
 
180
113
  ## License
181
114
 
182
- Apache 2.0 — see [LICENSE](./LICENSE)
115
+ Apache-2.0 — see [LICENSE](./LICENSE)
package/dist/cli.js CHANGED
@@ -1,98 +1,98 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var _o=Object.create;var{getPrototypeOf:To,defineProperty:zn,getOwnPropertyNames:ri}=Object;var ni=Object.prototype.hasOwnProperty;function oi(r){return this[r]}var ii,ei,Wn=(r,n,o)=>{var i=r!=null&&typeof r==="object";if(i){var e=n?ii??=new WeakMap:ei??=new WeakMap,t=e.get(r);if(t)return t}o=r!=null?_o(To(r)):{};let a=n||!r||!r.__esModule?zn(o,"default",{value:r,enumerable:!0}):o;for(let s of ri(r))if(!ni.call(a,s))zn(a,s,{get:oi.bind(r,s),enumerable:!0});if(i)e.set(r,a);return a};var ti=(r,n)=>()=>(n||r((n={exports:{}}).exports,n),n.exports);var sn=ti((tt,ro)=>{var an={to(r,n){if(!n)return`\x1B[${r+1}G`;return`\x1B[${n+1};${r+1}H`},move(r,n){let o="";if(r<0)o+=`\x1B[${-r}D`;else if(r>0)o+=`\x1B[${r}C`;if(n<0)o+=`\x1B[${-n}A`;else if(n>0)o+=`\x1B[${n}B`;return o},up:(r=1)=>`\x1B[${r}A`,down:(r=1)=>`\x1B[${r}B`,forward:(r=1)=>`\x1B[${r}C`,backward:(r=1)=>`\x1B[${r}D`,nextLine:(r=1)=>"\x1B[E".repeat(r),prevLine:(r=1)=>"\x1B[F".repeat(r),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},wi={up:(r=1)=>"\x1B[S".repeat(r),down:(r=1)=>"\x1B[T".repeat(r)},$i={screen:"\x1B[2J",up:(r=1)=>"\x1B[1J".repeat(r),down:(r=1)=>"\x1B[J".repeat(r),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(r){let n="";for(let o=0;o<r;o++)n+=this.line+(o<r-1?an.up():"");if(r)n+=an.left;return n}};ro.exports={cursor:an,scroll:wi,erase:$i,beep:"\x07"}});class X extends Error{constructor(r="Operation cancelled"){super(r)}}class v extends Error{hint;constructor(r,n){super(r);this.hint=n}}import{styleText as jr}from"util";import{stdout as un,stdin as eo}from"process";import*as or from"readline";import Pi from"readline";var Jn=(()=>{let r=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let o=0;r.lastIndex=0;while(r.test(n))o+=1;return n.length-o}})(),An=(r)=>{return r===12288||r>=65281&&r<=65376||r>=65504&&r<=65510},Kn=(r)=>{return r===8987||r===9001||r>=12272&&r<=12287||r>=12289&&r<=12350||r>=12441&&r<=12543||r>=12549&&r<=12591||r>=12593&&r<=12686||r>=12688&&r<=12771||r>=12783&&r<=12830||r>=12832&&r<=12871||r>=12880&&r<=19903||r>=65040&&r<=65049||r>=65072&&r<=65106||r>=65108&&r<=65126||r>=65128&&r<=65131||r>=127488&&r<=127490||r>=127504&&r<=127547||r>=127552&&r<=127560||r>=131072&&r<=196605||r>=196608&&r<=262141};var ai=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,si=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Yn=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ci=/\t{1,1000}/y,Zn=/[\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,fi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,mi=/\p{M}+/gu,ui={limit:1/0,ellipsis:""},xn=(r,n={},o={})=>{let i=n.limit??1/0,e=n.ellipsis??"",t=n?.ellipsisWidth??(e?xn(e,ui,o).width:0),a=0,s=o.controlWidth??0,c=o.tabWidth??8,f=o.emojiWidth??2,d=2,g=o.regularWidth??1,u=o.wideWidth??2,h=[[fi,g],[ai,0],[si,s],[ci,c],[Zn,f],[Yn,u]],l=0,b=0,k=r.length,R=0,C=!1,N=k,j=Math.max(0,i-t),F=0,E=0,M=0,L=0;r:while(!0){if(E>F||b>=k&&b>l){let H=r.slice(F,E)||r.slice(l,b);R=0;for(let V of H.replaceAll(mi,"")){let A=V.codePointAt(0)||0;if(An(A))L=2;else if(Kn(A))L=u;else L=g;if(M+L>j)N=Math.min(N,Math.max(F,l)+R);if(M+L>i){C=!0;break r}R+=V.length,M+=L}F=E=0}if(b>=k)break r;for(let H=0,V=h.length;H<V;H++){let[A,kr]=h[H];if(A.lastIndex=b,A.test(r)){if(R=A===Yn?Jn(r.slice(b,A.lastIndex)):A===Zn?1:A.lastIndex-b,L=R*kr,M+L>j)N=Math.min(N,b+Math.floor((j-M)/kr));if(M+L>i){C=!0;break r}M+=L,F=l,E=b,b=l=A.lastIndex;continue r}}b+=1}return{width:C?j:M,index:C?N:k,truncated:C,ellipsed:C&&i>=t}},Qn=xn;var pi={limit:1/0,ellipsis:"",ellipsisWidth:0},li=(r,n={})=>{return Qn(r,pi,n).width},K=li;var Lr="\x1B",Bn="\x9B",di=39,en="\x07",_n="[",gi="]",Tn="m",tn=`${gi}8;;`,Xn=new RegExp(`(?:\\${_n}(?<code>\\d+)m|\\${tn}(?<uri>.*)${en})`,"y"),Vn=(r)=>{if(r>=30&&r<=37)return 39;if(r>=90&&r<=97)return 39;if(r>=40&&r<=47)return 49;if(r>=100&&r<=107)return 49;if(r===1||r===2)return 22;if(r===3)return 23;if(r===4)return 24;if(r===7)return 27;if(r===8)return 28;if(r===9)return 29;if(r===0)return 0;return},On=(r)=>`${Lr}${_n}${r}${Tn}`,Sn=(r)=>`${Lr}${tn}${r}${en}`,on=(r,n,o)=>{let i=n[Symbol.iterator](),e=!1,t=!1,a=r.at(-1),s=a===void 0?0:K(a),c=i.next(),f=i.next(),d=0;while(!c.done){let g=c.value,u=K(g);if(s+u<=o)r[r.length-1]+=g;else r.push(g),s=0;if(g===Lr||g===Bn)e=!0,t=n.startsWith(tn,d+1);if(e){if(t){if(g===en)e=!1,t=!1}else if(g===Tn)e=!1}else if(s+=u,s===o&&!f.done)r.push(""),s=0;c=f,f=i.next(),d+=g.length}if(a=r.at(-1),!s&&a!==void 0&&a.length&&r.length>1)r[r.length-2]+=r.pop()},hi=(r)=>{let n=r.split(" "),o=n.length;while(o){if(K(n[o-1]))break;o--}if(o===n.length)return r;return n.slice(0,o).join(" ")+n.slice(o).join("")},bi=(r,n,o={})=>{if(o.trim!==!1&&r.trim()==="")return"";let i="",e,t,a=r.split(" "),s=[""],c=0;for(let g=0;g<a.length;g++){let u=a[g];if(o.trim!==!1){let l=s.at(-1)??"",b=l.trimStart();if(l.length!==b.length)s[s.length-1]=b,c=K(b)}if(g!==0){if(c>=n&&(o.wordWrap===!1||o.trim===!1))s.push(""),c=0;if(c||o.trim===!1)s[s.length-1]+=" ",c++}let h=K(u);if(o.hard&&h>n){let l=n-c,b=1+Math.floor((h-l-1)/n);if(Math.floor((h-1)/n)<b)s.push("");on(s,u,n),c=K(s.at(-1)??"");continue}if(c+h>n&&c&&h){if(o.wordWrap===!1&&c<n){on(s,u,n),c=K(s.at(-1)??"");continue}s.push(""),c=0}if(c+h>n&&o.wordWrap===!1){on(s,u,n),c=K(s.at(-1)??"");continue}s[s.length-1]+=u,c+=h}if(o.trim!==!1)s=s.map((g)=>hi(g));let f=s.join(`
4
- `),d=!1;for(let g=0;g<f.length;g++){let u=f[g];if(i+=u,!d){if(d=u>="\uD800"&&u<="\uDBFF",d)continue}else d=!1;if(u===Lr||u===Bn){Xn.lastIndex=g+1;let l=Xn.exec(f)?.groups;if(l?.code!==void 0){let b=Number.parseFloat(l.code);e=b===di?void 0:b}else if(l?.uri!==void 0)t=l.uri.length===0?void 0:l.uri}if(f[g+1]===`
5
- `){if(t)i+=Sn("");let h=e?Vn(e):void 0;if(e&&h)i+=On(h)}else if(u===`
6
- `){if(e&&Vn(e))i+=On(e);if(t)i+=Sn(t)}}return i},vi=/\r?\n/;function O(r,n,o){return String(r).normalize().split(vi).map((i)=>bi(i,n,o)).join(`
7
- `)}var W=Wn(sn(),1);import{ReadStream as no}from"tty";function _(r,n,o){if(!o.some((a)=>!a.disabled))return r;let i=r+n,e=Math.max(o.length-1,0),t=i<0?e:i>e?0:i;return o[t]?.disabled?_(t,n<0?-1:1,o):t}function Ir(r,n,o,i){let e=i.split(`
8
- `),t=0,a=r;for(let c of e){if(a<=c.length)break;a-=c.length+1,t++}for(t=Math.max(0,Math.min(e.length-1,t+o)),a=Math.min(a,e[t].length)+n;a<0&&t>0;)t--,a+=e[t].length+1;for(;a>e[t].length&&t<e.length-1;)a-=e[t].length+1,t++;a=Math.max(0,Math.min(e[t].length,a));let s=0;for(let c=0;c<t;c++)s+=e[c].length+1;return s+a}var Ci=["up","down","left","right","space","enter","cancel"],Fi=["January","February","March","April","May","June","July","August","September","October","November","December"],q={actions:new Set(Ci),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:[...Fi],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(r,n)=>`There are only ${r} days in ${n}`,afterMin:(r)=>`Date must be on or after ${r.toISOString().slice(0,10)}`,beforeMax:(r)=>`Date must be on or before ${r.toISOString().slice(0,10)}`}}};function pn(r,n){if(typeof r=="string")return q.aliases.get(r)===n;for(let o of r)if(o!==void 0&&pn(o,n))return!0;return!1}function ki(r,n){if(r===n)return;let o=r.split(`
3
+ var ni=Object.create;var{getPrototypeOf:oi,defineProperty:An,getOwnPropertyNames:ii}=Object;var ei=Object.prototype.hasOwnProperty;function ti(r){return this[r]}var ai,si,Jn=(r,n,o)=>{var i=r!=null&&typeof r==="object";if(i){var e=n?ai??=new WeakMap:si??=new WeakMap,t=e.get(r);if(t)return t}o=r!=null?ni(oi(r)):{};let a=n||!r||!r.__esModule?An(o,"default",{value:r,enumerable:!0}):o;for(let s of ii(r))if(!ei.call(a,s))An(a,s,{get:ti.bind(r,s),enumerable:!0});if(i)e.set(r,a);return a};var ci=(r,n)=>()=>(n||r((n={exports:{}}).exports,n),n.exports);var fn=ci((ft,oo)=>{var cn={to(r,n){if(!n)return`\x1B[${r+1}G`;return`\x1B[${n+1};${r+1}H`},move(r,n){let o="";if(r<0)o+=`\x1B[${-r}D`;else if(r>0)o+=`\x1B[${r}C`;if(n<0)o+=`\x1B[${-n}A`;else if(n>0)o+=`\x1B[${n}B`;return o},up:(r=1)=>`\x1B[${r}A`,down:(r=1)=>`\x1B[${r}B`,forward:(r=1)=>`\x1B[${r}C`,backward:(r=1)=>`\x1B[${r}D`,nextLine:(r=1)=>"\x1B[E".repeat(r),prevLine:(r=1)=>"\x1B[F".repeat(r),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ci={up:(r=1)=>"\x1B[S".repeat(r),down:(r=1)=>"\x1B[T".repeat(r)},Fi={screen:"\x1B[2J",up:(r=1)=>"\x1B[1J".repeat(r),down:(r=1)=>"\x1B[J".repeat(r),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(r){let n="";for(let o=0;o<r;o++)n+=this.line+(o<r-1?cn.up():"");if(r)n+=cn.left;return n}};oo.exports={cursor:cn,scroll:Ci,erase:Fi,beep:"\x07"}});class X extends Error{constructor(r="Operation cancelled"){super(r)}}class v extends Error{hint;constructor(r,n){super(r);this.hint=n}}import{styleText as jr}from"util";import{stdout as dn,stdin as ao}from"process";import*as or from"readline";import ki from"readline";var xn=(()=>{let r=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let o=0;r.lastIndex=0;while(r.test(n))o+=1;return n.length-o}})(),Kn=(r)=>{return r===12288||r>=65281&&r<=65376||r>=65504&&r<=65510},Yn=(r)=>{return r===8987||r===9001||r>=12272&&r<=12287||r>=12289&&r<=12350||r>=12441&&r<=12543||r>=12549&&r<=12591||r>=12593&&r<=12686||r>=12688&&r<=12771||r>=12783&&r<=12830||r>=12832&&r<=12871||r>=12880&&r<=19903||r>=65040&&r<=65049||r>=65072&&r<=65106||r>=65108&&r<=65126||r>=65128&&r<=65131||r>=127488&&r<=127490||r>=127504&&r<=127547||r>=127552&&r<=127560||r>=131072&&r<=196605||r>=196608&&r<=262141};var fi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,mi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Zn=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ui=/\t{1,1000}/y,Qn=/[\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,pi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,di=/\p{M}+/gu,li={limit:1/0,ellipsis:""},Xn=(r,n={},o={})=>{let i=n.limit??1/0,e=n.ellipsis??"",t=n?.ellipsisWidth??(e?Xn(e,li,o).width:0),a=0,s=o.controlWidth??0,c=o.tabWidth??8,f=o.emojiWidth??2,l=2,g=o.regularWidth??1,u=o.wideWidth??2,h=[[pi,g],[fi,0],[mi,s],[ui,c],[Qn,f],[Zn,u]],d=0,b=0,k=r.length,D=0,C=!1,G=k,H=Math.max(0,i-t),F=0,U=0,j=0,I=0;r:while(!0){if(U>F||b>=k&&b>d){let M=r.slice(F,U)||r.slice(d,b);D=0;for(let V of M.replaceAll(di,"")){let J=V.codePointAt(0)||0;if(Kn(J))I=2;else if(Yn(J))I=u;else I=g;if(j+I>H)G=Math.min(G,Math.max(F,d)+D);if(j+I>i){C=!0;break r}D+=V.length,j+=I}F=U=0}if(b>=k)break r;for(let M=0,V=h.length;M<V;M++){let[J,yr]=h[M];if(J.lastIndex=b,J.test(r)){if(D=J===Zn?xn(r.slice(b,J.lastIndex)):J===Qn?1:J.lastIndex-b,I=D*yr,j+I>H)G=Math.min(G,b+Math.floor((H-j)/yr));if(j+I>i){C=!0;break r}j+=I,F=d,U=b,b=d=J.lastIndex;continue r}}b+=1}return{width:C?H:j,index:C?G:k,truncated:C,ellipsed:C&&i>=t}},Vn=Xn;var gi={limit:1/0,ellipsis:"",ellipsisWidth:0},hi=(r,n={})=>{return Vn(r,gi,n).width},x=hi;var Lr="\x1B",Tn="\x9B",bi=39,an="\x07",ro="[",vi="]",no="m",sn=`${vi}8;;`,On=new RegExp(`(?:\\${ro}(?<code>\\d+)m|\\${sn}(?<uri>.*)${an})`,"y"),Sn=(r)=>{if(r>=30&&r<=37)return 39;if(r>=90&&r<=97)return 39;if(r>=40&&r<=47)return 49;if(r>=100&&r<=107)return 49;if(r===1||r===2)return 22;if(r===3)return 23;if(r===4)return 24;if(r===7)return 27;if(r===8)return 28;if(r===9)return 29;if(r===0)return 0;return},Bn=(r)=>`${Lr}${ro}${r}${no}`,_n=(r)=>`${Lr}${sn}${r}${an}`,tn=(r,n,o)=>{let i=n[Symbol.iterator](),e=!1,t=!1,a=r.at(-1),s=a===void 0?0:x(a),c=i.next(),f=i.next(),l=0;while(!c.done){let g=c.value,u=x(g);if(s+u<=o)r[r.length-1]+=g;else r.push(g),s=0;if(g===Lr||g===Tn)e=!0,t=n.startsWith(sn,l+1);if(e){if(t){if(g===an)e=!1,t=!1}else if(g===no)e=!1}else if(s+=u,s===o&&!f.done)r.push(""),s=0;c=f,f=i.next(),l+=g.length}if(a=r.at(-1),!s&&a!==void 0&&a.length&&r.length>1)r[r.length-2]+=r.pop()},wi=(r)=>{let n=r.split(" "),o=n.length;while(o){if(x(n[o-1]))break;o--}if(o===n.length)return r;return n.slice(0,o).join(" ")+n.slice(o).join("")},$i=(r,n,o={})=>{if(o.trim!==!1&&r.trim()==="")return"";let i="",e,t,a=r.split(" "),s=[""],c=0;for(let g=0;g<a.length;g++){let u=a[g];if(o.trim!==!1){let d=s.at(-1)??"",b=d.trimStart();if(d.length!==b.length)s[s.length-1]=b,c=x(b)}if(g!==0){if(c>=n&&(o.wordWrap===!1||o.trim===!1))s.push(""),c=0;if(c||o.trim===!1)s[s.length-1]+=" ",c++}let h=x(u);if(o.hard&&h>n){let d=n-c,b=1+Math.floor((h-d-1)/n);if(Math.floor((h-1)/n)<b)s.push("");tn(s,u,n),c=x(s.at(-1)??"");continue}if(c+h>n&&c&&h){if(o.wordWrap===!1&&c<n){tn(s,u,n),c=x(s.at(-1)??"");continue}s.push(""),c=0}if(c+h>n&&o.wordWrap===!1){tn(s,u,n),c=x(s.at(-1)??"");continue}s[s.length-1]+=u,c+=h}if(o.trim!==!1)s=s.map((g)=>wi(g));let f=s.join(`
4
+ `),l=!1;for(let g=0;g<f.length;g++){let u=f[g];if(i+=u,!l){if(l=u>="\uD800"&&u<="\uDBFF",l)continue}else l=!1;if(u===Lr||u===Tn){On.lastIndex=g+1;let d=On.exec(f)?.groups;if(d?.code!==void 0){let b=Number.parseFloat(d.code);e=b===bi?void 0:b}else if(d?.uri!==void 0)t=d.uri.length===0?void 0:d.uri}if(f[g+1]===`
5
+ `){if(t)i+=_n("");let h=e?Sn(e):void 0;if(e&&h)i+=Bn(h)}else if(u===`
6
+ `){if(e&&Sn(e))i+=Bn(e);if(t)i+=_n(t)}}return i},Pi=/\r?\n/;function O(r,n,o){return String(r).normalize().split(Pi).map((i)=>$i(i,n,o)).join(`
7
+ `)}var W=Jn(fn(),1);import{ReadStream as io}from"tty";function _(r,n,o){if(!o.some((a)=>!a.disabled))return r;let i=r+n,e=Math.max(o.length-1,0),t=i<0?e:i>e?0:i;return o[t]?.disabled?_(t,n<0?-1:1,o):t}function Rr(r,n,o,i){let e=i.split(`
8
+ `),t=0,a=r;for(let c of e){if(a<=c.length)break;a-=c.length+1,t++}for(t=Math.max(0,Math.min(e.length-1,t+o)),a=Math.min(a,e[t].length)+n;a<0&&t>0;)t--,a+=e[t].length+1;for(;a>e[t].length&&t<e.length-1;)a-=e[t].length+1,t++;a=Math.max(0,Math.min(e[t].length,a));let s=0;for(let c=0;c<t;c++)s+=e[c].length+1;return s+a}var yi=["up","down","left","right","space","enter","cancel"],Ii=["January","February","March","April","May","June","July","August","September","October","November","December"],N={actions:new Set(yi),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:[...Ii],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(r,n)=>`There are only ${r} days in ${n}`,afterMin:(r)=>`Date must be on or after ${r.toISOString().slice(0,10)}`,beforeMax:(r)=>`Date must be on or before ${r.toISOString().slice(0,10)}`}}};function ln(r,n){if(typeof r=="string")return N.aliases.get(r)===n;for(let o of r)if(o!==void 0&&ln(o,n))return!0;return!1}function Li(r,n){if(r===n)return;let o=r.split(`
9
9
  `),i=n.split(`
10
- `),e=Math.max(o.length,i.length),t=[];for(let a=0;a<e;a++)o[a]!==i[a]&&t.push(a);return{lines:t,numLinesBefore:o.length,numLinesAfter:i.length,numLines:e}}var yi=globalThis.process.platform.startsWith("win"),fn=Symbol("clack:cancel");function lr(r){return r===fn}function Dr(r,n){let o=r;o.isTTY&&o.setRawMode(n)}function to({input:r=eo,output:n=un,overwrite:o=!0,hideCursor:i=!0}={}){let e=or.createInterface({input:r,output:n,prompt:"",tabSize:1});or.emitKeypressEvents(r,e),r instanceof no&&r.isTTY&&r.setRawMode(!0);let t=(a,{name:s,sequence:c})=>{let f=String(a);if(pn([f,s,c],"cancel")){i&&n.write(W.cursor.show),process.exit(0);return}if(!o)return;or.moveCursor(n,s==="return"?0:-1,s==="return"?-1:0,()=>{or.clearLine(n,1,()=>{r.once("keypress",t)})})};return i&&n.write(W.cursor.hide),r.once("keypress",t),()=>{r.off("keypress",t),i&&n.write(W.cursor.show),r instanceof no&&r.isTTY&&!yi&&r.setRawMode(!1),e.terminal=!1,e.close()}}var dr=(r)=>("columns"in r)&&typeof r.columns=="number"?r.columns:80,ln=(r)=>("rows"in r)&&typeof r.rows=="number"?r.rows:20;function ir(r,n,o,i=o,e=o,t){let a=dr(r??un);return O(n,a-o.length,{hard:!0,trim:!1}).split(`
11
- `).map((s,c,f)=>{let d=t?t(s,c):s;return c===0?`${i}${d}`:c===f.length-1?`${e}${d}`:`${o}${d}`}).join(`
12
- `)}function ao(r,n){if("~standard"in r){let o=r["~standard"].validate(n);if(o instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return o.issues?.at(0)?.message}return r(n)}class T{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(r,n=!0){let{input:o=eo,output:i=un,render:e,signal:t,...a}=r;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=e.bind(this),this._track=n,this._abortSignal=t,this.input=o,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(r,n){let o=this._subscribers.get(r)??[];o.push(n),this._subscribers.set(r,o)}on(r,n){this.setSubscriber(r,{cb:n})}once(r,n){this.setSubscriber(r,{cb:n,once:!0})}emit(r,...n){let o=this._subscribers.get(r)??[],i=[];for(let e of o)e.cb(...n),e.once&&i.push(()=>o.splice(o.indexOf(e),1));for(let e of i)e()}prompt(){return new Promise((r)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),r(fn);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Pi.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),Dr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Dr(this.input,!1),r(this.value)}),this.once("cancel",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Dr(this.input,!1),r(fn)})})}_isActionKey(r,n){return r==="\t"}_shouldSubmit(r,n){return!0}_setValue(r){this.value=r,this.emit("value",this.value)}_setUserInput(r,n){this.userInput=r??"",this.emit("userInput",this.userInput),n&&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(r,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(r,n)&&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"),n?.name&&(!this._track&&q.aliases.has(n.name)&&this.emit("cursor",q.aliases.get(n.name)),q.actions.has(n.name)&&this.emit("cursor",n.name)),r&&(r.toLowerCase()==="y"||r.toLowerCase()==="n")&&this.emit("confirm",r.toLowerCase()==="y"),this.emit("key",r,n),n?.name==="return"&&this._shouldSubmit(r,n)){if(this.opts.validate){let o=ao(this.opts.validate,this.value);o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}pn([r,n?.name,n?.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(`
10
+ `),e=Math.max(o.length,i.length),t=[];for(let a=0;a<e;a++)o[a]!==i[a]&&t.push(a);return{lines:t,numLinesBefore:o.length,numLinesAfter:i.length,numLines:e}}var Ri=globalThis.process.platform.startsWith("win"),un=Symbol("clack:cancel");function lr(r){return r===un}function Dr(r,n){let o=r;o.isTTY&&o.setRawMode(n)}function so({input:r=ao,output:n=dn,overwrite:o=!0,hideCursor:i=!0}={}){let e=or.createInterface({input:r,output:n,prompt:"",tabSize:1});or.emitKeypressEvents(r,e),r instanceof io&&r.isTTY&&r.setRawMode(!0);let t=(a,{name:s,sequence:c})=>{let f=String(a);if(ln([f,s,c],"cancel")){i&&n.write(W.cursor.show),process.exit(0);return}if(!o)return;or.moveCursor(n,s==="return"?0:-1,s==="return"?-1:0,()=>{or.clearLine(n,1,()=>{r.once("keypress",t)})})};return i&&n.write(W.cursor.hide),r.once("keypress",t),()=>{r.off("keypress",t),i&&n.write(W.cursor.show),r instanceof io&&r.isTTY&&!Ri&&r.setRawMode(!1),e.terminal=!1,e.close()}}var gr=(r)=>("columns"in r)&&typeof r.columns=="number"?r.columns:80,gn=(r)=>("rows"in r)&&typeof r.rows=="number"?r.rows:20;function ir(r,n,o,i=o,e=o,t){let a=gr(r??dn);return O(n,a-o.length,{hard:!0,trim:!1}).split(`
11
+ `).map((s,c,f)=>{let l=t?t(s,c):s;return c===0?`${i}${l}`:c===f.length-1?`${e}${l}`:`${o}${l}`}).join(`
12
+ `)}function co(r,n){if("~standard"in r){let o=r["~standard"].validate(n);if(o instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return o.issues?.at(0)?.message}return r(n)}class T{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(r,n=!0){let{input:o=ao,output:i=dn,render:e,signal:t,...a}=r;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=e.bind(this),this._track=n,this._abortSignal=t,this.input=o,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(r,n){let o=this._subscribers.get(r)??[];o.push(n),this._subscribers.set(r,o)}on(r,n){this.setSubscriber(r,{cb:n})}once(r,n){this.setSubscriber(r,{cb:n,once:!0})}emit(r,...n){let o=this._subscribers.get(r)??[],i=[];for(let e of o)e.cb(...n),e.once&&i.push(()=>o.splice(o.indexOf(e),1));for(let e of i)e()}prompt(){return new Promise((r)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),r(un);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ki.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),Dr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Dr(this.input,!1),r(this.value)}),this.once("cancel",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Dr(this.input,!1),r(un)})})}_isActionKey(r,n){return r==="\t"}_shouldSubmit(r,n){return!0}_setValue(r){this.value=r,this.emit("value",this.value)}_setUserInput(r,n){this.userInput=r??"",this.emit("userInput",this.userInput),n&&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(r,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(r,n)&&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"),n?.name&&(!this._track&&N.aliases.has(n.name)&&this.emit("cursor",N.aliases.get(n.name)),N.actions.has(n.name)&&this.emit("cursor",n.name)),r&&(r.toLowerCase()==="y"||r.toLowerCase()==="n")&&this.emit("confirm",r.toLowerCase()==="y"),this.emit("key",r,n),n?.name==="return"&&this._shouldSubmit(r,n)){if(this.opts.validate){let o=co(this.opts.validate,this.value);o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}ln([r,n?.name,n?.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(`
13
13
  `),Dr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let r=O(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
14
- `).length-1;this.output.write(W.cursor.move(-999,r*-1))}render(){let r=O(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(r!==this._prevFrame){if(this.state==="initial")this.output.write(W.cursor.hide);else{let n=ki(this._prevFrame,r),o=ln(this.output);if(this.restoreCursor(),n){let i=Math.max(0,n.numLinesAfter-o),e=Math.max(0,n.numLinesBefore-o),t=n.lines.find((a)=>a>=i);if(t===void 0){this._prevFrame=r;return}if(n.lines.length===1){this.output.write(W.cursor.move(0,t-e)),this.output.write(W.erase.lines(1));let a=r.split(`
14
+ `).length-1;this.output.write(W.cursor.move(-999,r*-1))}render(){let r=O(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(r!==this._prevFrame){if(this.state==="initial")this.output.write(W.cursor.hide);else{let n=Li(this._prevFrame,r),o=gn(this.output);if(this.restoreCursor(),n){let i=Math.max(0,n.numLinesAfter-o),e=Math.max(0,n.numLinesBefore-o),t=n.lines.find((a)=>a>=i);if(t===void 0){this._prevFrame=r;return}if(n.lines.length===1){this.output.write(W.cursor.move(0,t-e)),this.output.write(W.erase.lines(1));let a=r.split(`
15
15
  `);this.output.write(a[t]),this._prevFrame=r,this.output.write(W.cursor.move(0,a.length-t-1));return}else if(n.lines.length>1){if(i<e)t=i;else{let s=t-e;s>0&&this.output.write(W.cursor.move(0,s))}this.output.write(W.erase.down());let a=r.split(`
16
16
  `).slice(t);this.output.write(a.join(`
17
- `)),this._prevFrame=r;return}}this.output.write(W.erase.down())}this.output.write(r),this.state==="initial"&&(this.state="active"),this._prevFrame=r}}}function Li(r,n){if(r===void 0||n.length===0)return 0;let o=n.findIndex((i)=>i.value===r);return o!==-1?o:0}function Ii(r,n){return(n.label??String(n.value)).toLowerCase().includes(r.toLowerCase())}function Di(r,n){if(n)return r?n:n[0]}var Ri=class extends T{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#e="";#r;#t;#s;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return jr(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let n=this.userInput.slice(0,this.cursor),o=this.userInput.slice(this.cursor,this.cursor+1),i=this.userInput.slice(this.cursor+1);return`${n}${jr("inverse",o)}${i}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(n){super(n),this.#t=n.options,this.#s=n.placeholder;let o=this.options;this.filteredOptions=[...o],this.multiple=n.multiple===!0,this.#r=typeof n.options=="function"?n.filter:n.filter??Ii;let i;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?i=n.initialValue:i=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0]?.value]),i)for(let e of i){let t=o.findIndex((a)=>a.value===e);t!==-1&&(this.toggleSelected(e),this.#n=t)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(e,t)=>this.#o(e,t)),this.on("userInput",(e)=>this.#i(e))}_isActionKey(n,o){return n==="\t"||this.multiple&&this.isNavigating&&o.name==="space"&&n!==void 0&&n!==""}#o(n,o){let i=o.name==="up",e=o.name==="down",t=o.name==="return",a=this.userInput===""||this.userInput==="\t",s=this.#s,c=this.options,f=s!==void 0&&s!==""&&c.some((d)=>!d.disabled&&(this.#r?this.#r(s,d):!0));if(o.name==="tab"&&a&&f){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}i||e?(this.#n=_(this.#n,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):t?this.value=Di(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(o.name==="tab"||this.isNavigating&&o.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((o)=>o!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#i(n){if(n!==this.#e){this.#e=n;let o=this.options;n&&this.#r?this.filteredOptions=o.filter((t)=>this.#r?.(n,t)):this.filteredOptions=[...o];let i=Li(this.focusedValue,this.filteredOptions);this.#n=_(i,0,this.filteredOptions);let e=this.filteredOptions[this.#n];e&&!e.disabled?this.focusedValue=e.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class dn extends T{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(r){super(r,!1),this.value=!!r.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(W.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var ji={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function oo(r){return[...r].map((n)=>ji[n])}function Mi(r){let n=new Intl.DateTimeFormat(r,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),o=[],i="/";for(let e of n)e.type==="literal"?i=e.value.trim()||e.value:(e.type==="year"||e.type==="month"||e.type==="day")&&o.push({type:e.type,len:e.type==="year"?4:2});return{segments:o,separator:i}}function cn(r){return Number.parseInt((r||"0").replace(/_/g,"0"),10)||0}function Rr(r){return{year:cn(r.year),month:cn(r.month),day:cn(r.day)}}function mn(r,n){return new Date(r||2001,n||1,0).getDate()}function so(r){let{year:n,month:o,day:i}=Rr(r);if(!n||n<0||n>9999||!o||o<1||o>12||!i||i<1)return;let e=new Date(Date.UTC(n,o-1,i));if(!(e.getUTCFullYear()!==n||e.getUTCMonth()!==o-1||e.getUTCDate()!==i))return{year:n,month:o,day:i}}function io(r){let n=so(r);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function Ui(r,n,o,i){let e=o?{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()}:null,t=i?{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}:null;return r==="year"?{min:e?.year??1,max:t?.year??9999}:r==="month"?{min:e&&n.year===e.year?e.month:1,max:t&&n.year===t.year?t.month:12}:{min:e&&n.year===e.year&&n.month===e.month?e.day:1,max:t&&n.year===t.year&&n.month===t.month?t.day:mn(n.year,n.month)}}class co extends T{#n;#e;#r;#t;#s;#o={segmentIndex:0,positionInSegment:0};#i=!0;#a=null;inlineError="";get segmentCursor(){return{...this.#o}}get segmentValues(){return{...this.#r}}get segments(){return this.#n}get separator(){return this.#e}get formattedValue(){return this.#u(this.#r)}#u(r){return this.#n.map((n)=>r[n.type]).join(this.#e)}#c(){this._setUserInput(this.#u(this.#r)),this._setValue(io(this.#r)??void 0)}constructor(r){let n=r.format?{segments:oo(r.format),separator:r.separator??"/"}:Mi(r.locale),o=r.separator??n.separator,i=r.format?oo(r.format):n.segments,e=r.initialValue??r.defaultValue,t=e?{year:String(e.getUTCFullYear()).padStart(4,"0"),month:String(e.getUTCMonth()+1).padStart(2,"0"),day:String(e.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=i.map((s)=>t[s.type]).join(o);super({...r,initialUserInput:a},!1),this.#n=i,this.#e=o,this.#r=t,this.#t=r.minDate,this.#s=r.maxDate,this.#c(),this.on("cursor",(s)=>this.#d(s)),this.on("key",(s,c)=>this.#g(s,c)),this.on("finalize",()=>this.#h(r))}#f(){let r=Math.max(0,Math.min(this.#o.segmentIndex,this.#n.length-1)),n=this.#n[r];if(n)return this.#o.positionInSegment=Math.max(0,Math.min(this.#o.positionInSegment,n.len-1)),{segment:n,index:r}}#m(r){this.inlineError="",this.#a=null;let n=this.#f();n&&(this.#o.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+r)),this.#o.positionInSegment=0,this.#i=!0)}#p(r){let n=this.#f();if(!n)return;let{segment:o}=n,i=this.#r[o.type],e=!i||i.replace(/_/g,"")==="",t=Number.parseInt((i||"0").replace(/_/g,"0"),10)||0,a=Ui(o.type,Rr(this.#r),this.#t,this.#s),s;e?s=r===1?a.min:a.max:s=Math.max(Math.min(a.max,t+r),a.min),this.#r={...this.#r,[o.type]:s.toString().padStart(o.len,"0")},this.#i=!0,this.#a=null,this.#c()}#d(r){if(r)switch(r){case"right":return this.#m(1);case"left":return this.#m(-1);case"up":return this.#p(1);case"down":return this.#p(-1)}}#g(r,n){if(n?.name==="backspace"||n?.sequence==="\x7F"||n?.sequence==="\b"||r==="\x7F"||r==="\b"){this.inlineError="";let o=this.#f();if(!o)return;if(!this.#r[o.segment.type].replace(/_/g,"")){this.#m(-1);return}this.#r[o.segment.type]="_".repeat(o.segment.len),this.#i=!0,this.#o.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let o=this.#f();if(!o)return;let i=n.shift?-1:1,e=o.index+i;e>=0&&e<this.#n.length&&(this.#o.segmentIndex=e,this.#o.positionInSegment=0,this.#i=!0);return}if(r&&/^[0-9]$/.test(r)){let o=this.#f();if(!o)return;let{segment:i}=o,e=!this.#r[i.type].replace(/_/g,"");if(this.#i&&this.#a!==null&&!e){let u=this.#a+r,h={...this.#r,[i.type]:u},l=this.#l(h,i);if(l){this.inlineError=l,this.#a=null,this.#i=!1;return}this.inlineError="",this.#r[i.type]=u,this.#a=null,this.#i=!1,this.#c(),o.index<this.#n.length-1&&(this.#o.segmentIndex=o.index+1,this.#o.positionInSegment=0,this.#i=!0);return}this.#i&&!e&&(this.#r[i.type]="_".repeat(i.len),this.#o.positionInSegment=0),this.#i=!1,this.#a=null;let t=this.#r[i.type],a=t.indexOf("_"),s=a>=0?a:Math.min(this.#o.positionInSegment,i.len-1);if(s<0||s>=i.len)return;let c=t.slice(0,s)+r+t.slice(s+1),f=!1;if(s===0&&t==="__"&&(i.type==="month"||i.type==="day")){let u=Number.parseInt(r,10);c=`0${r}`,f=u<=(i.type==="month"?1:2)}if(i.type==="year"&&(c=(t.replace(/_/g,"")+r).padStart(i.len,"_")),!c.includes("_")){let u={...this.#r,[i.type]:c},h=this.#l(u,i);if(h){this.inlineError=h;return}}this.inlineError="",this.#r[i.type]=c;let d=c.includes("_")?void 0:so(this.#r);if(d){let{year:u,month:h}=d,l=mn(u,h);this.#r={year:String(Math.max(0,Math.min(9999,u))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(l,d.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");f?(this.#i=!0,this.#a=r):g>=0?this.#o.positionInSegment=g:a>=0&&o.index<this.#n.length-1?(this.#o.segmentIndex=o.index+1,this.#o.positionInSegment=0,this.#i=!0):this.#o.positionInSegment=Math.min(s+1,i.len-1)}}#l(r,n){let{month:o,day:i}=Rr(r);if(n.type==="month"&&(o<0||o>12))return q.date.messages.invalidMonth;if(n.type==="day"&&(i<0||i>31))return q.date.messages.invalidDay(31,"any month")}#h(r){let{year:n,month:o,day:i}=Rr(this.#r);if(n&&o&&i){let e=mn(n,o);this.#r={...this.#r,day:String(Math.min(i,e)).padStart(2,"0")}}this.value=io(this.#r)??r.defaultValue??void 0}}var Hi=class extends T{options;cursor=0;#n;getGroupItems(n){return this.options.filter((o)=>o.group===n)}isGroupSelected(n){let o=this.getGroupItems(n),i=this.value;return i===void 0?!1:o.every((e)=>i.includes(e.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let o=n.value,i=this.getGroupItems(o);this.isGroupSelected(o)?this.value=this.value.filter((e)=>i.findIndex((t)=>t.value===e)===-1):this.value=[...this.value,...i.map((e)=>e.value)],this.value=Array.from(new Set(this.value))}else{let o=this.value.includes(n.value);this.value=o?this.value.filter((i)=>i!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:o}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(o).flatMap(([i,e])=>[{value:i,group:!0,label:i},...e.map((t)=>({...t,group:i}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===n.cursorAt),this.#n?0:1),this.on("cursor",(i)=>{switch(i){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!this.#n&&e&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let e=this.options[this.cursor]?.group===!0;!this.#n&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ei=new Set(["up","down","left","right"]);class fo extends T{#n=!1;#e;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${r}\u2588`;let n=r.slice(0,this.cursor),o=r.slice(this.cursor,this.cursor+1),i=r.slice(this.cursor+1);return o===`
17
+ `)),this._prevFrame=r;return}}this.output.write(W.erase.down())}this.output.write(r),this.state==="initial"&&(this.state="active"),this._prevFrame=r}}}function Di(r,n){if(r===void 0||n.length===0)return 0;let o=n.findIndex((i)=>i.value===r);return o!==-1?o:0}function Hi(r,n){return(n.label??String(n.value)).toLowerCase().includes(r.toLowerCase())}function ji(r,n){if(n)return r?n:n[0]}var Ei=class extends T{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#e="";#r;#t;#s;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return jr(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let n=this.userInput.slice(0,this.cursor),o=this.userInput.slice(this.cursor,this.cursor+1),i=this.userInput.slice(this.cursor+1);return`${n}${jr("inverse",o)}${i}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(n){super(n),this.#t=n.options,this.#s=n.placeholder;let o=this.options;this.filteredOptions=[...o],this.multiple=n.multiple===!0,this.#r=typeof n.options=="function"?n.filter:n.filter??Hi;let i;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?i=n.initialValue:i=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0]?.value]),i)for(let e of i){let t=o.findIndex((a)=>a.value===e);t!==-1&&(this.toggleSelected(e),this.#n=t)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(e,t)=>this.#o(e,t)),this.on("userInput",(e)=>this.#i(e))}_isActionKey(n,o){return n==="\t"||this.multiple&&this.isNavigating&&o.name==="space"&&n!==void 0&&n!==""}#o(n,o){let i=o.name==="up",e=o.name==="down",t=o.name==="return",a=this.userInput===""||this.userInput==="\t",s=this.#s,c=this.options,f=s!==void 0&&s!==""&&c.some((l)=>!l.disabled&&(this.#r?this.#r(s,l):!0));if(o.name==="tab"&&a&&f){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}i||e?(this.#n=_(this.#n,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):t?this.value=ji(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(o.name==="tab"||this.isNavigating&&o.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((o)=>o!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#i(n){if(n!==this.#e){this.#e=n;let o=this.options;n&&this.#r?this.filteredOptions=o.filter((t)=>this.#r?.(n,t)):this.filteredOptions=[...o];let i=Di(this.focusedValue,this.filteredOptions);this.#n=_(i,0,this.filteredOptions);let e=this.filteredOptions[this.#n];e&&!e.disabled?this.focusedValue=e.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class hn extends T{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(r){super(r,!1),this.value=!!r.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(W.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Mi={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function eo(r){return[...r].map((n)=>Mi[n])}function Ui(r){let n=new Intl.DateTimeFormat(r,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),o=[],i="/";for(let e of n)e.type==="literal"?i=e.value.trim()||e.value:(e.type==="year"||e.type==="month"||e.type==="day")&&o.push({type:e.type,len:e.type==="year"?4:2});return{segments:o,separator:i}}function mn(r){return Number.parseInt((r||"0").replace(/_/g,"0"),10)||0}function Hr(r){return{year:mn(r.year),month:mn(r.month),day:mn(r.day)}}function pn(r,n){return new Date(r||2001,n||1,0).getDate()}function fo(r){let{year:n,month:o,day:i}=Hr(r);if(!n||n<0||n>9999||!o||o<1||o>12||!i||i<1)return;let e=new Date(Date.UTC(n,o-1,i));if(!(e.getUTCFullYear()!==n||e.getUTCMonth()!==o-1||e.getUTCDate()!==i))return{year:n,month:o,day:i}}function to(r){let n=fo(r);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function Gi(r,n,o,i){let e=o?{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()}:null,t=i?{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}:null;return r==="year"?{min:e?.year??1,max:t?.year??9999}:r==="month"?{min:e&&n.year===e.year?e.month:1,max:t&&n.year===t.year?t.month:12}:{min:e&&n.year===e.year&&n.month===e.month?e.day:1,max:t&&n.year===t.year&&n.month===t.month?t.day:pn(n.year,n.month)}}class mo extends T{#n;#e;#r;#t;#s;#o={segmentIndex:0,positionInSegment:0};#i=!0;#a=null;inlineError="";get segmentCursor(){return{...this.#o}}get segmentValues(){return{...this.#r}}get segments(){return this.#n}get separator(){return this.#e}get formattedValue(){return this.#u(this.#r)}#u(r){return this.#n.map((n)=>r[n.type]).join(this.#e)}#c(){this._setUserInput(this.#u(this.#r)),this._setValue(to(this.#r)??void 0)}constructor(r){let n=r.format?{segments:eo(r.format),separator:r.separator??"/"}:Ui(r.locale),o=r.separator??n.separator,i=r.format?eo(r.format):n.segments,e=r.initialValue??r.defaultValue,t=e?{year:String(e.getUTCFullYear()).padStart(4,"0"),month:String(e.getUTCMonth()+1).padStart(2,"0"),day:String(e.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=i.map((s)=>t[s.type]).join(o);super({...r,initialUserInput:a},!1),this.#n=i,this.#e=o,this.#r=t,this.#t=r.minDate,this.#s=r.maxDate,this.#c(),this.on("cursor",(s)=>this.#l(s)),this.on("key",(s,c)=>this.#g(s,c)),this.on("finalize",()=>this.#h(r))}#f(){let r=Math.max(0,Math.min(this.#o.segmentIndex,this.#n.length-1)),n=this.#n[r];if(n)return this.#o.positionInSegment=Math.max(0,Math.min(this.#o.positionInSegment,n.len-1)),{segment:n,index:r}}#m(r){this.inlineError="",this.#a=null;let n=this.#f();n&&(this.#o.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+r)),this.#o.positionInSegment=0,this.#i=!0)}#p(r){let n=this.#f();if(!n)return;let{segment:o}=n,i=this.#r[o.type],e=!i||i.replace(/_/g,"")==="",t=Number.parseInt((i||"0").replace(/_/g,"0"),10)||0,a=Gi(o.type,Hr(this.#r),this.#t,this.#s),s;e?s=r===1?a.min:a.max:s=Math.max(Math.min(a.max,t+r),a.min),this.#r={...this.#r,[o.type]:s.toString().padStart(o.len,"0")},this.#i=!0,this.#a=null,this.#c()}#l(r){if(r)switch(r){case"right":return this.#m(1);case"left":return this.#m(-1);case"up":return this.#p(1);case"down":return this.#p(-1)}}#g(r,n){if(n?.name==="backspace"||n?.sequence==="\x7F"||n?.sequence==="\b"||r==="\x7F"||r==="\b"){this.inlineError="";let o=this.#f();if(!o)return;if(!this.#r[o.segment.type].replace(/_/g,"")){this.#m(-1);return}this.#r[o.segment.type]="_".repeat(o.segment.len),this.#i=!0,this.#o.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let o=this.#f();if(!o)return;let i=n.shift?-1:1,e=o.index+i;e>=0&&e<this.#n.length&&(this.#o.segmentIndex=e,this.#o.positionInSegment=0,this.#i=!0);return}if(r&&/^[0-9]$/.test(r)){let o=this.#f();if(!o)return;let{segment:i}=o,e=!this.#r[i.type].replace(/_/g,"");if(this.#i&&this.#a!==null&&!e){let u=this.#a+r,h={...this.#r,[i.type]:u},d=this.#d(h,i);if(d){this.inlineError=d,this.#a=null,this.#i=!1;return}this.inlineError="",this.#r[i.type]=u,this.#a=null,this.#i=!1,this.#c(),o.index<this.#n.length-1&&(this.#o.segmentIndex=o.index+1,this.#o.positionInSegment=0,this.#i=!0);return}this.#i&&!e&&(this.#r[i.type]="_".repeat(i.len),this.#o.positionInSegment=0),this.#i=!1,this.#a=null;let t=this.#r[i.type],a=t.indexOf("_"),s=a>=0?a:Math.min(this.#o.positionInSegment,i.len-1);if(s<0||s>=i.len)return;let c=t.slice(0,s)+r+t.slice(s+1),f=!1;if(s===0&&t==="__"&&(i.type==="month"||i.type==="day")){let u=Number.parseInt(r,10);c=`0${r}`,f=u<=(i.type==="month"?1:2)}if(i.type==="year"&&(c=(t.replace(/_/g,"")+r).padStart(i.len,"_")),!c.includes("_")){let u={...this.#r,[i.type]:c},h=this.#d(u,i);if(h){this.inlineError=h;return}}this.inlineError="",this.#r[i.type]=c;let l=c.includes("_")?void 0:fo(this.#r);if(l){let{year:u,month:h}=l,d=pn(u,h);this.#r={year:String(Math.max(0,Math.min(9999,u))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(d,l.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");f?(this.#i=!0,this.#a=r):g>=0?this.#o.positionInSegment=g:a>=0&&o.index<this.#n.length-1?(this.#o.segmentIndex=o.index+1,this.#o.positionInSegment=0,this.#i=!0):this.#o.positionInSegment=Math.min(s+1,i.len-1)}}#d(r,n){let{month:o,day:i}=Hr(r);if(n.type==="month"&&(o<0||o>12))return N.date.messages.invalidMonth;if(n.type==="day"&&(i<0||i>31))return N.date.messages.invalidDay(31,"any month")}#h(r){let{year:n,month:o,day:i}=Hr(this.#r);if(n&&o&&i){let e=pn(n,o);this.#r={...this.#r,day:String(Math.min(i,e)).padStart(2,"0")}}this.value=to(this.#r)??r.defaultValue??void 0}}var Ni=class extends T{options;cursor=0;#n;getGroupItems(n){return this.options.filter((o)=>o.group===n)}isGroupSelected(n){let o=this.getGroupItems(n),i=this.value;return i===void 0?!1:o.every((e)=>i.includes(e.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let o=n.value,i=this.getGroupItems(o);this.isGroupSelected(o)?this.value=this.value.filter((e)=>i.findIndex((t)=>t.value===e)===-1):this.value=[...this.value,...i.map((e)=>e.value)],this.value=Array.from(new Set(this.value))}else{let o=this.value.includes(n.value);this.value=o?this.value.filter((i)=>i!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:o}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(o).flatMap(([i,e])=>[{value:i,group:!0,label:i},...e.map((t)=>({...t,group:i}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===n.cursorAt),this.#n?0:1),this.on("cursor",(i)=>{switch(i){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!this.#n&&e&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let e=this.options[this.cursor]?.group===!0;!this.#n&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},qi=new Set(["up","down","left","right"]);class uo extends T{#n=!1;#e;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${r}\u2588`;let n=r.slice(0,this.cursor),o=r.slice(this.cursor,this.cursor+1),i=r.slice(this.cursor+1);return o===`
18
18
  `?`${n}\u2588
19
- ${i}`:`${n}${jr("inverse",o)}${i}`}get cursor(){return this._cursor}#r(r){if(this.userInput.length===0){this._setUserInput(r);return}this._setUserInput(this.userInput.slice(0,this.cursor)+r+this.userInput.slice(this.cursor))}#t(r){let n=this.value??"";switch(r){case"up":this._cursor=Ir(this._cursor,0,-1,n);return;case"down":this._cursor=Ir(this._cursor,0,1,n);return;case"left":this._cursor=Ir(this._cursor,-1,0,n);return;case"right":this._cursor=Ir(this._cursor,1,0,n);return}}_shouldSubmit(r,n){if(this.#e)return this.focused==="submit"?!0:(this.#r(`
19
+ ${i}`:`${n}${jr("inverse",o)}${i}`}get cursor(){return this._cursor}#r(r){if(this.userInput.length===0){this._setUserInput(r);return}this._setUserInput(this.userInput.slice(0,this.cursor)+r+this.userInput.slice(this.cursor))}#t(r){let n=this.value??"";switch(r){case"up":this._cursor=Rr(this._cursor,0,-1,n);return;case"down":this._cursor=Rr(this._cursor,0,1,n);return;case"left":this._cursor=Rr(this._cursor,-1,0,n);return;case"right":this._cursor=Rr(this._cursor,1,0,n);return}}_shouldSubmit(r,n){if(this.#e)return this.focused==="submit"?!0:(this.#r(`
20
20
  `),this._cursor++,!1);let o=this.#n;return this.#n=!0,o&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
21
21
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#r(`
22
- `),this._cursor++,!1)}constructor(r){let n=r.initialUserInput??r.initialValue;super({...r,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#e=r.showSubmit??!1,this.on("key",(o,i)=>{if(i?.name&&Ei.has(i.name)){this.#n=!1,this.#t(i.name);return}if(o==="\t"&&this.#e){this.focused=this.focused==="editor"?"submit":"editor";return}if(i?.name!=="return"){if(this.#n=!1,i?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(i?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}o&&(this.#e&&this.focused==="submit"&&(this.focused="editor"),this.#r(o??""),this._cursor++)}}),this.on("userInput",(o)=>{this._setValue(o)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}class gn extends T{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((r)=>r.disabled!==!0)}toggleAll(){let r=this._enabledOptions,n=this.value!==void 0&&this.value.length===r.length;this.value=n?[]:r.map((o)=>o.value)}toggleInvert(){let r=this.value;if(!r)return;let n=this._enabledOptions.filter((o)=>!r.includes(o.value));this.value=n.map((o)=>o.value)}toggleValue(){this.value===void 0&&(this.value=[]);let r=this.value.includes(this._value);this.value=r?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(r){super(r,!1),this.options=r.options,this.value=[...r.initialValues??[]];let n=Math.max(this.options.findIndex(({value:o})=>o===r.cursorAt),0);this.cursor=this.options[n]?.disabled?_(n,1,this.options):n,this.on("key",(o,i)=>{i.name==="a"&&this.toggleAll(),i.name==="i"&&this.toggleInvert()}),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var mo=class extends T{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let n=this._selectedValue;this.value=n===void 0?void 0:n.value}constructor(n){super(n,!1),this.options=n.options;let o=this.options.findIndex(({value:e})=>e===n.initialValue),i=o===-1?0:o;this.cursor=this.options[i]?.disabled?_(i,1,this.options):i,this.changeValue(),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break}this.changeValue()})}};class hn extends T{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${this.userInput}\u2588`;let n=r.slice(0,this.cursor),o=r.slice(this.cursor,this.cursor+1),i=r.slice(this.cursor+1);return`${n}${jr("inverse",o)}${i}`}get cursor(){return this._cursor}constructor(r){super({...r,initialUserInput:r.initialUserInput??r.initialValue}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as m,stripVTControlCharacters as bt}from"util";import x from"process";var hr=Wn(sn(),1);function Ni(){if(x.platform!=="win32")return x.env.TERM!=="linux";return Boolean(x.env.CI)||Boolean(x.env.WT_SESSION)||Boolean(x.env.TERMINUS_SUBLIME)||x.env.ConEmuTask==="{cmd::Cmder}"||x.env.TERM_PROGRAM==="Terminus-Sublime"||x.env.TERM_PROGRAM==="vscode"||x.env.TERM==="xterm-256color"||x.env.TERM==="alacritty"||x.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var bn=Ni(),qi=()=>process.env.CI==="true";var y=(r,n)=>bn?r:n,Gi=y("\u25C6","*"),ho=y("\u25A0","x"),bo=y("\u25B2","x"),Hr=y("\u25C7","o"),zi=y("\u250C","T"),P=y("\u2502","|"),er=y("\u2514","\u2014"),Pt=y("\u2510","T"),Ct=y("\u2518","\u2014"),vn=y("\u25CF",">"),Ur=y("\u25CB"," "),Wi=y("\u25FB","[\u2022]"),uo=y("\u25FC","[+]"),po=y("\u25FB","[ ]"),Ft=y("\u25AA","\u2022"),lo=y("\u2500","-"),Ji=y("\u256E","+"),Ai=y("\u251C","+"),Ki=y("\u256F","+"),Yi=y("\u2570","+"),kt=y("\u256D","+"),Zi=y("\u25CF","\u2022"),xi=y("\u25C6","*"),Qi=y("\u25B2","!"),Xi=y("\u25A0","x"),Er=(r)=>{switch(r){case"initial":case"active":return m("cyan",Gi);case"cancel":return m("red",ho);case"error":return m("yellow",bo);case"submit":return m("green",Hr)}},vo=(r)=>{switch(r){case"initial":case"active":return m("cyan",P);case"cancel":return m("red",P);case"error":return m("yellow",P);case"submit":return m("green",P)}};function wo(r,n){let o=[`${n?`${m("cyan",P)} `:""}${r.join(" \u2022 ")}`];return n&&o.push(m("cyan",er)),o}var go=(r,n,o,i,e,t=!1)=>{let a=n,s=0;if(t)for(let c=i-1;c>=o;c--){let f=r[c];if(f&&(a-=f.length),s++,a<=e)break}else for(let c=o;c<i;c++){let f=r[c];if(f&&(a-=f.length),s++,a<=e)break}return{lineCount:a,removals:s}},wn=({cursor:r,options:n,style:o,output:i=process.stdout,maxItems:e=Number.POSITIVE_INFINITY,columnPadding:t=0,rowPadding:a=4})=>{let s=dr(i)-t,c=ln(i),f=m("dim","..."),d=Math.max(c-a,0),g=Math.max(Math.min(e,d),5),u=0;r>=g-3&&(u=Math.max(Math.min(r-g+3,n.length-g),0));let h=g<n.length&&u>0,l=g<n.length&&u+g<n.length,b=Math.min(u+g,n.length),k=[],R=0;h&&R++,l&&R++;let C=u+(h?1:0),N=b-(l?1:0);for(let F=C;F<N;F++){let E=n[F],M=E?o(E,F===r):"",L=O(M,s,{hard:!0,trim:!1}).split(`
23
- `);k.push(L),R+=L.length}if(R>d){let F=0,E=0,M=R,L=r-C,H=d,V=()=>go(k,M,0,L,H),A=()=>go(k,M,L+1,k.length,H,!0);h?({lineCount:M,removals:F}=V(),M>H&&(l||(H-=1),{lineCount:M,removals:E}=A())):(l||(H-=1),{lineCount:M,removals:E}=A(),M>H&&(H-=1,{lineCount:M,removals:F}=V())),F>0&&(h=!0,k.splice(0,F)),E>0&&(l=!0,k.splice(k.length-E,E))}let j=[];h&&j.push(f);for(let F of k)for(let E of F)j.push(E);return l&&j.push(f),j};var $o=(r)=>{let n=r.active??"Yes",o=r.inactive??"No";return new dn({active:n,inactive:o,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue??!0,render(){let i=r.withGuide??q.withGuide,e=`${Er(this.state)} `,t=i?`${m("gray",P)} `:"",a=ir(r.output,r.message,t,e),s=`${i?`${m("gray",P)}
22
+ `),this._cursor++,!1)}constructor(r){let n=r.initialUserInput??r.initialValue;super({...r,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#e=r.showSubmit??!1,this.on("key",(o,i)=>{if(i?.name&&qi.has(i.name)){this.#n=!1,this.#t(i.name);return}if(o==="\t"&&this.#e){this.focused=this.focused==="editor"?"submit":"editor";return}if(i?.name!=="return"){if(this.#n=!1,i?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(i?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}o&&(this.#e&&this.focused==="submit"&&(this.focused="editor"),this.#r(o??""),this._cursor++)}}),this.on("userInput",(o)=>{this._setValue(o)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}class bn extends T{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((r)=>r.disabled!==!0)}toggleAll(){let r=this._enabledOptions,n=this.value!==void 0&&this.value.length===r.length;this.value=n?[]:r.map((o)=>o.value)}toggleInvert(){let r=this.value;if(!r)return;let n=this._enabledOptions.filter((o)=>!r.includes(o.value));this.value=n.map((o)=>o.value)}toggleValue(){this.value===void 0&&(this.value=[]);let r=this.value.includes(this._value);this.value=r?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(r){super(r,!1),this.options=r.options,this.value=[...r.initialValues??[]];let n=Math.max(this.options.findIndex(({value:o})=>o===r.cursorAt),0);this.cursor=this.options[n]?.disabled?_(n,1,this.options):n,this.on("key",(o,i)=>{i.name==="a"&&this.toggleAll(),i.name==="i"&&this.toggleInvert()}),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var po=class extends T{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let n=this._selectedValue;this.value=n===void 0?void 0:n.value}constructor(n){super(n,!1),this.options=n.options;let o=this.options.findIndex(({value:e})=>e===n.initialValue),i=o===-1?0:o;this.cursor=this.options[i]?.disabled?_(i,1,this.options):i,this.changeValue(),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break}this.changeValue()})}};class vn extends T{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${this.userInput}\u2588`;let n=r.slice(0,this.cursor),o=r.slice(this.cursor,this.cursor+1),i=r.slice(this.cursor+1);return`${n}${jr("inverse",o)}${i}`}get cursor(){return this._cursor}constructor(r){super({...r,initialUserInput:r.initialUserInput??r.initialValue}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as m,stripVTControlCharacters as Pt}from"util";import Z from"process";var br=Jn(fn(),1);function zi(){if(Z.platform!=="win32")return Z.env.TERM!=="linux";return Boolean(Z.env.CI)||Boolean(Z.env.WT_SESSION)||Boolean(Z.env.TERMINUS_SUBLIME)||Z.env.ConEmuTask==="{cmd::Cmder}"||Z.env.TERM_PROGRAM==="Terminus-Sublime"||Z.env.TERM_PROGRAM==="vscode"||Z.env.TERM==="xterm-256color"||Z.env.TERM==="alacritty"||Z.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var wn=zi(),Wi=()=>process.env.CI==="true";var y=(r,n)=>wn?r:n,Ai=y("\u25C6","*"),vo=y("\u25A0","x"),wo=y("\u25B2","x"),Ur=y("\u25C7","o"),Ji=y("\u250C","T"),P=y("\u2502","|"),er=y("\u2514","\u2014"),yt=y("\u2510","T"),It=y("\u2518","\u2014"),$n=y("\u25CF",">"),Mr=y("\u25CB"," "),xi=y("\u25FB","[\u2022]"),lo=y("\u25FC","[+]"),go=y("\u25FB","[ ]"),Lt=y("\u25AA","\u2022"),ho=y("\u2500","-"),Ki=y("\u256E","+"),Yi=y("\u251C","+"),Zi=y("\u256F","+"),Qi=y("\u2570","+"),Rt=y("\u256D","+"),Xi=y("\u25CF","\u2022"),Vi=y("\u25C6","*"),Oi=y("\u25B2","!"),Si=y("\u25A0","x"),Gr=(r)=>{switch(r){case"initial":case"active":return m("cyan",Ai);case"cancel":return m("red",vo);case"error":return m("yellow",wo);case"submit":return m("green",Ur)}},$o=(r)=>{switch(r){case"initial":case"active":return m("cyan",P);case"cancel":return m("red",P);case"error":return m("yellow",P);case"submit":return m("green",P)}};function Po(r,n){let o=[`${n?`${m("cyan",P)} `:""}${r.join(" \u2022 ")}`];return n&&o.push(m("cyan",er)),o}var bo=(r,n,o,i,e,t=!1)=>{let a=n,s=0;if(t)for(let c=i-1;c>=o;c--){let f=r[c];if(f&&(a-=f.length),s++,a<=e)break}else for(let c=o;c<i;c++){let f=r[c];if(f&&(a-=f.length),s++,a<=e)break}return{lineCount:a,removals:s}},Pn=({cursor:r,options:n,style:o,output:i=process.stdout,maxItems:e=Number.POSITIVE_INFINITY,columnPadding:t=0,rowPadding:a=4})=>{let s=gr(i)-t,c=gn(i),f=m("dim","..."),l=Math.max(c-a,0),g=Math.max(Math.min(e,l),5),u=0;r>=g-3&&(u=Math.max(Math.min(r-g+3,n.length-g),0));let h=g<n.length&&u>0,d=g<n.length&&u+g<n.length,b=Math.min(u+g,n.length),k=[],D=0;h&&D++,d&&D++;let C=u+(h?1:0),G=b-(d?1:0);for(let F=C;F<G;F++){let U=n[F],j=U?o(U,F===r):"",I=O(j,s,{hard:!0,trim:!1}).split(`
23
+ `);k.push(I),D+=I.length}if(D>l){let F=0,U=0,j=D,I=r-C,M=l,V=()=>bo(k,j,0,I,M),J=()=>bo(k,j,I+1,k.length,M,!0);h?({lineCount:j,removals:F}=V(),j>M&&(d||(M-=1),{lineCount:j,removals:U}=J())):(d||(M-=1),{lineCount:j,removals:U}=J(),j>M&&(M-=1,{lineCount:j,removals:F}=V())),F>0&&(h=!0,k.splice(0,F)),U>0&&(d=!0,k.splice(k.length-U,U))}let H=[];h&&H.push(f);for(let F of k)for(let U of F)H.push(U);return d&&H.push(f),H};var Co=(r)=>{let n=r.active??"Yes",o=r.inactive??"No";return new hn({active:n,inactive:o,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue??!0,render(){let i=r.withGuide??N.withGuide,e=`${Gr(this.state)} `,t=i?`${m("gray",P)} `:"",a=ir(r.output,r.message,t,e),s=`${i?`${m("gray",P)}
24
24
  `:""}${a}
25
25
  `,c=this.value?n:o;switch(this.state){case"submit":{let f=i?`${m("gray",P)} `:"";return`${s}${f}${m("dim",c)}`}case"cancel":{let f=i?`${m("gray",P)} `:"";return`${s}${f}${m(["strikethrough","dim"],c)}${i?`
26
- ${m("gray",P)}`:""}`}default:{let f=i?`${m("cyan",P)} `:"",d=i?m("cyan",er):"";return`${s}${f}${this.value?`${m("green",vn)} ${n}`:`${m("dim",Ur)} ${m("dim",n)}`}${r.vertical?i?`
26
+ ${m("gray",P)}`:""}`}default:{let f=i?`${m("cyan",P)} `:"",l=i?m("cyan",er):"";return`${s}${f}${this.value?`${m("green",$n)} ${n}`:`${m("dim",Mr)} ${m("dim",n)}`}${r.vertical?i?`
27
27
  ${m("cyan",P)} `:`
28
- `:` ${m("dim","/")} `}${this.value?`${m("dim",Ur)} ${m("dim",o)}`:`${m("green",vn)} ${o}`}
29
- ${d}
30
- `}}}}).prompt()};var Nr=async(r,n)=>{let o={},i=Object.keys(r);for(let e of i){let t=r[e],a=await t({results:o})?.catch((s)=>{throw s});if(typeof n?.onCancel=="function"&&lr(a)){o[e]="canceled",n.onCancel({results:o});continue}o[e]=a}return o},Vi=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Space:")} select`,`${m("dim","Enter:")} confirm`],gr=(r,n)=>r.split(`
28
+ `:` ${m("dim","/")} `}${this.value?`${m("dim",Mr)} ${m("dim",o)}`:`${m("green",$n)} ${o}`}
29
+ ${l}
30
+ `}}}}).prompt()};var Nr=async(r,n)=>{let o={},i=Object.keys(r);for(let e of i){let t=r[e],a=await t({results:o})?.catch((s)=>{throw s});if(typeof n?.onCancel=="function"&&lr(a)){o[e]="canceled",n.onCancel({results:o});continue}o[e]=a}return o},Bi=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Space:")} select`,`${m("dim","Enter:")} confirm`],hr=(r,n)=>r.split(`
31
31
  `).map((o)=>n(o)).join(`
32
- `),Po=(r)=>{let n=(e,t)=>{let a=e.label??String(e.value);return t==="disabled"?`${m("gray",po)} ${gr(a,(s)=>m(["strikethrough","gray"],s))}${e.hint?` ${m("dim",`(${e.hint??"disabled"})`)}`:""}`:t==="active"?`${m("cyan",Wi)} ${a}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="selected"?`${m("green",uo)} ${gr(a,(s)=>m("dim",s))}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="cancelled"?`${gr(a,(s)=>m(["strikethrough","dim"],s))}`:t==="active-selected"?`${m("green",uo)} ${a}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="submitted"?`${gr(a,(s)=>m("dim",s))}`:`${m("dim",po)} ${gr(a,(s)=>m("dim",s))}`},o=r.required??!0,i=r.showInstructions??!0;return new gn({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValues:r.initialValues,required:o,cursorAt:r.cursorAt,validate(e){if(o&&(e===void 0||e.length===0))return`Please select at least one option.
33
- ${m("reset",m("dim",`Press ${m(["gray","bgWhite","inverse"]," space ")} to select, ${m("gray",m("bgWhite",m("inverse"," enter ")))} to submit`))}`},render(){let e=r.withGuide??q.withGuide,t=ir(r.output,r.message,e?`${vo(this.state)} `:"",`${Er(this.state)} `),a=`${e?`${m("gray",P)}
32
+ `),Fo=(r)=>{let n=(e,t)=>{let a=e.label??String(e.value);return t==="disabled"?`${m("gray",go)} ${hr(a,(s)=>m(["strikethrough","gray"],s))}${e.hint?` ${m("dim",`(${e.hint??"disabled"})`)}`:""}`:t==="active"?`${m("cyan",xi)} ${a}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="selected"?`${m("green",lo)} ${hr(a,(s)=>m("dim",s))}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="cancelled"?`${hr(a,(s)=>m(["strikethrough","dim"],s))}`:t==="active-selected"?`${m("green",lo)} ${a}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="submitted"?`${hr(a,(s)=>m("dim",s))}`:`${m("dim",go)} ${hr(a,(s)=>m("dim",s))}`},o=r.required??!0,i=r.showInstructions??!0;return new bn({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValues:r.initialValues,required:o,cursorAt:r.cursorAt,validate(e){if(o&&(e===void 0||e.length===0))return`Please select at least one option.
33
+ ${m("reset",m("dim",`Press ${m(["gray","bgWhite","inverse"]," space ")} to select, ${m("gray",m("bgWhite",m("inverse"," enter ")))} to submit`))}`},render(){let e=r.withGuide??N.withGuide,t=ir(r.output,r.message,e?`${$o(this.state)} `:"",`${Gr(this.state)} `),a=`${e?`${m("gray",P)}
34
34
  `:""}${t}
35
- `,s=this.value??[],c=(f,d)=>{if(f.disabled)return n(f,"disabled");let g=s.includes(f.value);return d&&g?n(f,"active-selected"):g?n(f,"selected"):n(f,d?"active":"inactive")};switch(this.state){case"submit":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"submitted")).join(m("dim",", "))||m("dim","none"),d=ir(r.output,f,e?`${m("gray",P)} `:"");return`${a}${d}`}case"cancel":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"cancelled")).join(m("dim",", "));if(f.trim()==="")return`${a}${m("gray",P)}`;let d=ir(r.output,f,e?`${m("gray",P)} `:"");return`${a}${d}${e?`
36
- ${m("gray",P)}`:""}`}case"error":{let f=e?`${m("yellow",P)} `:"",d=this.error.split(`
37
- `).map((h,l)=>l===0?`${e?`${m("yellow",er)} `:""}${m("yellow",h)}`:` ${h}`).join(`
35
+ `,s=this.value??[],c=(f,l)=>{if(f.disabled)return n(f,"disabled");let g=s.includes(f.value);return l&&g?n(f,"active-selected"):g?n(f,"selected"):n(f,l?"active":"inactive")};switch(this.state){case"submit":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"submitted")).join(m("dim",", "))||m("dim","none"),l=ir(r.output,f,e?`${m("gray",P)} `:"");return`${a}${l}`}case"cancel":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"cancelled")).join(m("dim",", "));if(f.trim()==="")return`${a}${m("gray",P)}`;let l=ir(r.output,f,e?`${m("gray",P)} `:"");return`${a}${l}${e?`
36
+ ${m("gray",P)}`:""}`}case"error":{let f=e?`${m("yellow",P)} `:"",l=this.error.split(`
37
+ `).map((h,d)=>d===0?`${e?`${m("yellow",er)} `:""}${m("yellow",h)}`:` ${h}`).join(`
38
38
  `),g=a.split(`
39
- `).length,u=d.split(`
40
- `).length+1;return`${a}${f}${wn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:g+u,style:c}).join(`
39
+ `).length,u=l.split(`
40
+ `).length+1;return`${a}${f}${Pn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:g+u,style:c}).join(`
41
41
  ${f}`)}
42
- ${d}
43
- `}default:{let f=e?`${m("cyan",P)} `:"",d=a.split(`
44
- `).length,g=i?wo(Vi,e):e?[m("cyan",er)]:[],u=g.join(`
45
- `),h=g.length+1;return`${a}${f}${wn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:d+h,style:c}).join(`
42
+ ${l}
43
+ `}default:{let f=e?`${m("cyan",P)} `:"",l=a.split(`
44
+ `).length,g=i?Po(Bi,e):e?[m("cyan",er)]:[],u=g.join(`
45
+ `),h=g.length+1;return`${a}${f}${Pn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:l+h,style:c}).join(`
46
46
  ${f}`)}
47
47
  ${u}
48
- `}}}}).prompt()};var w={message:(r=[],{symbol:n=m("gray",P),secondarySymbol:o=m("gray",P),output:i=process.stdout,spacing:e=1,withGuide:t}={})=>{let a=[],s=t??q.withGuide,c=s?o:"",f=s?`${n} `:"",d=s?`${o} `:"";for(let u=0;u<e;u++)a.push(c);let g=Array.isArray(r)?r:r.split(`
49
- `);if(g.length>0){let[u,...h]=g;u.length>0?a.push(`${f}${u}`):a.push(s?n:"");for(let l of h)l.length>0?a.push(`${d}${l}`):a.push(s?o:"")}i.write(`${a.join(`
48
+ `}}}}).prompt()};var w={message:(r=[],{symbol:n=m("gray",P),secondarySymbol:o=m("gray",P),output:i=process.stdout,spacing:e=1,withGuide:t}={})=>{let a=[],s=t??N.withGuide,c=s?o:"",f=s?`${n} `:"",l=s?`${o} `:"";for(let u=0;u<e;u++)a.push(c);let g=Array.isArray(r)?r:r.split(`
49
+ `);if(g.length>0){let[u,...h]=g;u.length>0?a.push(`${f}${u}`):a.push(s?n:"");for(let d of h)d.length>0?a.push(`${l}${d}`):a.push(s?o:"")}i.write(`${a.join(`
50
50
  `)}
51
- `)},info:(r,n)=>{w.message(r,{...n,symbol:m("blue",Zi)})},success:(r,n)=>{w.message(r,{...n,symbol:m("green",xi)})},step:(r,n)=>{w.message(r,{...n,symbol:m("green",Hr)})},warn:(r,n)=>{w.message(r,{...n,symbol:m("yellow",Qi)})},warning:(r,n)=>{w.warn(r,n)},error:(r,n)=>{w.message(r,{...n,symbol:m("red",Xi)})}};var qr=(r="",n)=>{let o=n?.output??process.stdout,i=n?.withGuide??q.withGuide?`${m("gray",zi)} `:"";o.write(`${i}${r}
52
- `)},Gr=(r="",n)=>{let o=n?.output??process.stdout,i=n?.withGuide??q.withGuide?`${m("gray",P)}
51
+ `)},info:(r,n)=>{w.message(r,{...n,symbol:m("blue",Xi)})},success:(r,n)=>{w.message(r,{...n,symbol:m("green",Vi)})},step:(r,n)=>{w.message(r,{...n,symbol:m("green",Ur)})},warn:(r,n)=>{w.message(r,{...n,symbol:m("yellow",Oi)})},warning:(r,n)=>{w.warn(r,n)},error:(r,n)=>{w.message(r,{...n,symbol:m("red",Si)})}};var qr=(r="",n)=>{let o=n?.output??process.stdout,i=n?.withGuide??N.withGuide?`${m("gray",Ji)} `:"";o.write(`${i}${r}
52
+ `)},zr=(r="",n)=>{let o=n?.output??process.stdout,i=n?.withGuide??N.withGuide?`${m("gray",P)}
53
53
  ${m("gray",er)} `:"";o.write(`${i}${r}
54
54
 
55
- `)};var Oi=(r)=>r,Si=(r,n,o)=>{let i={hard:!0,trim:!1},e=O(r,n,i).split(`
56
- `),t=e.reduce((c,f)=>Math.max(K(f),c),0),a=e.map(o).reduce((c,f)=>Math.max(K(f),c),0),s=n-(a-t);return O(r,s,i)},sr=(r="",n="",o)=>{let i=o?.output??x.stdout,e=o?.withGuide??q.withGuide,t=o?.format??Oi,a=["",...Si(r,dr(i)-6,t).split(`
57
- `).map(t),""],s=K(n),c=Math.max(a.reduce((u,h)=>{let l=K(h);return l>u?l:u},0),s)+2,f=a.map((u)=>`${m("gray",P)} ${u}${" ".repeat(c-K(u))}${m("gray",P)}`).join(`
58
- `),d=e?`${m("gray",P)}
59
- `:"",g=e?Ai:Yi;i.write(`${d}${m("green",Hr)} ${m("reset",n)} ${m("gray",lo.repeat(Math.max(c-s-1,1))+Ji)}
55
+ `)};var _i=(r)=>r,Ti=(r,n,o)=>{let i={hard:!0,trim:!1},e=O(r,n,i).split(`
56
+ `),t=e.reduce((c,f)=>Math.max(x(f),c),0),a=e.map(o).reduce((c,f)=>Math.max(x(f),c),0),s=n-(a-t);return O(r,s,i)},cr=(r="",n="",o)=>{let i=o?.output??Z.stdout,e=o?.withGuide??N.withGuide,t=o?.format??_i,a=["",...Ti(r,gr(i)-6,t).split(`
57
+ `).map(t),""],s=x(n),c=Math.max(a.reduce((u,h)=>{let d=x(h);return d>u?d:u},0),s)+2,f=a.map((u)=>`${m("gray",P)} ${u}${" ".repeat(c-x(u))}${m("gray",P)}`).join(`
58
+ `),l=e?`${m("gray",P)}
59
+ `:"",g=e?Yi:Qi;i.write(`${l}${m("green",Ur)} ${m("reset",n)} ${m("gray",ho.repeat(Math.max(c-s-1,1))+Ki)}
60
60
  ${f}
61
- ${m("gray",g+lo.repeat(c+2)+Ki)}
62
- `)};var Bi=(r)=>m("magenta",r),Y=({indicator:r="dots",onCancel:n,output:o=process.stdout,cancelMessage:i,errorMessage:e,frames:t=bn?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=bn?80:120,signal:s,...c}={})=>{let f=qi(),d,g,u=!1,h=!1,l="",b,k=performance.now(),R=dr(o),C=c?.styleFrame??Bi,N=(U)=>{let Z=U>1?e??q.messages.error:i??q.messages.cancel;h=U===1,u&&(pr(Z,U),h&&typeof n=="function"&&n())},j=()=>N(2),F=()=>N(1),E=()=>{process.on("uncaughtExceptionMonitor",j),process.on("unhandledRejection",j),process.on("SIGINT",F),process.on("SIGTERM",F),process.on("exit",N),s&&s.addEventListener("abort",F)},M=()=>{process.removeListener("uncaughtExceptionMonitor",j),process.removeListener("unhandledRejection",j),process.removeListener("SIGINT",F),process.removeListener("SIGTERM",F),process.removeListener("exit",N),s&&s.removeEventListener("abort",F)},L=()=>{if(b===void 0)return;f&&o.write(`
63
- `);let U=O(b,R,{hard:!0,trim:!1}).split(`
64
- `);U.length>1&&o.write(hr.cursor.up(U.length-1)),o.write(hr.cursor.to(0)),o.write(hr.erase.down())},H=(U)=>U.replace(/\.+$/,""),V=(U)=>{let Z=(performance.now()-U)/1000,S=Math.floor(Z/60),B=Math.floor(Z%60);return S>0?`[${S}m ${B}s]`:`[${B}s]`},A=c.withGuide??q.withGuide,kr=(U="")=>{u=!0,d=to({output:o}),l=H(U),k=performance.now(),A&&o.write(`${m("gray",P)}
65
- `);let Z=0,S=0;E(),g=setInterval(()=>{if(f&&l===b)return;L(),b=l;let B=C(t[Z]),yr;if(f)yr=`${B} ${l}...`;else if(r==="timer")yr=`${B} ${l} ${V(k)}`;else{let Bo=".".repeat(Math.floor(S)).slice(0,3);yr=`${B} ${l}${Bo}`}let So=O(yr,R,{hard:!0,trim:!1});o.write(So),Z=Z+1<t.length?Z+1:0,S=S<4?S+0.125:0},a)},pr=(U="",Z=0,S=!1)=>{if(!u)return;u=!1,clearInterval(g),L();let B=Z===0?m("green",Hr):Z===1?m("red",ho):m("red",bo);l=U??l,S||(r==="timer"?o.write(`${B} ${l} ${V(k)}
66
- `):o.write(`${B} ${l}
67
- `)),M(),d()};return{start:kr,stop:(U="")=>pr(U,0),message:(U="")=>{l=H(U??l)},cancel:(U="")=>pr(U,1),error:(U="")=>pr(U,2),clear:()=>pr("",0,!0),get isCancelled(){return h}}},yt={light:y("\u2500","-"),heavy:y("\u2501","="),block:y("\u2588","#")};var _i=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Enter:")} confirm`],Mr=(r,n)=>r.includes(`
61
+ ${m("gray",g+ho.repeat(c+2)+Zi)}
62
+ `)};var re=(r)=>m("magenta",r),K=({indicator:r="dots",onCancel:n,output:o=process.stdout,cancelMessage:i,errorMessage:e,frames:t=wn?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=wn?80:120,signal:s,...c}={})=>{let f=Wi(),l,g,u=!1,h=!1,d="",b,k=performance.now(),D=gr(o),C=c?.styleFrame??re,G=(E)=>{let Y=E>1?e??N.messages.error:i??N.messages.cancel;h=E===1,u&&(dr(Y,E),h&&typeof n=="function"&&n())},H=()=>G(2),F=()=>G(1),U=()=>{process.on("uncaughtExceptionMonitor",H),process.on("unhandledRejection",H),process.on("SIGINT",F),process.on("SIGTERM",F),process.on("exit",G),s&&s.addEventListener("abort",F)},j=()=>{process.removeListener("uncaughtExceptionMonitor",H),process.removeListener("unhandledRejection",H),process.removeListener("SIGINT",F),process.removeListener("SIGTERM",F),process.removeListener("exit",G),s&&s.removeEventListener("abort",F)},I=()=>{if(b===void 0)return;f&&o.write(`
63
+ `);let E=O(b,D,{hard:!0,trim:!1}).split(`
64
+ `);E.length>1&&o.write(br.cursor.up(E.length-1)),o.write(br.cursor.to(0)),o.write(br.erase.down())},M=(E)=>E.replace(/\.+$/,""),V=(E)=>{let Y=(performance.now()-E)/1000,S=Math.floor(Y/60),B=Math.floor(Y%60);return S>0?`[${S}m ${B}s]`:`[${B}s]`},J=c.withGuide??N.withGuide,yr=(E="")=>{u=!0,l=so({output:o}),d=M(E),k=performance.now(),J&&o.write(`${m("gray",P)}
65
+ `);let Y=0,S=0;U(),g=setInterval(()=>{if(f&&d===b)return;I(),b=d;let B=C(t[Y]),Ir;if(f)Ir=`${B} ${d}...`;else if(r==="timer")Ir=`${B} ${d} ${V(k)}`;else{let ri=".".repeat(Math.floor(S)).slice(0,3);Ir=`${B} ${d}${ri}`}let To=O(Ir,D,{hard:!0,trim:!1});o.write(To),Y=Y+1<t.length?Y+1:0,S=S<4?S+0.125:0},a)},dr=(E="",Y=0,S=!1)=>{if(!u)return;u=!1,clearInterval(g),I();let B=Y===0?m("green",Ur):Y===1?m("red",vo):m("red",wo);d=E??d,S||(r==="timer"?o.write(`${B} ${d} ${V(k)}
66
+ `):o.write(`${B} ${d}
67
+ `)),j(),l()};return{start:yr,stop:(E="")=>dr(E,0),message:(E="")=>{d=M(E??d)},cancel:(E="")=>dr(E,1),error:(E="")=>dr(E,2),clear:()=>dr("",0,!0),get isCancelled(){return h}}},Dt={light:y("\u2500","-"),heavy:y("\u2501","="),block:y("\u2588","#")};var ne=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Enter:")} confirm`],Er=(r,n)=>r.includes(`
68
68
  `)?r.split(`
69
69
  `).map((o)=>n(o)).join(`
70
- `):n(r),Co=(r)=>{let n=(i,e)=>{if(i===void 0)return"";let t=i.label??String(i.value);switch(e){case"disabled":return`${m("gray",Ur)} ${Mr(t,(a)=>m("gray",a))}${i.hint?` ${m("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Mr(t,(a)=>m("dim",a))}`;case"active":return`${m("green",vn)} ${t}${i.hint?` ${m("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${Mr(t,(a)=>m(["strikethrough","dim"],a))}`;default:return`${m("dim",Ur)} ${Mr(t,(a)=>m("dim",a))}`}},o=r.showInstructions??!0;return new mo({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue,render(){let i=r.withGuide??q.withGuide,e=`${Er(this.state)} `,t=`${vo(this.state)} `,a=ir(r.output,r.message,t,e),s=`${i?`${m("gray",P)}
70
+ `):n(r),ko=(r)=>{let n=(i,e)=>{if(i===void 0)return"";let t=i.label??String(i.value);switch(e){case"disabled":return`${m("gray",Mr)} ${Er(t,(a)=>m("gray",a))}${i.hint?` ${m("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Er(t,(a)=>m("dim",a))}`;case"active":return`${m("green",$n)} ${t}${i.hint?` ${m("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${Er(t,(a)=>m(["strikethrough","dim"],a))}`;default:return`${m("dim",Mr)} ${Er(t,(a)=>m("dim",a))}`}},o=r.showInstructions??!0;return new po({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue,render(){let i=r.withGuide??N.withGuide,e=`${Gr(this.state)} `,t=`${$o(this.state)} `,a=ir(r.output,r.message,t,e),s=`${i?`${m("gray",P)}
71
71
  `:""}${a}
72
72
  `;switch(this.state){case"submit":{let c=i?`${m("gray",P)} `:"",f=ir(r.output,n(this.options[this.cursor],"selected"),c);return`${s}${f}`}case"cancel":{let c=i?`${m("gray",P)} `:"",f=ir(r.output,n(this.options[this.cursor],"cancelled"),c);return`${s}${f}${i?`
73
73
  ${m("gray",P)}`:""}`}default:{let c=i?`${m("cyan",P)} `:"",f=s.split(`
74
- `).length,d=o?wo(_i,i):i?[m("cyan",er)]:[],g=d.join(`
75
- `),u=d.length+1;return`${s}${c}${wn({output:r.output,cursor:this.cursor,options:this.options,maxItems:r.maxItems,columnPadding:c.length,rowPadding:f+u,style:(h,l)=>n(h,h.disabled?"disabled":l?"active":"inactive")}).join(`
74
+ `).length,l=o?Po(ne,i):i?[m("cyan",er)]:[],g=l.join(`
75
+ `),u=l.length+1;return`${s}${c}${Pn({output:r.output,cursor:this.cursor,options:this.options,maxItems:r.maxItems,columnPadding:c.length,rowPadding:f+u,style:(h,d)=>n(h,h.disabled?"disabled":d?"active":"inactive")}).join(`
76
76
  ${c}`)}
77
77
  ${g}
78
- `}}}}).prompt()};var Lt=`${m("gray",P)} `;var Fo=(r)=>new hn({validate:r.validate,placeholder:r.placeholder,defaultValue:r.defaultValue,initialValue:r.initialValue,output:r.output,signal:r.signal,input:r.input,render(){let n=r?.withGuide??q.withGuide,o=`${`${n?`${m("gray",P)}
79
- `:""}${Er(this.state)} `}${r.message}
78
+ `}}}}).prompt()};var Ht=`${m("gray",P)} `;var yo=(r)=>new vn({validate:r.validate,placeholder:r.placeholder,defaultValue:r.defaultValue,initialValue:r.initialValue,output:r.output,signal:r.signal,input:r.input,render(){let n=r?.withGuide??N.withGuide,o=`${`${n?`${m("gray",P)}
79
+ `:""}${Gr(this.state)} `}${r.message}
80
80
  `,i=r.placeholder&&r.placeholder.length>0?m("inverse",r.placeholder[0])+m("dim",r.placeholder.slice(1)):m(["inverse","hidden"],"_"),e=this.userInput?this.userInputWithCursor:i,t=this.value??"";switch(this.state){case"error":{let a=this.error?` ${m("yellow",this.error)}`:"",s=n?`${m("yellow",P)} `:"",c=n?m("yellow",er):"";return`${o.trim()}
81
81
  ${s}${e}
82
82
  ${c}${a}
83
83
  `}case"submit":{let a=t?` ${m("dim",t)}`:"",s=n?m("gray",P):"";return`${o}${s}${a}`}case"cancel":{let a=t?` ${m(["strikethrough","dim"],t)}`:"",s=n?m("gray",P):"";return`${o}${s}${a}${t.trim()?`
84
84
  ${s}`:""}`}default:{let a=n?`${m("cyan",P)} `:"",s=n?m("cyan",er):"";return`${o}${a}${e}
85
85
  ${s}
86
- `}}}}).prompt();var re=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Lo=["black","blue","cyan","gray","green","magenta","red","white","yellow"],ne=["bold","dim","italic","underline","reset"],Io={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},oe={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"},ie={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"},ko={"\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 zr(r){return(n)=>re?`${r}${n}${Io.reset}`:n}function ee(r){for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o<32&&o!==27)return!1}return!0}function yo({bright:r=!1,color:n}){let o=Bun.color(n,"ansi"),i=typeof o==="string"&&o.length>0&&ee(o)?o:oe[n];if(!i)return"";return r&&i in ko?ko[i]:i}var te=Lo.reduce((r,n)=>{let o=yo({color:n});if(o)r[n]=zr(o);let i=yo({bright:!0,color:n});if(i)r[`${n}Bright`]=zr(i);return r},{}),ae=ne.reduce((r,n)=>{return r[n]=zr(Io[n]),r},{}),se=Lo.reduce((r,n)=>{let o=ie[n];if(o){let i=`bg${n.charAt(0).toUpperCase()}${n.slice(1)}`;r[i]=zr(o)}return r},{}),p={...te,...ae,...se};function Wr(r){if(lr(r))throw new X;return r}function fe(r){return r.map((n)=>n.key?`${p.bold(n.key)} ${p.dim(n.text)}`:p.dim(n.text)).join(p.dim(" \xB7 "))}function Jr(r){w.info(fe(r))}var Ar={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 br(r){return Jr(Ar.confirm),Wr(await $o(r))}async function rr(r){return Jr(Ar.text),Wr(await Fo(r))}async function tr(r){return Jr(Ar.select),Wr(await Co({showInstructions:!1,...r}))}async function ar(r){return Jr(Ar.multiselect),Wr(await Po({showInstructions:!1,...r}))}var $={arg:p.magenta,cmd:p.cyan,default:p.blue,desc:p.white,flag:p.green,header:(r)=>p.bold(p.yellow(r)),hint:p.dim,name:(r)=>p.bold(p.cyan(r)),placeholder:p.magenta};class $n{metadata;commands;globalArgs;constructor(r,n,o){this.metadata=r;this.commands=n;this.globalArgs=o}version(){return`${$.name(this.metadata.name)} ${$.hint(this.metadata.version??"0.0.0")}`}global(){let r=[],{name:n,bin:o,version:i,description:e}=this.metadata;if(r.push(""),r.push(`${$.name(n)}${i?` ${$.hint(`v${i}`)}`:""}`),e)r.push($.desc(e));r.push(""),r.push($.header("Usage:")),r.push(` ${$.cmd(o)} ${$.placeholder("[command]")} ${$.hint("[options]")}`),r.push(""),r.push($.header("Commands:"));let t=Array.from(this.commands.values()).map((a)=>[` ${$.cmd(a.name)}`,$.desc(a.description)]);return r.push(...this.formatColumns(t)),r.push(""),r.push($.header("Options:")),r.push(...this.formatArgDefs(this.globalArgs)),r.push(""),r.push($.hint(`Run "${o} <command> --help" for command-specific options.`)),r.push(""),r.join(`
86
+ `}}}}).prompt();var ie=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Ro=["black","blue","cyan","gray","green","magenta","red","white","yellow"],ee=["bold","dim","italic","underline","reset"],Do={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},te={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"},ae={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"},Io={"\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 Wr(r){return(n)=>ie?`${r}${n}${Do.reset}`:n}function se(r){for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o<32&&o!==27)return!1}return!0}function Lo({bright:r=!1,color:n}){let o=Bun.color(n,"ansi"),i=typeof o==="string"&&o.length>0&&se(o)?o:te[n];if(!i)return"";return r&&i in Io?Io[i]:i}var ce=Ro.reduce((r,n)=>{let o=Lo({color:n});if(o)r[n]=Wr(o);let i=Lo({bright:!0,color:n});if(i)r[`${n}Bright`]=Wr(i);return r},{}),fe=ee.reduce((r,n)=>{return r[n]=Wr(Do[n]),r},{}),me=Ro.reduce((r,n)=>{let o=ae[n];if(o){let i=`bg${n.charAt(0).toUpperCase()}${n.slice(1)}`;r[i]=Wr(o)}return r},{}),p={...ce,...fe,...me};function Ar(r){if(lr(r))throw new X;return r}function pe(r){return r.map((n)=>n.key?`${p.bold(n.key)} ${p.dim(n.text)}`:p.dim(n.text)).join(p.dim(" \xB7 "))}function Jr(r){w.info(pe(r))}var xr={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 vr(r){return Jr(xr.confirm),Ar(await Co(r))}async function rr(r){return Jr(xr.text),Ar(await yo(r))}async function tr(r){return Jr(xr.select),Ar(await ko({showInstructions:!1,...r}))}async function ar(r){return Jr(xr.multiselect),Ar(await Fo({showInstructions:!1,...r}))}var $={arg:p.magenta,cmd:p.cyan,default:p.blue,desc:p.white,flag:p.green,header:(r)=>p.bold(p.yellow(r)),hint:p.dim,name:(r)=>p.bold(p.cyan(r)),placeholder:p.magenta};class Cn{metadata;commands;globalArgs;constructor(r,n,o){this.metadata=r;this.commands=n;this.globalArgs=o}version(){return`${$.name(this.metadata.name)} ${$.hint(this.metadata.version??"0.0.0")}`}global(){let r=[],{name:n,bin:o,version:i,description:e}=this.metadata;if(r.push(""),r.push(`${$.name(n)}${i?` ${$.hint(`v${i}`)}`:""}`),e)r.push($.desc(e));r.push(""),r.push($.header("Usage:")),r.push(` ${$.cmd(o)} ${$.placeholder("[command]")} ${$.hint("[options]")}`),r.push(""),r.push($.header("Commands:"));let t=Array.from(this.commands.values()).map((a)=>[` ${$.cmd(a.name)}`,$.desc(a.description)]);return r.push(...this.formatColumns(t)),r.push(""),r.push($.header("Options:")),r.push(...this.formatArgDefs(this.globalArgs)),r.push(""),r.push($.hint(`Run "${o} <command> --help" for command-specific options.`)),r.push(""),r.join(`
87
87
  `)}command(r,n){let o=[],i=n??this.metadata.bin,e=`${$.cmd(i)} ${$.cmd(r.name)}`;o.push(""),o.push(`${$.name(r.name)} ${$.hint("-")} ${$.desc(r.description)}`),o.push(""),o.push($.header("Usage:"));let t=this.formatPositionalUsage(r.positionals);if(r.hasSubcommands())o.push(` ${e} ${$.placeholder("<subcommand>")} ${$.hint("[options]")}`);else{let c=[e];if(t)c.push(t);c.push($.hint("[options]")),o.push(` ${c.join(" ")}`)}if(r.prompts)o.push(` ${e} ${$.hint("- runs interactively")}`);if(o.push(""),r.hasSubcommands()){o.push($.header("Subcommands:"));let c=r.getSubcommands().map((f)=>[` ${$.cmd(f.name)}`,$.desc(f.description)]);o.push(...this.formatColumns(c)),o.push("")}if(Object.entries(r.positionals).length>0)o.push($.header("Arguments:")),o.push(...this.formatPositionalDefs(r.positionals)),o.push("");if(Object.entries(r.args).length>0)o.push($.header("Options:")),o.push(...this.formatArgDefs(r.args)),o.push("");return o.join(`
88
- `)}formatPositionalUsage(r){return Object.entries(r).map(([n,o])=>{let i=o.variadic?`${n}...`:n;return o.required?$.arg(`<${i}>`):$.arg(`[${i}]`)}).join(" ")}formatPositionalDefs(r){let n=Object.entries(r).map(([o,i])=>{let e=i.variadic?`${o}...`:o,t=$.desc(i.description??""),a=i.required?"":$.hint(" (optional)");return[` ${$.arg(e)}`,`${t}${a}`]});return this.formatColumns(n)}formatArgDefs(r){let n=[];for(let[o,i]of Object.entries(r)){let t=`${i.alias?`${$.flag(`-${i.alias}`)}, `:" "}${$.flag(`--${o}`)}`,a=$.desc(i.description??""),s=i.default!==void 0?$.hint(` (default: ${$.default(this.formatDefault(i))})`):"";n.push([` ${t}`,`${a}${s}`])}return this.formatColumns(n)}formatDefault(r){if(r.type==="string")return`"${r.default}"`;return String(r.default)}formatColumns(r){if(r.length===0)return[];let n=Math.max(...r.map(([i])=>this.stripAnsi(i).length)),o=2;return r.map(([i,e])=>{let t=n-this.stripAnsi(i).length+o;return`${i}${" ".repeat(t)}${e}`})}stripAnsi(r){return r.replace(/\x1b\[[0-9;]*m/g,"")}}var nr=new Uint32Array(65536),me=(r,n)=>{let o=r.length,i=n.length,e=1<<o-1,t=-1,a=0,s=o,c=o;while(c--)nr[r.charCodeAt(c)]|=1<<c;for(c=0;c<i;c++){let f=nr[n.charCodeAt(c)],d=f|a;if(f|=(f&t)+t^t,a|=~(f|t),t&=f,a&e)s++;if(t&e)s--;a=a<<1|1,t=t<<1|~(d|a),a&=d}c=o;while(c--)nr[r.charCodeAt(c)]=0;return s},ue=(r,n)=>{let o=n.length,i=r.length,e=[],t=[],a=Math.ceil(o/32),s=Math.ceil(i/32);for(let l=0;l<a;l++)t[l]=-1,e[l]=0;let c=0;for(;c<s-1;c++){let l=0,b=-1,k=c*32,R=Math.min(32,i)+k;for(let C=k;C<R;C++)nr[r.charCodeAt(C)]|=1<<C;for(let C=0;C<o;C++){let N=nr[n.charCodeAt(C)],j=t[C/32|0]>>>C&1,F=e[C/32|0]>>>C&1,E=N|l,M=((N|F)&b)+b^b|N|F,L=l|~(M|b),H=b&M;if(L>>>31^j)t[C/32|0]^=1<<C;if(H>>>31^F)e[C/32|0]^=1<<C;L=L<<1|j,H=H<<1|F,b=H|~(E|L),l=L&E}for(let C=k;C<R;C++)nr[r.charCodeAt(C)]=0}let f=0,d=-1,g=c*32,u=Math.min(32,i-g)+g;for(let l=g;l<u;l++)nr[r.charCodeAt(l)]|=1<<l;let h=i;for(let l=0;l<o;l++){let b=nr[n.charCodeAt(l)],k=t[l/32|0]>>>l&1,R=e[l/32|0]>>>l&1,C=b|f,N=((b|R)&d)+d^d|b|R,j=f|~(N|d),F=d&N;if(h+=j>>>i-1&1,h-=F>>>i-1&1,j>>>31^k)t[l/32|0]^=1<<l;if(F>>>31^R)e[l/32|0]^=1<<l;j=j<<1|k,F=F<<1|R,d=F|~(C|j),f=j&C}for(let l=g;l<u;l++)nr[r.charCodeAt(l)]=0;return h},pe=(r,n)=>{if(r.length<n.length){let o=n;n=r,r=o}if(n.length===0)return r.length;if(r.length<=32)return me(r,n);return ue(r,n)},Do=(r,n)=>{let o=1/0,i=0;for(let e=0;e<n.length;e++){let t=pe(r,n[e]);if(t<o)o=t,i=e}return n[i]};function Kr(r,n,o,i){let e=Do(n,o);if(console.error(p.red(`Unknown ${r}: ${n}`)),e)console.error(p.yellow(`Did you mean "${e}"?`));console.error(`
89
- Run "${i} --help" for usage.`),process.exit(1)}function vr(r,n){let o=(e)=>e&&typeof e==="object";if(!o(r)||!o(n))return n;let i={...r};for(let e of Object.keys(n)){let t=i[e],a=n[e];if(Array.isArray(t)&&Array.isArray(a))i[e]=[...a];else if(o(t)&&o(a))i[e]=vr(t,a);else i[e]=a}return i}function Pn(r){return r==null?[]:Array.isArray(r)?r:[r]}function le(r,n,o,i){var e,t=r[n],a=~i.string.indexOf(n)?o==null||o===!0?"":String(o):typeof o==="boolean"?o:~i.boolean.indexOf(n)?o==="false"?!1:o==="true"||(r._.push((e=+o,e*0===0)?e:o),!!o):(e=+o,e*0===0)?e:o;r[n]=t==null?a:Array.isArray(t)?t.concat(a):[t,a]}function Yr(r,n){r=r||[],n=n||{};var o,i,e,t,a,s={_:[]},c=0,f=0,d=0,g=r.length;let u=n.alias!==void 0,h=n.unknown!==void 0,l=n.default!==void 0;if(n.alias=n.alias||{},n.string=Pn(n.string),n.boolean=Pn(n.boolean),u)for(o in n.alias){i=n.alias[o]=Pn(n.alias[o]);for(c=0;c<i.length;c++)(n.alias[i[c]]=i.concat(o)).splice(c,1)}for(c=n.boolean.length;c-- >0;){i=n.alias[n.boolean[c]]||[];for(f=i.length;f-- >0;)n.boolean.push(i[f])}for(c=n.string.length;c-- >0;){i=n.alias[n.string[c]]||[];for(f=i.length;f-- >0;)n.string.push(i[f])}if(l){for(o in n.default)if(t=typeof n.default[o],i=n.alias[o]=n.alias[o]||[],n[t]!==void 0){n[t].push(o);for(c=0;c<i.length;c++)n[t].push(i[c])}}let b=h?Object.keys(n.alias):[];for(c=0;c<g;c++){if(e=r[c],e==="--"){s._=s._.concat(r.slice(++c));break}for(f=0;f<e.length;f++)if(e.charCodeAt(f)!==45)break;if(f===0)s._.push(e);else if(e.substring(f,f+3)==="no-"){if(t=e.substring(f+3),h&&!~b.indexOf(t))return n.unknown(e);s[t]=!1}else{for(d=f+1;d<e.length;d++)if(e.charCodeAt(d)===61)break;t=e.substring(f,d),a=e.substring(++d)||(c+1===g||(""+r[c+1]).charCodeAt(0)===45||r[++c]),i=f===2?[t]:t;for(d=0;d<i.length;d++){if(t=i[d],h&&!~b.indexOf(t))return n.unknown("-".repeat(f)+t);le(s,t,d+1<i.length||a,n)}}}if(l){for(o in n.default)if(s[o]===void 0)s[o]=n.default[o]}if(u)for(o in s){i=n.alias[o]||[];while(i.length>0)s[i.shift()]=s[o]}return s}function de(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Ro(r){let n={alias:{},boolean:[],default:{},string:[]};for(let[o,i]of Object.entries(r)){if(i.type==="boolean")n.boolean.push(o);else n.string.push(o);if(i.alias)n.alias[i.alias]=o;let e=de(o);if(e!==o)n.alias[e]=o;if(i.default!==void 0)n.default[o]=i.default}return n}function jo(r,n){let o={...r};for(let[i,e]of Object.entries(n)){if(e.type!=="number")continue;let t=r[i];if(t===void 0||typeof t==="boolean")continue;let a=Number(t);if(Number.isNaN(a))throw Error(`Invalid number for --${i}: "${t}"`);o[i]=a}return o}function Mo(r,n){let o=Ro(n),i=Yr(r,o),e=i._[0],t=e?r.indexOf(e):-1,{_:a,...s}=i,c=jo(s,n);return{command:e,flags:c,restArgs:t>=0?r.slice(t+1):[]}}function Cn(r,n={}){let o=Ro(n),i=Yr(r,o),{_:e,...t}=i;return{args:jo(t,n),rawPositionals:e}}function Fn(r,n){let o={},i=Object.entries(n);for(let[e,[t,a]]of i.entries())o[t]=a.variadic?r.slice(e):r[e];return o}function Uo(r,n){for(let[o,i]of Object.entries(n)){if(!i.required)continue;let e=r[o];if(Array.isArray(e)?e.length===0:!e)return`Missing required argument: <${o}${i.variadic?"...":""}>`}return null}var kn="__exit__";class cr{command;env;prefix;options;constructor(r,n,o,i={}){this.command=r;this.env=n;this.prefix=o;this.options=i}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(r,n){if(n)await this.routeInteractive();else await this.routeDirect(r)}async routeDirect(r){let[n,...o]=r;if(n&&this.command.hasSubcommands()){let i=this.command.getSubcommand(n);if(i){await this.handleSubcommandRoute(i,o);return}if(!n.startsWith("-")){this.handleUnknownSubcommand(n);return}}await this.executeCommand(r)}handleUnknownSubcommand(r){let n=this.command.getSubcommands().map((o)=>o.name);Kr("subcommand",r,n,this.commandPath)}async handleSubcommandRoute(r,n){await new cr(r,this.env,this.commandPath).route(n,!1)}async executeCommand(r){if(this.isHelpRequest(r)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:o,rawPositionals:i}=Cn(r,this.command.args),e=Fn(i,this.command.positionals),t=Uo(e,this.command.positionals);if(t)w.error(t),console.error(`
90
- Run "${this.commandPath} --help" for usage.`),process.exit(1);let a=this.command.prompts&&i.length===0,s=this.buildContext(e,o,a);await this.command.execute(s)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:r}=Cn([],this.command.args),n=Fn([],this.command.positionals),o=this.buildContext(n,r,!0);await this.command.execute?.(o)}async runSubcommandMenu(){while(!0){let r=await this.promptSubcommandSelectionOrBack();if(r===null)return;if(r===kn){this.options.onExit?.();return}let n=this.command.getSubcommand(r);if(n)await this.executeSubcommand(n)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(r){if(r instanceof X){if(this.options.isRoot)this.options.onExit?.();return null}throw r}}async executeSubcommand(r){try{await new cr(r,this.env,this.commandPath).route([],!0)}catch(n){if(n instanceof X)return;if(n instanceof v){if(w.warn(p.yellow(n.message)),n.hint)w.info(p.dim(n.hint));return}throw n}}promptSubcommandSelection(){let{isRoot:r}=this.options,n=r?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:kn}:{hint:"Return to previous menu",label:"Back",value:kn};return tr({message:r?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((o)=>({hint:o.description,label:o.name,value:o.name})),n]})}buildContext(r,n,o){return{...this.env,args:n,interactive:o,positionals:r}}isHelpRequest(r){return r.includes("--help")||r.includes("-h")}printHelp(r){let n=r===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(r,n))}}var ge={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class yn{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Enable interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(r,n){this.configManager=r,this.metadata={...ge,...n},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new $n({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(r){for(let n of r)n.init?.(),this.commands.set(n.name,n)}async run(r=process.argv.slice(2)){let{command:n,flags:o,restArgs:i}=Mo(r,this.globalArgs);if(o.version&&!n)return console.log(this.help.version());if(o.interactive&&!n)return this.runInteractive();if(!n)return console.log(this.help.global());if(n==="help")return this.printHelpFor(i[0]);await this.runDirect(n,i,!!o.help)}printHelpFor(r){if(!r)return console.log(this.help.global());let n=this.commands.get(r);if(!n)return this.handleUnknownCommand(r);console.log(this.help.command(n))}async runInteractive(){this.showIntro();let r=this.createVirtualRootCommand(),n={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},o=new cr(r,n,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await o.route([],!0)}catch(i){this.handleError(i)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(r)=>this.commands.get(r),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){Gr(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(r,n,o){let i=this.commands.get(r);if(!i)return this.handleUnknownCommand(r);let e=n.length>0&&!n[0]?.startsWith("-");if(o&&!e)return console.log(this.help.command(i));try{let t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new cr(i,t,this.bin).route(n,!1)}catch(t){this.handleError(t)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let r=this.metadata.version?` v${this.metadata.version}`:"";qr(`${p.bgCyan(p.black(` ${this.metadata.name}${r} `))}`)}handleUnknownCommand(r){let n=Array.from(this.commands.keys());Kr("command",r,n,this.bin)}handleError(r){if(this.metadata.onError?.(r))return;if(r instanceof X)process.exit(0);if(r instanceof v){if(w.warn(p.yellow(r.message)),r.hint)w.info(p.dim(r.hint));process.exit(0)}if(r instanceof Error)w.error(p.red(r.message)),process.exit(1);console.error(p.red("Error:"),r),process.exit(1)}}class wr{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(r){for(let n of r)n.init?.(),this.subcommands.set(n.name,n)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(r){return this.subcommands.get(r)}getSubcommands(){return Array.from(this.subcommands.values())}}function fr(r){return r}function G(r){return r}import mr from"fs";import Ho from"path";class Ln{config;configPath;defaultConfig;constructor(r,n){this.configPath=Ho.resolve(r),this.defaultConfig=n,this.config=this.loadConfig()}get(r){return this.config[r]}set(r,n){this.config[r]=n,this.save()}delete(r){delete this.config[r],this.save()}exists(){return mr.existsSync(this.configPath)}getAll(){return vr({},this.config)}save(r){if(r)this.config={...r};this.ensureDirectoryExists();try{mr.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(n){console.error(`Failed to save config to ${this.configPath}:`,n)}}ensureDirectoryExists(){let r=Ho.dirname(this.configPath);if(!mr.existsSync(r))try{mr.mkdirSync(r,{recursive:!0})}catch(n){console.error(`Failed to create config directory at ${r}:`,n)}}loadConfig(){if(!mr.existsSync(this.configPath))return{...this.defaultConfig};try{let r=mr.readFileSync(this.configPath,"utf-8"),n=JSON.parse(r);return vr({...this.defaultConfig},n)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var Eo="0.6.0";import{join as De}from"path";class I extends wr{}import{existsSync as Fr}from"fs";import{cp as Ce,link as Fe,mkdir as Un,readdir as Ko,readFile as Hn,readlink as ke,rm as En,symlink as ye,unlink as Yo,writeFile as Le}from"fs/promises";import{join as D,resolve as xr}from"path";var Zr="hydra";var No=".hydra/config.json",$r=".hydra/shared",Pr=".hydra/runners",Cr="default",qo={profiles:{}};import{existsSync as be}from"fs";import{readdir as ve,stat as we}from"fs/promises";import{join as $e}from"path";var In="_diag",Go={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},zo=1024,Wo=["B","KB","MB","GB"],Pe=1;function Jo(r){if(Go.worker.test(r))return"worker";if(Go.runner.test(r))return"runner";return null}function Ao(r){return[...r].sort((n,o)=>o.mtime.getTime()-n.mtime.getTime())}async function Dn(r){if(!be(r))return[];let n=await ve(r,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isFile())continue;let e=Jo(i.name);if(!e)continue;let t=$e(r,i.name),a=await we(t);o.push({mtime:a.mtime,name:i.name,path:t,size:a.size,type:e})}return Ao(o)}function Rn(r,n){let o=r.find((e)=>e.type===n);if(o)return{fallback:!1,file:o};let i=r[0];return i?{fallback:!0,file:i}:null}function jn(r,n){if(n<=0)return"";let o=r.endsWith(`
88
+ `)}formatPositionalUsage(r){return Object.entries(r).map(([n,o])=>{let i=o.variadic?`${n}...`:n;return o.required?$.arg(`<${i}>`):$.arg(`[${i}]`)}).join(" ")}formatPositionalDefs(r){let n=Object.entries(r).map(([o,i])=>{let e=i.variadic?`${o}...`:o,t=$.desc(i.description??""),a=i.required?"":$.hint(" (optional)");return[` ${$.arg(e)}`,`${t}${a}`]});return this.formatColumns(n)}formatArgDefs(r){let n=[];for(let[o,i]of Object.entries(r)){let t=`${i.alias?`${$.flag(`-${i.alias}`)}, `:" "}${$.flag(`--${o}`)}`,a=$.desc(i.description??""),s=i.default!==void 0?$.hint(` (default: ${$.default(this.formatDefault(i))})`):"";n.push([` ${t}`,`${a}${s}`])}return this.formatColumns(n)}formatDefault(r){if(r.type==="string")return`"${r.default}"`;return String(r.default)}formatColumns(r){if(r.length===0)return[];let n=Math.max(...r.map(([i])=>this.stripAnsi(i).length)),o=2;return r.map(([i,e])=>{let t=n-this.stripAnsi(i).length+o;return`${i}${" ".repeat(t)}${e}`})}stripAnsi(r){return r.replace(/\x1b\[[0-9;]*m/g,"")}}var nr=new Uint32Array(65536),de=(r,n)=>{let o=r.length,i=n.length,e=1<<o-1,t=-1,a=0,s=o,c=o;while(c--)nr[r.charCodeAt(c)]|=1<<c;for(c=0;c<i;c++){let f=nr[n.charCodeAt(c)],l=f|a;if(f|=(f&t)+t^t,a|=~(f|t),t&=f,a&e)s++;if(t&e)s--;a=a<<1|1,t=t<<1|~(l|a),a&=l}c=o;while(c--)nr[r.charCodeAt(c)]=0;return s},le=(r,n)=>{let o=n.length,i=r.length,e=[],t=[],a=Math.ceil(o/32),s=Math.ceil(i/32);for(let d=0;d<a;d++)t[d]=-1,e[d]=0;let c=0;for(;c<s-1;c++){let d=0,b=-1,k=c*32,D=Math.min(32,i)+k;for(let C=k;C<D;C++)nr[r.charCodeAt(C)]|=1<<C;for(let C=0;C<o;C++){let G=nr[n.charCodeAt(C)],H=t[C/32|0]>>>C&1,F=e[C/32|0]>>>C&1,U=G|d,j=((G|F)&b)+b^b|G|F,I=d|~(j|b),M=b&j;if(I>>>31^H)t[C/32|0]^=1<<C;if(M>>>31^F)e[C/32|0]^=1<<C;I=I<<1|H,M=M<<1|F,b=M|~(U|I),d=I&U}for(let C=k;C<D;C++)nr[r.charCodeAt(C)]=0}let f=0,l=-1,g=c*32,u=Math.min(32,i-g)+g;for(let d=g;d<u;d++)nr[r.charCodeAt(d)]|=1<<d;let h=i;for(let d=0;d<o;d++){let b=nr[n.charCodeAt(d)],k=t[d/32|0]>>>d&1,D=e[d/32|0]>>>d&1,C=b|f,G=((b|D)&l)+l^l|b|D,H=f|~(G|l),F=l&G;if(h+=H>>>i-1&1,h-=F>>>i-1&1,H>>>31^k)t[d/32|0]^=1<<d;if(F>>>31^D)e[d/32|0]^=1<<d;H=H<<1|k,F=F<<1|D,l=F|~(C|H),f=H&C}for(let d=g;d<u;d++)nr[r.charCodeAt(d)]=0;return h},ge=(r,n)=>{if(r.length<n.length){let o=n;n=r,r=o}if(n.length===0)return r.length;if(r.length<=32)return de(r,n);return le(r,n)},Ho=(r,n)=>{let o=1/0,i=0;for(let e=0;e<n.length;e++){let t=ge(r,n[e]);if(t<o)o=t,i=e}return n[i]};function Kr(r,n,o,i){let e=Ho(n,o);if(console.error(p.red(`Unknown ${r}: ${n}`)),e)console.error(p.yellow(`Did you mean "${e}"?`));console.error(`
89
+ Run "${i} --help" for usage.`),process.exit(1)}function wr(r,n){let o=(e)=>e&&typeof e==="object";if(!o(r)||!o(n))return n;let i={...r};for(let e of Object.keys(n)){let t=i[e],a=n[e];if(Array.isArray(t)&&Array.isArray(a))i[e]=[...a];else if(o(t)&&o(a))i[e]=wr(t,a);else i[e]=a}return i}function Fn(r){return r==null?[]:Array.isArray(r)?r:[r]}function he(r,n,o,i){var e,t=r[n],a=~i.string.indexOf(n)?o==null||o===!0?"":String(o):typeof o==="boolean"?o:~i.boolean.indexOf(n)?o==="false"?!1:o==="true"||(r._.push((e=+o,e*0===0)?e:o),!!o):(e=+o,e*0===0)?e:o;r[n]=t==null?a:Array.isArray(t)?t.concat(a):[t,a]}function Yr(r,n){r=r||[],n=n||{};var o,i,e,t,a,s={_:[]},c=0,f=0,l=0,g=r.length;let u=n.alias!==void 0,h=n.unknown!==void 0,d=n.default!==void 0;if(n.alias=n.alias||{},n.string=Fn(n.string),n.boolean=Fn(n.boolean),u)for(o in n.alias){i=n.alias[o]=Fn(n.alias[o]);for(c=0;c<i.length;c++)(n.alias[i[c]]=i.concat(o)).splice(c,1)}for(c=n.boolean.length;c-- >0;){i=n.alias[n.boolean[c]]||[];for(f=i.length;f-- >0;)n.boolean.push(i[f])}for(c=n.string.length;c-- >0;){i=n.alias[n.string[c]]||[];for(f=i.length;f-- >0;)n.string.push(i[f])}if(d){for(o in n.default)if(t=typeof n.default[o],i=n.alias[o]=n.alias[o]||[],n[t]!==void 0){n[t].push(o);for(c=0;c<i.length;c++)n[t].push(i[c])}}let b=h?Object.keys(n.alias):[];for(c=0;c<g;c++){if(e=r[c],e==="--"){s._=s._.concat(r.slice(++c));break}for(f=0;f<e.length;f++)if(e.charCodeAt(f)!==45)break;if(f===0)s._.push(e);else if(e.substring(f,f+3)==="no-"){if(t=e.substring(f+3),h&&!~b.indexOf(t))return n.unknown(e);s[t]=!1}else{for(l=f+1;l<e.length;l++)if(e.charCodeAt(l)===61)break;t=e.substring(f,l),a=e.substring(++l)||(c+1===g||(""+r[c+1]).charCodeAt(0)===45||r[++c]),i=f===2?[t]:t;for(l=0;l<i.length;l++){if(t=i[l],h&&!~b.indexOf(t))return n.unknown("-".repeat(f)+t);he(s,t,l+1<i.length||a,n)}}}if(d){for(o in n.default)if(s[o]===void 0)s[o]=n.default[o]}if(u)for(o in s){i=n.alias[o]||[];while(i.length>0)s[i.shift()]=s[o]}return s}function be(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function jo(r){let n={alias:{},boolean:[],default:{},string:[]};for(let[o,i]of Object.entries(r)){if(i.type==="boolean")n.boolean.push(o);else n.string.push(o);if(i.alias)n.alias[i.alias]=o;let e=be(o);if(e!==o)n.alias[e]=o;if(i.default!==void 0)n.default[o]=i.default}return n}function Eo(r,n){let o={...r};for(let[i,e]of Object.entries(n)){if(e.type!=="number")continue;let t=r[i];if(t===void 0||typeof t==="boolean")continue;let a=Number(t);if(Number.isNaN(a))throw Error(`Invalid number for --${i}: "${t}"`);o[i]=a}return o}function Mo(r,n){let o=jo(n),i=Yr(r,o),e=i._[0],t=e?r.indexOf(e):-1,{_:a,...s}=i,c=Eo(s,n);return{command:e,flags:c,restArgs:t>=0?r.slice(t+1):[]}}function kn(r,n={}){let o=jo(n),i=Yr(r,o),{_:e,...t}=i;return{args:Eo(t,n),rawPositionals:e}}function yn(r,n){let o={},i=Object.entries(n);for(let[e,[t,a]]of i.entries())o[t]=a.variadic?r.slice(e):r[e];return o}function Uo(r,n){for(let[o,i]of Object.entries(n)){if(!i.required)continue;let e=r[o];if(Array.isArray(e)?e.length===0:!e)return`Missing required argument: <${o}${i.variadic?"...":""}>`}return null}var In="__exit__";class fr{command;env;prefix;options;constructor(r,n,o,i={}){this.command=r;this.env=n;this.prefix=o;this.options=i}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(r,n){if(n)await this.routeInteractive();else await this.routeDirect(r)}async routeDirect(r){let[n,...o]=r;if(n&&this.command.hasSubcommands()){let i=this.command.getSubcommand(n);if(i){await this.handleSubcommandRoute(i,o);return}if(!n.startsWith("-")){this.handleUnknownSubcommand(n);return}}await this.executeCommand(r)}handleUnknownSubcommand(r){let n=this.command.getSubcommands().map((o)=>o.name);Kr("subcommand",r,n,this.commandPath)}async handleSubcommandRoute(r,n){await new fr(r,this.env,this.commandPath).route(n,!1)}async executeCommand(r){if(this.isHelpRequest(r)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:o,rawPositionals:i}=kn(r,this.command.args),e=yn(i,this.command.positionals),t=Uo(e,this.command.positionals);if(t)w.error(t),console.error(`
90
+ Run "${this.commandPath} --help" for usage.`),process.exit(1);let a=this.command.prompts&&i.length===0,s=this.buildContext(e,o,a);await this.command.execute(s)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:r}=kn([],this.command.args),n=yn([],this.command.positionals),o=this.buildContext(n,r,!0);await this.command.execute?.(o)}async runSubcommandMenu(){while(!0){let r=await this.promptSubcommandSelectionOrBack();if(r===null)return;if(r===In){this.options.onExit?.();return}let n=this.command.getSubcommand(r);if(n)await this.executeSubcommand(n)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(r){if(r instanceof X){if(this.options.isRoot)this.options.onExit?.();return null}throw r}}async executeSubcommand(r){try{await new fr(r,this.env,this.commandPath).route([],!0)}catch(n){if(n instanceof X)return;if(n instanceof v){if(w.warn(p.yellow(n.message)),n.hint)w.info(p.dim(n.hint));return}throw n}}promptSubcommandSelection(){let{isRoot:r}=this.options,n=r?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:In}:{hint:"Return to previous menu",label:"Back",value:In};return tr({message:r?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((o)=>({hint:o.description,label:o.name,value:o.name})),n]})}buildContext(r,n,o){return{...this.env,args:n,interactive:o,positionals:r}}isHelpRequest(r){return r.includes("--help")||r.includes("-h")}printHelp(r){let n=r===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(r,n))}}var ve={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Ln{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Enable interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(r,n){this.configManager=r,this.metadata={...ve,...n},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Cn({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(r){for(let n of r)n.init?.(),this.commands.set(n.name,n)}async run(r=process.argv.slice(2)){let{command:n,flags:o,restArgs:i}=Mo(r,this.globalArgs);if(o.version&&!n)return console.log(this.help.version());if(o.interactive&&!n)return this.runInteractive();if(!n)return console.log(this.help.global());if(n==="help")return this.printHelpFor(i[0]);await this.runDirect(n,i,!!o.help)}printHelpFor(r){if(!r)return console.log(this.help.global());let n=this.commands.get(r);if(!n)return this.handleUnknownCommand(r);console.log(this.help.command(n))}async runInteractive(){this.showIntro();let r=this.createVirtualRootCommand(),n={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},o=new fr(r,n,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await o.route([],!0)}catch(i){this.handleError(i)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(r)=>this.commands.get(r),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){zr(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(r,n,o){let i=this.commands.get(r);if(!i)return this.handleUnknownCommand(r);let e=n.length>0&&!n[0]?.startsWith("-");if(o&&!e)return console.log(this.help.command(i));try{let t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new fr(i,t,this.bin).route(n,!1)}catch(t){this.handleError(t)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let r=this.metadata.version?` v${this.metadata.version}`:"";qr(`${p.bgCyan(p.black(` ${this.metadata.name}${r} `))}`)}handleUnknownCommand(r){let n=Array.from(this.commands.keys());Kr("command",r,n,this.bin)}handleError(r){if(this.metadata.onError?.(r))return;if(r instanceof X)process.exit(0);if(r instanceof v){if(w.warn(p.yellow(r.message)),r.hint)w.info(p.dim(r.hint));process.exit(0)}if(r instanceof Error)w.error(p.red(r.message)),process.exit(1);console.error(p.red("Error:"),r),process.exit(1)}}class $r{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(r){for(let n of r)n.init?.(),this.subcommands.set(n.name,n)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(r){return this.subcommands.get(r)}getSubcommands(){return Array.from(this.subcommands.values())}}function mr(r){return r}function q(r){return r}import ur from"fs";import Go from"path";class Rn{config;configPath;defaultConfig;constructor(r,n){this.configPath=Go.resolve(r),this.defaultConfig=n,this.config=this.loadConfig()}get(r){return this.config[r]}set(r,n){this.config[r]=n,this.save()}delete(r){delete this.config[r],this.save()}exists(){return ur.existsSync(this.configPath)}getAll(){return wr({},this.config)}save(r){if(r)this.config={...r};this.ensureDirectoryExists();try{ur.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(n){console.error(`Failed to save config to ${this.configPath}:`,n)}}ensureDirectoryExists(){let r=Go.dirname(this.configPath);if(!ur.existsSync(r))try{ur.mkdirSync(r,{recursive:!0})}catch(n){console.error(`Failed to create config directory at ${r}:`,n)}}loadConfig(){if(!ur.existsSync(this.configPath))return{...this.defaultConfig};try{let r=ur.readFileSync(this.configPath,"utf-8"),n=JSON.parse(r);return wr({...this.defaultConfig},n)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var No="0.7.0";import{join as Ee}from"path";class L extends $r{}import{existsSync as kr}from"fs";import{cp as Ie,link as Le,mkdir as Un,readdir as Zo,readFile as Gn,readlink as Re,rm as Nn,symlink as De,unlink as Qo,writeFile as He}from"fs/promises";import{join as R,resolve as Xr}from"path";var Zr="hydra";var qo=".hydra/config.json",Pr=".hydra/shared",Cr=".hydra/runners",Fr="default",zo={profiles:{}};var $e=new Set(["github.com","www.github.com"]);var Wo=/\.git$/;function sr(r){let n;try{n=new URL(r)}catch{throw Error(`Invalid GitHub URL: ${r}`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${r}`);if(!$e.has(n.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${r}`);let o=n.pathname.split("/").filter(Boolean);if(o.length===1){let i=o[0]?.replace(Wo,"");if(!i)throw Error(`Invalid GitHub URL: ${r}`);return{kind:"org",org:i}}if(o.length===2){let i=o[0],e=o[1]?.replace(Wo,"");if(!i||!e)throw Error(`Invalid GitHub URL: ${r}`);return{kind:"repo",owner:i,repo:e}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${r}`)}function Qr(r){return r.kind==="repo"?`${r.owner}/${r.repo}`:r.org}import{existsSync as Pe}from"fs";import{readdir as Ce,stat as Fe}from"fs/promises";import{join as ke}from"path";var Dn="_diag",Ao={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},Jo=1024,xo=["B","KB","MB","GB"],ye=1;function Ko(r){if(Ao.worker.test(r))return"worker";if(Ao.runner.test(r))return"runner";return null}function Yo(r){return[...r].sort((n,o)=>o.mtime.getTime()-n.mtime.getTime())}async function Hn(r){if(!Pe(r))return[];let n=await Ce(r,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isFile())continue;let e=Ko(i.name);if(!e)continue;let t=ke(r,i.name),a=await Fe(t);o.push({mtime:a.mtime,name:i.name,path:t,size:a.size,type:e})}return Yo(o)}function jn(r,n){let o=r.find((e)=>e.type===n);if(o)return{fallback:!1,file:o};let i=r[0];return i?{fallback:!0,file:i}:null}function En(r,n){if(n<=0)return"";let o=r.endsWith(`
91
91
  `)?r.slice(0,-1):r;if(o==="")return"";return o.split(`
92
92
  `).slice(-n).join(`
93
- `)}function Mn(r){let n=r,o=0;while(n>=zo&&o<Wo.length-1)n/=zo,o++;return`${o===0?String(n):n.toFixed(Pe)} ${Wo[o]??"B"}`}var Zo="actions/runner",Ie={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},xo=["bin"],Qo=["externals"];class Qr{profile;sharedPath=null;constructor(r){this.profile=r}async download(){let r=Ie[this.profile.os],n=await this.getLatestVersion(),o=D($r,"github",n);if(Fr(o))return this.sharedPath=o,{path:o,version:n};await Un(o,{recursive:!0});let i=`actions-runner-${r}-${n}.tar.gz`,e=D(o,i),t=`https://github.com/${Zo}/releases/download/v${n}/${i}`;return await Bun.$`curl -sL -o ${e} ${t}`,await Bun.$`tar xzf ${e} -C ${o}`,await Yo(e),this.sharedPath=o,{path:o,version:n}}async create(r){let n=await this.ensureDownloaded(),o=[];for(let i of r){let e=D(this.profile.directory,i);await this.setupRunnerDir(n,e),await this.registerRunner(e,i),o.push({directory:e,id:i,name:i,status:"registered"})}return o}async remove(r){for(let n of r){let o=D(this.profile.directory,n);if(!Fr(D(o,".runner")))continue;let i=await this.fetchRemovalToken(o);await Bun.$`bash ./config.sh remove --token ${i}`.cwd(o).quiet().nothrow()}}async start(r){for(let n of r){let o=D(this.profile.directory,n),i=await this.readPidFile(o);if(i&&this.isProcessRunning(i))continue;let e=Bun.spawn(["bash","./run.sh"],{cwd:xr(o),stderr:"pipe",stdout:"pipe"});e.unref(),await this.writePidFile(o,e.pid)}}async stop(r){for(let n of r){let o=D(this.profile.directory,n);if(!await this.readPidFile(o))continue;let e=xr(o);await Bun.$`pkill -f ${e}`.quiet().nothrow(),await this.removePidFile(o)}}async list(){let r=this.profile.directory;if(!Fr(r))return[];let n=await Ko(r,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory())continue;let e=D(r,i.name);o.push(await this.getRunnerStatus(e,i.name))}return o}async currentVersion(r){let n=D(this.profile.directory,r);return this.detectVersion(n)}async logFiles(r){return Dn(D(this.profile.directory,r,In))}async update(r){let n=await this.ensureDownloaded();for(let o of r){let i=D(this.profile.directory,o);await this.removeRunnerBinaries(i),await this.setupRunnerDir(n,i)}}async getRunnerStatus(r,n){let o=await this.readRunnerName(r),i=await this.readPidFile(r),e=i!==null&&this.isProcessRunning(i),t="unknown";if(e)t="running";else if(Fr(D(r,".runner")))t="registered";return{directory:r,id:n,name:o,pid:e?i:void 0,status:t}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:r}=await this.download();return r}async setupRunnerDir(r,n){await Un(n,{recursive:!0});for(let o of xo)await this.hardLinkDir(D(r,o),D(n,o));for(let o of Qo){let i=xr(r,o),e=D(n,o);if(!Fr(e))await ye(i,e)}for(let o of["*.sh","*.sh.template"]){let i=await Array.fromAsync(new Bun.Glob(o).scan(r));for(let e of i)await Ce(D(r,e),D(n,e))}}async registerRunner(r,n){let o=await this.fetchRegistrationToken(),i=["--url",this.profile.url,"--token",o,"--name",n,"--unattended"];if(this.profile.labels)i.push("--labels",this.profile.labels);if(this.profile.runnerGroup)i.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${i}`.cwd(r).quiet()}async fetchRegistrationToken(){let{owner:r,repo:n}=this.parseUrl(this.profile.url),i=(await Bun.$`gh api repos/${r}/${n}/actions/runners/registration-token --method POST --jq .token`.quiet()).stdout.toString().trim();if(!i)throw Error(`Failed to fetch registration token for ${r}/${n}`);return i}async fetchRemovalToken(r){let n=await Hn(D(r,".runner"),"utf-8"),i=JSON.parse(this.stripBom(n)).gitHubUrl;if(!i)throw Error("Cannot determine GitHub URL from runner config");let{owner:e,repo:t}=this.parseUrl(i);return(await Bun.$`gh api repos/${e}/${t}/actions/runners/remove-token --method POST --jq .token`.quiet()).stdout.toString().trim()}async getLatestVersion(){return(await Bun.$`gh api repos/${Zo}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}parseUrl(r){let n=r.match(/github\.com\/([^/]+)\/([^/.]+)/);if(!n?.[1]||!n[2])throw Error(`Invalid GitHub URL: ${r}`);return{owner:n[1],repo:n[2]}}pidFilePath(r){return xr(r,".pid")}async writePidFile(r,n){await Le(this.pidFilePath(r),String(n))}async readPidFile(r){try{let n=await Hn(this.pidFilePath(r),"utf-8");return Number.parseInt(n.trim(),10)}catch{return null}}async removePidFile(r){try{await Yo(this.pidFilePath(r))}catch{}}async readRunnerName(r){try{let n=await Hn(D(r,".runner"),"utf-8");return JSON.parse(this.stripBom(n)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(r,n){await Un(n,{recursive:!0});let o=await Ko(r,{withFileTypes:!0});for(let i of o){let e=D(r,i.name),t=D(n,i.name);if(i.isDirectory())await this.hardLinkDir(e,t);else await Fe(e,t)}}async detectVersion(r){try{return(await ke(D(r,"externals"))).match(/github\/([^/]+)/)?.[1]??null}catch{return null}}async removeRunnerBinaries(r){for(let n of xo)await En(D(r,n),{force:!0,recursive:!0});for(let n of Qo)await En(D(r,n),{force:!0});for(let n of["*.sh","*.sh.template"]){let o=await Array.fromAsync(new Bun.Glob(n).scan(r));for(let i of o)await En(D(r,i),{force:!0})}}stripBom(r){return r.replace(/^\uFEFF/,"")}isProcessRunning(r){try{return process.kill(r,0),!0}catch{return!1}}}function z(r){switch(r.provider){case"github":return new Qr(r);default:throw Error(`Runner provider "${r.provider}" is not yet implemented`)}}function ur(r,n){if(r.length===0)return n;for(let o of r)if(!n.includes(o))throw new v(`Runner "${o}" not found`);return r}function J(r,n){let o=r.get("profiles");if(Object.keys(o).length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=n??r.get("defaultProfile")??Cr,e=o[i];if(!e)throw new v(`Profile "${i}" not found`);return{name:i,profile:e}}async function Q(r){let n=r.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");if(o.length===1)return o[0];return tr({message:"Select profile",options:o.map((i)=>({label:i,value:i,hint:n[i]?.url}))})}var Re=G({profile:{description:"Profile name"},count:{description:"Number of runners to create (overrides profile)"}});class Xr extends I{name="create";description="Create and register runners";positionals=Re;async execute(r){let{name:n,profile:o}=r.interactive?J(r.config,await Q(r.config)):J(r.config,r.positionals.profile),i=r.interactive?await this.promptCount(o.numberOfMachines):r.positionals.count?Number.parseInt(r.positionals.count,10):o.numberOfMachines;if(!i||i<1)throw new v("Runner count must be at least 1");let e=z(o),t=Y();t.start("Downloading runner binary...");let{version:a}=await e.download();t.stop(`Runner v${a} ready`);let s=r.config.get("runners")??[],c=s.filter((l)=>l.profile===n),f=i-c.length;if(f<=0){w.warn(`Already have ${c.length} runner(s) for profile "${n}". Nothing to create.`);return}let d=new Set(s.map((l)=>l.id)),g=1;for(let l=0;l<f;){let b=`${o.name}-${g++}`;if(d.has(b))continue;l++,t.start(`Registering ${b}...`),await e.create([b]),t.stop(`${p.green("+")} ${b}`),s.push({createdAt:new Date().toISOString(),directory:De(o.directory,b),id:b,name:b,profile:n,provider:o.provider,url:o.url})}r.config.set("runners",s);let h=n===r.config.get("defaultProfile")?"":` ${n}`;w.info(`${p.green("Created")} ${f} runner(s) for "${n}". Run ${p.green(`hydra start${h}`)} to start them.`)}async promptCount(r){let n=await rr({initialValue:String(r),message:"Number of runners to create",validate:(o)=>{let i=Number.parseInt(o??"",10);if(Number.isNaN(i)||i<1)return"Must be a positive number";return}});return Number.parseInt(n,10)}}import{existsSync as Xo}from"fs";import{mkdir as Vo}from"fs/promises";var je=G({url:{description:"GitHub repository or organization URL"}}),Me=fr({force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},labels:{alias:"l",description:"Comma-separated runner labels",type:"string"},name:{alias:"n",description:"Base name for runners",type:"string"},profile:{alias:"p",description:"Profile name",type:"string"},runners:{alias:"c",description:"Number of runners to create",type:"number"}});class Vr extends I{name="init";description="Initialize Hydra runner manager";positionals=je;args=Me;prompts=!0;async execute(r){let n=r.interactive?await this.promptProfileName(r):r.args.profile??Cr,o=!r.config.exists();if(!o&&r.config.get("profiles")[n]&&!r.args.force){if(!r.interactive)throw new v(`Profile "${n}" already exists. Use --force to overwrite.`);if(!await br({initialValue:!1,message:`Profile "${n}" already exists. Overwrite?`}))return}await this.ensureDirectories();let e=r.interactive?await this.runInitForm():this.buildProfileFromArgs(r),t=o?{}:{...r.config.get("profiles")};if(t[n]=e,r.config.set("profiles",t),!r.config.get("defaultProfile"))r.config.set("defaultProfile",n);sr([`${p.dim("Profile:")} ${n}`,`${p.dim("URL:")} ${e.url}`,`${p.dim("Runners:")} ${e.numberOfMachines}`,`${p.dim("Name:")} ${e.name}`,e.labels?`${p.dim("Labels:")} ${e.labels}`:"","",`Run ${p.green(`${Zr} create${n!==r.config.get("defaultProfile")?` ${n}`:""}`)} to provision runners.`].filter(Boolean).join(`
94
- `),p.green(o?"Hydra initialized":`Profile "${n}" added`))}async promptProfileName(r){return rr({initialValue:r.args.profile??Cr,message:"Profile name"})}async ensureDirectories(){if(!Xo($r))await Vo($r,{recursive:!0});if(!Xo(Pr))await Vo(Pr,{recursive:!0})}async runInitForm(){let r=await Nr({url:()=>rr({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{new URL(n)}catch{return"Must be a valid URL"}return}}),name:()=>rr({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>rr({initialValue:"1",message:"Number of runners",placeholder:"1",validate:(n)=>{if(!n)return"Must be a positive number";let o=Number.parseInt(n,10);if(Number.isNaN(o)||o<1)return"Must be a positive number";return}}),labels:()=>rr({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new X}});return{directory:Pr,labels:r.labels||void 0,name:r.name,numberOfMachines:Number.parseInt(r.runners,10)||1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.url}}buildProfileFromArgs(r){if(!r.positionals.url)throw new v("URL is required","Usage: hydra init <url>");return this.validateUrl(r.positionals.url),this.validateRunnerCount(r.args.runners),{directory:Pr,labels:r.args.labels,name:r.args.name??"runner",numberOfMachines:r.args.runners??1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.positionals.url}}validateUrl(r){try{new URL(r)}catch{throw new v(`Invalid URL: ${r}`)}}validateRunnerCount(r){if(r!==void 0&&r<1)throw new v("Runner count must be at least 1")}detectOs(){let r=process.platform;if(r==="darwin")return"osx";if(r==="win32")return"windows";return"linux"}}import{existsSync as Ue}from"fs";import{readFile as He}from"fs/promises";var Ee=100,Ne={runner:"runner daemon log",worker:"job log"},qe=fr({lines:{alias:"n",default:Ee,description:"Number of lines to tail",type:"number"},list:{alias:"l",default:!1,description:"List available log files instead of printing content",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file in $EDITOR instead of printing",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner daemon log instead of the latest job log",type:"boolean"}}),Ge=G({id:{description:"Runner ID"}});class Or extends I{name="logs";description="Inspect logs of the latest jobs";args=qe;positionals=Ge;async execute(r){let n=r.config.get("runners")??[];if(n.length===0)throw new v("No runners found","Run hydra create to provision runners");let o=await this.resolveEntry(r,n),i=r.config.get("profiles")[o.profile];if(!i)throw new v(`Profile "${o.profile}" not found for runner "${o.id}"`,"Run hydra init to set it up");if(!Ue(o.directory))throw new v(`Runner directory not found: ${o.directory}`,"Run hydra create to provision this runner");let t=await z(i).logFiles(o.id);if(t.length===0)this.noLogs(o.id);if(r.args.list){this.printList(o,t);return}let a=this.selectFile(r,o,t);if(r.args.open){await this.openFile(a);return}await this.printTail(o,a,r.args.lines)}async resolveEntry(r,n){let o=r.positionals.id;if(o){let e=n.find((t)=>t.id===o);if(!e)throw new v(`Runner "${o}" not found`,`Known runners: ${n.map((t)=>t.id).join(", ")}`);return e}if(r.interactive)return tr({message:"Select runner",options:n.map((e)=>({hint:e.profile,label:e.name,value:e}))});let i=n[0];if(n.length===1&&i)return i;throw new v("Multiple runners found",`Pass a runner id: hydra logs <id> (${n.map((e)=>e.id).join(", ")})`)}selectFile(r,n,o){if(r.args.runner){let e=o.find((t)=>t.type==="runner");if(!e)throw new v(`No runner daemon logs found for "${n.id}"`,"Start the runner first: hydra start");return e}let i=Rn(o,"worker");if(!i)this.noLogs(n.id);if(i.fallback)w.warn(p.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return i.file}noLogs(r){throw new v(`No logs found for runner "${r}"`,"Logs appear once the runner has started; run hydra start")}printList(r,n){let o=[`${p.bold(r.name)} ${p.dim(r.directory)}`];for(let i of n){let e=i.type==="worker"?p.green("worker"):p.blue("runner");o.push(` ${e} ${i.name} ${p.dim(`${i.mtime.toISOString()} \xB7 ${Mn(i.size)}`)}`)}w.info(o.join(`
95
- `))}async printTail(r,n,o){let i=await He(n.path,"utf-8"),e=[`${p.bold(r.name)} ${p.dim(Ne[n.type])}`,p.dim(n.path),p.dim(`Last modified: ${n.mtime.toISOString()}`)];w.info(e.join(`
96
- `)),console.log(jn(i,o))}async openFile(r){let n=(process.env.EDITOR??"").split(" ").filter(Boolean),o=n[0];if(o){await Bun.spawn([o,...n.slice(1),r.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${r.path}`.quiet();return}throw new v("No editor configured","Set $EDITOR to open log files")}}var ze=G({name:{description:"Profile name to set as default"}});class Nn extends I{name="default";description="Set the default profile";positionals=ze;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new v("Profile name is required","Usage: hydra profile default <name>");let{name:o}=J(r.config,n);if(r.config.get("defaultProfile")===o){w.info(`"${o}" is already the default profile.`);return}r.config.set("defaultProfile",o),w.info(`${p.green("Default profile set to")} "${o}".`)}}class qn extends I{name="list";description="List all profiles";async execute(r){let n=r.config.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=r.config.get("runners")??[],e=r.config.get("defaultProfile");for(let t of o){let a=n[t],c=await z(a).list(),f=i.filter((b)=>b.profile===t),d=new Set(c.filter((b)=>b.status==="running").map((b)=>b.id)),g=f.filter((b)=>d.has(b.id)).length,u=t===e,h=[`${p.dim("URL:")} ${a.url}`,`${p.dim("Provider:")} ${a.provider}`,`${p.dim("OS:")} ${a.os}`,`${p.dim("Name:")} ${a.name}`,`${p.dim("Runners:")} ${f.length}/${a.numberOfMachines} created, ${p.green(`${g} running`)}`];if(a.labels)h.push(`${p.dim("Labels:")} ${a.labels}`);let l=u?`${t} ${p.dim("(default)")}`:t;sr(h.join(`
97
- `),l)}w.info(p.dim(`${o.length} profile(s)`))}}import{rm as We}from"fs/promises";import{join as Je}from"path";var Ae=G({name:{description:"Profile name to remove"}});class Gn extends I{name="remove";description="Remove a profile";positionals=Ae;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new v("Profile name is required","Usage: hydra profile remove <name>");let{profile:o}=J(r.config,n),i=r.config.get("runners")??[],e=i.filter((c)=>c.profile===n);if(e.length>0){if(!await br({initialValue:!0,message:`This will stop and remove ${e.length} runner(s). Continue?`}))return;await this.removeRunners(o,e.map((d)=>d.id));let f=i.filter((d)=>d.profile!==n);r.config.set("runners",f)}let{[n]:t,...a}=r.config.get("profiles");if(r.config.set("profiles",a),r.config.get("defaultProfile")===n){let c=Object.keys(a);r.config.set("defaultProfile",c[0])}w.info(`${p.green("Removed")} profile "${n}".`)}async removeRunners(r,n){let o=z(r),i=Y();for(let e of n)i.start(`Stopping and removing ${e}...`),await o.stop([e]),await o.remove([e]),await We(Je(r.directory,e),{force:!0,recursive:!0}),i.stop(`${p.red("-")} ${e}`)}}class Sr extends I{name="profile";description="Manage profiles";init(){this.registerSubcommands([new qn,new Gn,new Nn])}}import{rm as Ke}from"fs/promises";import{join as Ye}from"path";var Ze=G({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class Br extends I{name="remove";description="Deregister and remove runners";positionals=Ze;async execute(r){let{name:n,profile:o}=r.interactive?J(r.config,await Q(r.config)):J(r.config,r.positionals.profile),i=r.config.get("runners")??[],e=i.filter((f)=>f.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=r.interactive?await this.promptRunnerSelection(e.map((f)=>f.id)):ur(r.positionals.ids??[],e.map((f)=>f.id)),a=z(o),s=Y();for(let f of t)s.start(`Stopping and removing ${f}...`),await a.stop([f]),await a.remove([f]),await Ke(Ye(o.directory,f),{force:!0,recursive:!0}),s.stop(`${p.red("-")} ${f}`);let c=i.filter((f)=>!t.includes(f.id));r.config.set("runners",c),w.info(`${p.green("Removed")} ${t.length} runner(s).`)}async promptRunnerSelection(r){return ar({message:"Select runners to remove",options:r.map((n)=>({label:n,value:n})),required:!0})}}var xe=G({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class _r extends I{name="start";description="Start runners";positionals=xe;async execute(r){let{name:n,profile:o}=r.interactive?J(r.config,await Q(r.config)):J(r.config,r.positionals.profile),e=(r.config.get("runners")??[]).filter((u)=>u.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=z(o),a=Y();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((u)=>u.status==="running").map((u)=>u.id)),f=e.map((u)=>u.id).filter((u)=>!c.has(u)),d=r.interactive?await this.promptRunnerSelection(f):ur(r.positionals.ids??[],e.map((u)=>u.id)),g=0;for(let u of d){if(c.has(u)){a.start(""),a.stop(`${p.dim("\u25CF")} ${u} ${p.dim("already running")}`);continue}a.start(`Starting ${u}...`),await t.start([u]),a.stop(`${p.green("\u25B6")} ${u}`),g++}w.info(`${p.green("Started")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new v("All runners are already running");return ar({message:"Select runners to start",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Qe={registered:p.yellow,running:p.green,stopped:p.red,unknown:p.dim};class Tr extends I{name="status";description="Show runner status across all profiles";async execute(r){let n=r.config.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=r.config.get("runners")??[],e=0,t=0,a=[];for(let s of o){let c=n[s],d=await z(c).list();if(a.length>0)a.push("");a.push(`${p.bold(s)} ${p.dim(c.url)}`);let g=new Set(i.filter((h)=>h.profile===s).map((h)=>h.id)),u=d.filter((h)=>g.has(h.id)).sort((h,l)=>h.name.localeCompare(l.name,void 0,{numeric:!0}));this.formatRunners(u,a),e+=u.length,t+=u.filter((h)=>h.status==="running").length}a.push(""),a.push(p.dim(`${e} runner(s) total, ${t} running`)),w.info(a.join(`
98
- `))}formatRunners(r,n){if(r.length===0){n.push(p.dim(" No runners."));return}for(let o of r){let i=Qe[o.status]??p.dim,e=o.pid?p.dim(` (pid: ${o.pid})`):"";n.push(` ${i("\u25CF")} ${o.name} ${i(o.status)}${e}`)}}}var Xe=G({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class rn extends I{name="stop";description="Stop runners";positionals=Xe;async execute(r){let{name:n,profile:o}=r.interactive?J(r.config,await Q(r.config)):J(r.config,r.positionals.profile),e=(r.config.get("runners")??[]).filter((u)=>u.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=z(o),a=Y();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((u)=>u.status==="running").map((u)=>u.id)),f=e.map((u)=>u.id).filter((u)=>c.has(u)),d=r.interactive?await this.promptRunnerSelection(f):ur(r.positionals.ids??[],e.map((u)=>u.id)),g=0;for(let u of d){if(!c.has(u)){a.start(""),a.stop(`${p.dim("\u25CF")} ${u} ${p.dim("not running")}`);continue}a.start(`Stopping ${u}...`),await t.stop([u]),a.stop(`${p.red("\u25A0")} ${u}`),g++}w.info(`${p.green("Stopped")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new v("No runners are currently running");return ar({message:"Select runners to stop",options:r.map((n)=>({label:n,value:n})),required:!0})}}class nn extends I{name="update";description="Update runners to the latest version";async execute(r){let n=r.config.get("profiles"),o=r.config.get("runners")??[];if(o.length===0)throw new v("No runners found","Run hydra create to provision runners");let i=Y(),e=Map.groupBy(o,(c)=>c.profile),t=null,a="",s=!1;for(let[c,f]of e){let d=n[c],g=f[0];if(!d||!g)continue;let u=z(d);if(!s){if(s=!0,i.start("Checking for updates..."),a=(await u.download()).version,t=await u.currentVersion(g.id),i.stop(`Current: v${t??"unknown"} | Latest: v${a}`),t===a){w.info(`Already on latest version ${p.dim(`(v${a})`)}`);return}}let h=await u.list(),l=new Set(h.filter((b)=>b.status==="running").map((b)=>b.id));for(let b of f){let k=l.has(b.id);if(i.start(`Updating ${b.id}...`),k)await u.stop([b.id]);if(await u.update([b.id]),k)await u.start([b.id]);let R=k?` ${p.dim("(restarted)")}`:"";i.stop(`${p.green("\u2713")} ${b.id}${R}`)}}w.info(`${p.green("Updated")} ${o.length} runner(s) from v${t} to v${a}`)}}class Oo extends yn{constructor(){super(new Ln(No,qo),{bin:Zr,clearOnStart:!0,exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:Eo})}init(){this.registerCommands([new Vr,new Xr,new _r,new rn,new Tr,new Or,new Br,new nn,new Sr])}}var Ve=new Oo;Ve.run();
93
+ `)}function Mn(r){let n=r,o=0;while(n>=Jo&&o<xo.length-1)n/=Jo,o++;return`${o===0?String(n):n.toFixed(ye)} ${xo[o]??"B"}`}var Xo="actions/runner",je={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},Vo=["bin"],Oo=["externals"];class Vr{profile;sharedPath=null;constructor(r){this.profile=r}async download(){let r=je[this.profile.os],n=await this.getLatestVersion(),o=R(Pr,"github",n);if(kr(o))return this.sharedPath=o,{path:o,version:n};await Un(o,{recursive:!0});let i=`actions-runner-${r}-${n}.tar.gz`,e=R(o,i),t=`https://github.com/${Xo}/releases/download/v${n}/${i}`;return await Bun.$`curl -sL -o ${e} ${t}`,await Bun.$`tar xzf ${e} -C ${o}`,await Qo(e),this.sharedPath=o,{path:o,version:n}}async create(r){let n=await this.ensureDownloaded(),o=[];for(let i of r){let e=R(this.profile.directory,i);await this.setupRunnerDir(n,e),await this.registerRunner(e,i),o.push({directory:e,id:i,name:i,status:"registered"})}return o}async remove(r){for(let n of r){let o=R(this.profile.directory,n);if(!kr(R(o,".runner")))continue;let i=await this.fetchRemovalToken(o);await Bun.$`bash ./config.sh remove --token ${i}`.cwd(o).quiet().nothrow()}}async start(r){for(let n of r){let o=R(this.profile.directory,n),i=await this.readPidFile(o);if(i&&this.isProcessRunning(i))continue;let e=Bun.spawn(["bash","./run.sh"],{cwd:Xr(o),stderr:"pipe",stdout:"pipe"});e.unref(),await this.writePidFile(o,e.pid)}}async stop(r){for(let n of r){let o=R(this.profile.directory,n);if(!await this.readPidFile(o))continue;let e=Xr(o);await Bun.$`pkill -f ${e}`.quiet().nothrow(),await this.removePidFile(o)}}async list(){let r=this.profile.directory;if(!kr(r))return[];let n=await Zo(r,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory())continue;let e=R(r,i.name);o.push(await this.getRunnerStatus(e,i.name))}return o}async currentVersion(r){let n=R(this.profile.directory,r);return this.detectVersion(n)}async logFiles(r){return Hn(R(this.profile.directory,r,Dn))}async update(r){let n=await this.ensureDownloaded();for(let o of r){let i=R(this.profile.directory,o);await this.removeRunnerBinaries(i),await this.setupRunnerDir(n,i)}}async getRunnerStatus(r,n){let o=await this.readRunnerName(r),i=await this.readPidFile(r),e=i!==null&&this.isProcessRunning(i),t="unknown";if(e)t="running";else if(kr(R(r,".runner")))t="registered";return{directory:r,id:n,name:o,pid:e?i:void 0,status:t}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:r}=await this.download();return r}async setupRunnerDir(r,n){await Un(n,{recursive:!0});for(let o of Vo)await this.hardLinkDir(R(r,o),R(n,o));for(let o of Oo){let i=Xr(r,o),e=R(n,o);if(!kr(e))await De(i,e)}for(let o of["*.sh","*.sh.template"]){let i=await Array.fromAsync(new Bun.Glob(o).scan(r));for(let e of i)await Ie(R(r,e),R(n,e))}}async registerRunner(r,n){let o=await this.fetchRegistrationToken(),i=["--url",this.profile.url,"--token",o,"--name",n,"--unattended"];if(this.profile.labels)i.push("--labels",this.profile.labels);if(this.profile.runnerGroup)i.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${i}`.cwd(r).quiet()}async fetchRegistrationToken(){return this.fetchRunnerToken(sr(this.profile.url),"registration-token")}async fetchRemovalToken(r){let n=await Gn(R(r,".runner"),"utf-8"),i=JSON.parse(this.stripBom(n)).gitHubUrl;if(!i)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(sr(i),"remove-token")}async fetchRunnerToken(r,n){let o=r.kind==="repo"?`repos/${r.owner}/${r.repo}/actions/runners/${n}`:`orgs/${r.org}/actions/runners/${n}`,i=r.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",e=await Bun.$`gh api ${o} --method POST --jq .token`.quiet().nothrow();if(e.exitCode!==0){let a=e.stderr.toString().trim();throw Error(`gh api ${o} failed for ${Qr(r)} (${i})${a?`: ${a}`:""}`)}let t=e.stdout.toString().trim();if(!t)throw Error(`Failed to fetch ${n} for ${Qr(r)}`);return t}async getLatestVersion(){return(await Bun.$`gh api repos/${Xo}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(r){return Xr(r,".pid")}async writePidFile(r,n){await He(this.pidFilePath(r),String(n))}async readPidFile(r){try{let n=await Gn(this.pidFilePath(r),"utf-8");return Number.parseInt(n.trim(),10)}catch{return null}}async removePidFile(r){try{await Qo(this.pidFilePath(r))}catch{}}async readRunnerName(r){try{let n=await Gn(R(r,".runner"),"utf-8");return JSON.parse(this.stripBom(n)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(r,n){await Un(n,{recursive:!0});let o=await Zo(r,{withFileTypes:!0});for(let i of o){let e=R(r,i.name),t=R(n,i.name);if(i.isDirectory())await this.hardLinkDir(e,t);else await Le(e,t)}}async detectVersion(r){try{return(await Re(R(r,"externals"))).match(/github\/([^/]+)/)?.[1]??null}catch{return null}}async removeRunnerBinaries(r){for(let n of Vo)await Nn(R(r,n),{force:!0,recursive:!0});for(let n of Oo)await Nn(R(r,n),{force:!0});for(let n of["*.sh","*.sh.template"]){let o=await Array.fromAsync(new Bun.Glob(n).scan(r));for(let i of o)await Nn(R(r,i),{force:!0})}}stripBom(r){return r.replace(/^\uFEFF/,"")}isProcessRunning(r){try{return process.kill(r,0),!0}catch{return!1}}}function z(r){switch(r.provider){case"github":return new Vr(r);default:throw Error(`Runner provider "${r.provider}" is not yet implemented`)}}function pr(r,n){if(r.length===0)return n;for(let o of r)if(!n.includes(o))throw new v(`Runner "${o}" not found`);return r}function A(r,n){let o=r.get("profiles");if(Object.keys(o).length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=n??r.get("defaultProfile")??Fr,e=o[i];if(!e)throw new v(`Profile "${i}" not found`);return{name:i,profile:e}}async function Q(r){let n=r.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");if(o.length===1)return o[0];return tr({message:"Select profile",options:o.map((i)=>({label:i,value:i,hint:n[i]?.url}))})}var Me=q({profile:{description:"Profile name"},count:{description:"Number of runners to create (overrides profile)"}});class Or extends L{name="create";description="Create and register runners";positionals=Me;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),i=r.interactive?await this.promptCount(o.numberOfMachines):r.positionals.count?Number.parseInt(r.positionals.count,10):o.numberOfMachines;if(!i||i<1)throw new v("Runner count must be at least 1");let e=z(o),t=K();t.start("Downloading runner binary...");let{version:a}=await e.download();t.stop(`Runner v${a} ready`);let s=r.config.get("runners")??[],c=s.filter((d)=>d.profile===n),f=i-c.length;if(f<=0){w.warn(`Already have ${c.length} runner(s) for profile "${n}". Nothing to create.`);return}let l=new Set(s.map((d)=>d.id)),g=1;for(let d=0;d<f;){let b=`${o.name}-${g++}`;if(l.has(b))continue;d++,t.start(`Registering ${b}...`),await e.create([b]),t.stop(`${p.green("+")} ${b}`),s.push({createdAt:new Date().toISOString(),directory:Ee(o.directory,b),id:b,name:b,profile:n,provider:o.provider,url:o.url})}r.config.set("runners",s);let h=n===r.config.get("defaultProfile")?"":` ${n}`;w.info(`${p.green("Created")} ${f} runner(s) for "${n}". Run ${p.green(`hydra start${h}`)} to start them.`)}async promptCount(r){let n=await rr({initialValue:String(r),message:"Number of runners to create",validate:(o)=>{let i=Number.parseInt(o??"",10);if(Number.isNaN(i)||i<1)return"Must be a positive number";return}});return Number.parseInt(n,10)}}import{existsSync as So}from"fs";import{mkdir as Bo}from"fs/promises";var Ue=q({url:{description:"GitHub repository or organization URL"}}),Ge=mr({force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},labels:{alias:"l",description:"Comma-separated runner labels",type:"string"},name:{alias:"n",description:"Base name for runners",type:"string"},profile:{alias:"p",description:"Profile name",type:"string"},runners:{alias:"c",description:"Number of runners to create",type:"number"}});class Sr extends L{name="init";description="Initialize Hydra runner manager";positionals=Ue;args=Ge;prompts=!0;async execute(r){let n=r.interactive?await this.promptProfileName(r):r.args.profile??Fr,o=!r.config.exists();if(!o&&r.config.get("profiles")[n]&&!r.args.force){if(!r.interactive)throw new v(`Profile "${n}" already exists. Use --force to overwrite.`);if(!await vr({initialValue:!1,message:`Profile "${n}" already exists. Overwrite?`}))return}await this.ensureDirectories();let e=r.interactive?await this.runInitForm():this.buildProfileFromArgs(r),t=o?{}:{...r.config.get("profiles")};if(t[n]=e,r.config.set("profiles",t),!r.config.get("defaultProfile"))r.config.set("defaultProfile",n);cr([`${p.dim("Profile:")} ${n}`,`${p.dim("URL:")} ${e.url}`,`${p.dim("Runners:")} ${e.numberOfMachines}`,`${p.dim("Name:")} ${e.name}`,e.labels?`${p.dim("Labels:")} ${e.labels}`:"","",`Run ${p.green(`${Zr} create${n!==r.config.get("defaultProfile")?` ${n}`:""}`)} to provision runners.`].filter(Boolean).join(`
94
+ `),p.green(o?"Hydra initialized":`Profile "${n}" added`))}async promptProfileName(r){return rr({initialValue:r.args.profile??Fr,message:"Profile name"})}async ensureDirectories(){if(!So(Pr))await Bo(Pr,{recursive:!0});if(!So(Cr))await Bo(Cr,{recursive:!0})}async runInitForm(){let r=await Nr({url:()=>rr({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{sr(n)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>rr({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>rr({initialValue:"1",message:"Number of runners",placeholder:"1",validate:(n)=>{if(!n)return"Must be a positive number";let o=Number.parseInt(n,10);if(Number.isNaN(o)||o<1)return"Must be a positive number";return}}),labels:()=>rr({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new X}});return{directory:Cr,labels:r.labels||void 0,name:r.name,numberOfMachines:Number.parseInt(r.runners,10)||1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.url}}buildProfileFromArgs(r){if(!r.positionals.url)throw new v("URL is required","Usage: hydra init <url>");return this.validateUrl(r.positionals.url),this.validateRunnerCount(r.args.runners),{directory:Cr,labels:r.args.labels,name:r.args.name??"runner",numberOfMachines:r.args.runners??1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.positionals.url}}validateUrl(r){try{sr(r)}catch(n){throw new v(n instanceof Error?n.message:`Invalid GitHub URL: ${r}`,"Expected https://github.com/<owner>/<repo> or https://github.com/<org>")}}validateRunnerCount(r){if(r!==void 0&&r<1)throw new v("Runner count must be at least 1")}detectOs(){let r=process.platform;if(r==="darwin")return"osx";if(r==="win32")return"windows";return"linux"}}import{existsSync as Ne}from"fs";import{readFile as qe}from"fs/promises";var ze=100,We={runner:"runner daemon log",worker:"job log"},Ae=mr({lines:{alias:"n",default:ze,description:"Number of lines to tail",type:"number"},list:{alias:"l",default:!1,description:"List available log files instead of printing content",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file in $EDITOR instead of printing",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner daemon log instead of the latest job log",type:"boolean"}}),Je=q({id:{description:"Runner ID"}});class Br extends L{name="logs";description="Inspect logs of the latest jobs";args=Ae;positionals=Je;async execute(r){let n=r.config.get("runners")??[];if(n.length===0)throw new v("No runners found","Run hydra create to provision runners");let o=await this.resolveEntry(r,n),i=r.config.get("profiles")[o.profile];if(!i)throw new v(`Profile "${o.profile}" not found for runner "${o.id}"`,"Run hydra init to set it up");if(!Ne(o.directory))throw new v(`Runner directory not found: ${o.directory}`,"Run hydra create to provision this runner");let t=await z(i).logFiles(o.id);if(t.length===0)this.noLogs(o.id);if(r.args.list){this.printList(o,t);return}let a=this.selectFile(r,o,t);if(r.args.open){await this.openFile(a);return}await this.printTail(o,a,r.args.lines)}async resolveEntry(r,n){let o=r.positionals.id;if(o){let e=n.find((t)=>t.id===o);if(!e)throw new v(`Runner "${o}" not found`,`Known runners: ${n.map((t)=>t.id).join(", ")}`);return e}if(r.interactive)return tr({message:"Select runner",options:n.map((e)=>({hint:e.profile,label:e.name,value:e}))});let i=n[0];if(n.length===1&&i)return i;throw new v("Multiple runners found",`Pass a runner id: hydra logs <id> (${n.map((e)=>e.id).join(", ")})`)}selectFile(r,n,o){if(r.args.runner){let e=o.find((t)=>t.type==="runner");if(!e)throw new v(`No runner daemon logs found for "${n.id}"`,"Start the runner first: hydra start");return e}let i=jn(o,"worker");if(!i)this.noLogs(n.id);if(i.fallback)w.warn(p.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return i.file}noLogs(r){throw new v(`No logs found for runner "${r}"`,"Logs appear once the runner has started; run hydra start")}printList(r,n){let o=[`${p.bold(r.name)} ${p.dim(r.directory)}`];for(let i of n){let e=i.type==="worker"?p.green("worker"):p.blue("runner");o.push(` ${e} ${i.name} ${p.dim(`${i.mtime.toISOString()} \xB7 ${Mn(i.size)}`)}`)}w.info(o.join(`
95
+ `))}async printTail(r,n,o){let i=await qe(n.path,"utf-8"),e=[`${p.bold(r.name)} ${p.dim(We[n.type])}`,p.dim(n.path),p.dim(`Last modified: ${n.mtime.toISOString()}`)];w.info(e.join(`
96
+ `)),console.log(En(i,o))}async openFile(r){let n=(process.env.EDITOR??"").split(" ").filter(Boolean),o=n[0];if(o){await Bun.spawn([o,...n.slice(1),r.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${r.path}`.quiet();return}throw new v("No editor configured","Set $EDITOR to open log files")}}var xe=q({name:{description:"Profile name to set as default"}});class qn extends L{name="default";description="Set the default profile";positionals=xe;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new v("Profile name is required","Usage: hydra profile default <name>");let{name:o}=A(r.config,n);if(r.config.get("defaultProfile")===o){w.info(`"${o}" is already the default profile.`);return}r.config.set("defaultProfile",o),w.info(`${p.green("Default profile set to")} "${o}".`)}}class zn extends L{name="list";description="List all profiles";async execute(r){let n=r.config.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=r.config.get("runners")??[],e=r.config.get("defaultProfile");for(let t of o){let a=n[t],c=await z(a).list(),f=i.filter((b)=>b.profile===t),l=new Set(c.filter((b)=>b.status==="running").map((b)=>b.id)),g=f.filter((b)=>l.has(b.id)).length,u=t===e,h=[`${p.dim("URL:")} ${a.url}`,`${p.dim("Provider:")} ${a.provider}`,`${p.dim("OS:")} ${a.os}`,`${p.dim("Name:")} ${a.name}`,`${p.dim("Runners:")} ${f.length}/${a.numberOfMachines} created, ${p.green(`${g} running`)}`];if(a.labels)h.push(`${p.dim("Labels:")} ${a.labels}`);let d=u?`${t} ${p.dim("(default)")}`:t;cr(h.join(`
97
+ `),d)}w.info(p.dim(`${o.length} profile(s)`))}}import{rm as Ke}from"fs/promises";import{join as Ye}from"path";var Ze=q({name:{description:"Profile name to remove"}});class Wn extends L{name="remove";description="Remove a profile";positionals=Ze;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new v("Profile name is required","Usage: hydra profile remove <name>");let{profile:o}=A(r.config,n),i=r.config.get("runners")??[],e=i.filter((c)=>c.profile===n);if(e.length>0){if(!await vr({initialValue:!0,message:`This will stop and remove ${e.length} runner(s). Continue?`}))return;await this.removeRunners(o,e.map((l)=>l.id));let f=i.filter((l)=>l.profile!==n);r.config.set("runners",f)}let{[n]:t,...a}=r.config.get("profiles");if(r.config.set("profiles",a),r.config.get("defaultProfile")===n){let c=Object.keys(a);r.config.set("defaultProfile",c[0])}w.info(`${p.green("Removed")} profile "${n}".`)}async removeRunners(r,n){let o=z(r),i=K();for(let e of n)i.start(`Stopping and removing ${e}...`),await o.stop([e]),await o.remove([e]),await Ke(Ye(r.directory,e),{force:!0,recursive:!0}),i.stop(`${p.red("-")} ${e}`)}}class _r extends L{name="profile";description="Manage profiles";init(){this.registerSubcommands([new zn,new Wn,new qn])}}import{rm as Qe}from"fs/promises";import{join as Xe}from"path";var Ve=q({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class Tr extends L{name="remove";description="Deregister and remove runners";positionals=Ve;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),i=r.config.get("runners")??[],e=i.filter((f)=>f.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=r.interactive?await this.promptRunnerSelection(e.map((f)=>f.id)):pr(r.positionals.ids??[],e.map((f)=>f.id)),a=z(o),s=K();for(let f of t)s.start(`Stopping and removing ${f}...`),await a.stop([f]),await a.remove([f]),await Qe(Xe(o.directory,f),{force:!0,recursive:!0}),s.stop(`${p.red("-")} ${f}`);let c=i.filter((f)=>!t.includes(f.id));r.config.set("runners",c),w.info(`${p.green("Removed")} ${t.length} runner(s).`)}async promptRunnerSelection(r){return ar({message:"Select runners to remove",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Oe=q({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class rn extends L{name="start";description="Start runners";positionals=Oe;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),e=(r.config.get("runners")??[]).filter((u)=>u.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=z(o),a=K();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((u)=>u.status==="running").map((u)=>u.id)),f=e.map((u)=>u.id).filter((u)=>!c.has(u)),l=r.interactive?await this.promptRunnerSelection(f):pr(r.positionals.ids??[],e.map((u)=>u.id)),g=0;for(let u of l){if(c.has(u)){a.start(""),a.stop(`${p.dim("\u25CF")} ${u} ${p.dim("already running")}`);continue}a.start(`Starting ${u}...`),await t.start([u]),a.stop(`${p.green("\u25B6")} ${u}`),g++}w.info(`${p.green("Started")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new v("All runners are already running");return ar({message:"Select runners to start",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Se={registered:p.yellow,running:p.green,stopped:p.red,unknown:p.dim};class nn extends L{name="status";description="Show runner status across all profiles";async execute(r){let n=r.config.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=r.config.get("runners")??[],e=0,t=0,a=[];for(let s of o){let c=n[s],l=await z(c).list();if(a.length>0)a.push("");a.push(`${p.bold(s)} ${p.dim(c.url)}`);let g=new Set(i.filter((h)=>h.profile===s).map((h)=>h.id)),u=l.filter((h)=>g.has(h.id)).sort((h,d)=>h.name.localeCompare(d.name,void 0,{numeric:!0}));this.formatRunners(u,a),e+=u.length,t+=u.filter((h)=>h.status==="running").length}a.push(""),a.push(p.dim(`${e} runner(s) total, ${t} running`)),w.info(a.join(`
98
+ `))}formatRunners(r,n){if(r.length===0){n.push(p.dim(" No runners."));return}for(let o of r){let i=Se[o.status]??p.dim,e=o.pid?p.dim(` (pid: ${o.pid})`):"";n.push(` ${i("\u25CF")} ${o.name} ${i(o.status)}${e}`)}}}var Be=q({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class on extends L{name="stop";description="Stop runners";positionals=Be;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),e=(r.config.get("runners")??[]).filter((u)=>u.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=z(o),a=K();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((u)=>u.status==="running").map((u)=>u.id)),f=e.map((u)=>u.id).filter((u)=>c.has(u)),l=r.interactive?await this.promptRunnerSelection(f):pr(r.positionals.ids??[],e.map((u)=>u.id)),g=0;for(let u of l){if(!c.has(u)){a.start(""),a.stop(`${p.dim("\u25CF")} ${u} ${p.dim("not running")}`);continue}a.start(`Stopping ${u}...`),await t.stop([u]),a.stop(`${p.red("\u25A0")} ${u}`),g++}w.info(`${p.green("Stopped")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new v("No runners are currently running");return ar({message:"Select runners to stop",options:r.map((n)=>({label:n,value:n})),required:!0})}}class en extends L{name="update";description="Update runners to the latest version";async execute(r){let n=r.config.get("profiles"),o=r.config.get("runners")??[];if(o.length===0)throw new v("No runners found","Run hydra create to provision runners");let i=K(),e=Map.groupBy(o,(c)=>c.profile),t=null,a="",s=!1;for(let[c,f]of e){let l=n[c],g=f[0];if(!l||!g)continue;let u=z(l);if(!s){if(s=!0,i.start("Checking for updates..."),a=(await u.download()).version,t=await u.currentVersion(g.id),i.stop(`Current: v${t??"unknown"} | Latest: v${a}`),t===a){w.info(`Already on latest version ${p.dim(`(v${a})`)}`);return}}let h=await u.list(),d=new Set(h.filter((b)=>b.status==="running").map((b)=>b.id));for(let b of f){let k=d.has(b.id);if(i.start(`Updating ${b.id}...`),k)await u.stop([b.id]);if(await u.update([b.id]),k)await u.start([b.id]);let D=k?` ${p.dim("(restarted)")}`:"";i.stop(`${p.green("\u2713")} ${b.id}${D}`)}}w.info(`${p.green("Updated")} ${o.length} runner(s) from v${t} to v${a}`)}}class _o extends Ln{constructor(){super(new Rn(qo,zo),{bin:Zr,clearOnStart:!0,exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:No})}init(){this.registerCommands([new Sr,new Or,new rn,new on,new nn,new Br,new Tr,new en,new _r])}}var _e=new _o;_e.run();
package/package.json CHANGED
@@ -5,11 +5,7 @@
5
5
  },
6
6
  "description": "A tool for spawning multiple local GitHub self-hosted runners",
7
7
  "dependencies": {
8
- "@r5n/cli-core": "workspace:*"
9
- },
10
- "devDependencies": {
11
- "@clack/prompts": "1.7.0",
12
- "@r5n/tools": "workspace:*"
8
+ "@r5n/cli-core": "0.2.2"
13
9
  },
14
10
  "files": [
15
11
  "dist",
@@ -43,5 +39,5 @@
43
39
  },
44
40
  "type": "module",
45
41
  "types": "src/cli.ts",
46
- "version": "0.6.0"
42
+ "version": "0.7.0"
47
43
  }
package/schema.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "$comment": "Add this to your hydra.json: \"$schema\": \"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/hydra/schema.json\"",
2
+ "$comment": "Add this to your .hydra/config.json: \"$schema\": \"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/hydra/schema.json\"",
3
3
  "$schema": "http://json-schema.org/draft-07/schema#",
4
4
  "additionalProperties": false,
5
5
  "definitions": {
@@ -7,7 +7,7 @@
7
7
  "additionalProperties": false,
8
8
  "properties": {
9
9
  "directory": {
10
- "default": "./gh-runners",
10
+ "default": ".hydra/runners",
11
11
  "description": "Directory where runners will be created",
12
12
  "type": "string"
13
13
  },
@@ -26,14 +26,45 @@
26
26
  "type": "string"
27
27
  },
28
28
  "overwrite": { "default": false, "description": "Whether to overwrite existing runners", "type": "boolean" },
29
+ "provider": {
30
+ "default": "github",
31
+ "description": "Runner provider backing this profile",
32
+ "enum": ["github", "gitlab"],
33
+ "type": "string"
34
+ },
29
35
  "run": {
30
36
  "default": false,
31
37
  "description": "Whether to start runners immediately after creation",
32
38
  "type": "boolean"
33
39
  },
34
- "runnerGroup": { "description": "Runner group to assign runners to", "type": "string" },
35
- "url": { "description": "GitHub repository or organization URL", "format": "uri", "type": "string" }
40
+ "runnerGroup": {
41
+ "description": "Runner group to assign runners to (applies to organization runners)",
42
+ "type": "string"
43
+ },
44
+ "url": {
45
+ "description": "GitHub repository URL (https://github.com/<owner>/<repo>) or organization URL (https://github.com/<org>)",
46
+ "format": "uri",
47
+ "type": "string"
48
+ }
49
+ },
50
+ "type": "object"
51
+ },
52
+ "runnerEntry": {
53
+ "additionalProperties": false,
54
+ "properties": {
55
+ "createdAt": { "description": "ISO timestamp of when the runner was created", "type": "string" },
56
+ "directory": { "description": "Directory of the runner installation", "type": "string" },
57
+ "id": { "description": "Runner identifier", "type": "string" },
58
+ "name": { "description": "Runner name as registered with the provider", "type": "string" },
59
+ "profile": { "description": "Profile the runner belongs to", "type": "string" },
60
+ "provider": {
61
+ "description": "Provider the runner is registered with",
62
+ "enum": ["github", "gitlab"],
63
+ "type": "string"
64
+ },
65
+ "url": { "description": "Repository or organization URL the runner is registered against", "type": "string" }
36
66
  },
67
+ "required": ["id", "name", "profile", "provider", "url", "directory", "createdAt"],
37
68
  "type": "object"
38
69
  }
39
70
  },
@@ -45,6 +76,11 @@
45
76
  "additionalProperties": { "$ref": "#/definitions/profile" },
46
77
  "description": "Named profiles for different runner configurations",
47
78
  "type": "object"
79
+ },
80
+ "runners": {
81
+ "description": "Runners Hydra has created; managed by Hydra, do not edit by hand",
82
+ "items": { "$ref": "#/definitions/runnerEntry" },
83
+ "type": "array"
48
84
  }
49
85
  },
50
86
  "required": ["profiles"],