@r5n/hydra 0.9.3 → 0.10.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 +3 -1
- package/dist/cli.js +97 -93
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -89,7 +89,7 @@ Passing any of `-l`/`-w`/`-s` cleans only those targets; with none, the targets
|
|
|
89
89
|
|
|
90
90
|
- `hydra profile list` — profiles with URL, OS, and created/running counts
|
|
91
91
|
- `hydra profile default <name>` — set the default profile
|
|
92
|
-
- `hydra profile remove <name
|
|
92
|
+
- `hydra profile remove <name> [--yes]` — remove a profile; if it has runners, stops and deregisters them first. Pass `--yes` to skip confirmation in scripts.
|
|
93
93
|
|
|
94
94
|
## Configuration
|
|
95
95
|
|
|
@@ -131,6 +131,8 @@ The `url` is either a repository URL (`https://github.com/owner/repo`) or an org
|
|
|
131
131
|
|
|
132
132
|
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.
|
|
133
133
|
|
|
134
|
+
Hydra disables the runner's automatic updater when registering it; use `hydra update` to update the shared binaries. Failed downloads are discarded, and completed registrations and removals are saved as each runner finishes, so a later failure in the batch can be retried. Failed deregistrations preserve the runner's files and record.
|
|
135
|
+
|
|
134
136
|
## License
|
|
135
137
|
|
|
136
138
|
Apache-2.0 — see [LICENSE](./LICENSE)
|
package/dist/cli.js
CHANGED
|
@@ -1,99 +1,103 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),
|
|
5
|
-
`){if(
|
|
6
|
-
`){if(i&&
|
|
7
|
-
`)}var
|
|
8
|
-
`),
|
|
9
|
-
`),o=n.split(`
|
|
10
|
-
`)
|
|
11
|
-
`).
|
|
12
|
-
`)
|
|
13
|
-
`)
|
|
14
|
-
`)
|
|
15
|
-
`)
|
|
16
|
-
`).
|
|
17
|
-
`)),this._prevFrame=r;return}}this.output.write(q.erase.down())}this.output.write(r),this.state==="initial"&&(this.state="active"),this._prevFrame=r}}}function ei(r,n){if(r===void 0||n.length===0)return 0;let e=n.findIndex((o)=>o.value===r);return e!==-1?e:0}function oi(r,n){return(n.label??String(n.value)).toLowerCase().includes(r.toLowerCase())}function ii(r,n){if(n)return r?n:n[0]}var ti=class extends T{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#i="";#r;#t;#s;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return xr(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let n=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),o=this.userInput.slice(this.cursor+1);return`${n}${xr("inverse",e)}${o}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(n){super(n),this.#t=n.options,this.#s=n.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=n.multiple===!0,this.#r=typeof n.options=="function"?n.filter:n.filter??oi;let o;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?o=n.initialValue:o=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(o=[this.options[0]?.value]),o)for(let i of o){let t=e.findIndex((a)=>a.value===i);t!==-1&&(this.toggleSelected(i),this.#n=t)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,t)=>this.#e(i,t)),this.on("userInput",(i)=>this.#o(i))}_isActionKey(n,e){return n==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&n!==void 0&&n!==""}#e(n,e){let o=e.name==="up",i=e.name==="down",t=e.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(e.name==="tab"&&a&&f){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}o||i?(this.#n=_(this.#n,o?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):t?this.value=ii(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.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((e)=>e!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#o(n){if(n!==this.#i){this.#i=n;let e=this.options;n&&this.#r?this.filteredOptions=e.filter((t)=>this.#r?.(n,t)):this.filteredOptions=[...e];let o=ei(this.focusedValue,this.filteredOptions);this.#n=_(o,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class En 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(q.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var ai={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Ce(r){return[...r].map((n)=>ai[n])}function si(r){let n=new Intl.DateTimeFormat(r,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],o="/";for(let i of n)i.type==="literal"?o=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:o}}function Fn(r){return Number.parseInt((r||"0").replace(/_/g,"0"),10)||0}function Gr(r){return{year:Fn(r.year),month:Fn(r.month),day:Fn(r.day)}}function kn(r,n){return new Date(r||2001,n||1,0).getDate()}function Re(r){let{year:n,month:e,day:o}=Gr(r);if(!n||n<0||n>9999||!e||e<1||e>12||!o||o<1)return;let i=new Date(Date.UTC(n,e-1,o));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==e-1||i.getUTCDate()!==o))return{year:n,month:e,day:o}}function $e(r){let n=Re(r);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function ci(r,n,e,o){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,t=o?{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()}:null;return r==="year"?{min:i?.year??1,max:t?.year??9999}:r==="month"?{min:i&&n.year===i.year?i.month:1,max:t&&n.year===t.year?t.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:t&&n.year===t.year&&n.month===t.month?t.day:kn(n.year,n.month)}}class ke extends T{#n;#i;#r;#t;#s;#e={segmentIndex:0,positionInSegment:0};#o=!0;#a=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#r}}get segments(){return this.#n}get separator(){return this.#i}get formattedValue(){return this.#p(this.#r)}#p(r){return this.#n.map((n)=>r[n.type]).join(this.#i)}#c(){this._setUserInput(this.#p(this.#r)),this._setValue($e(this.#r)??void 0)}constructor(r){let n=r.format?{segments:Ce(r.format),separator:r.separator??"/"}:si(r.locale),e=r.separator??n.separator,o=r.format?Ce(r.format):n.segments,i=r.initialValue??r.defaultValue,t=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=o.map((s)=>t[s.type]).join(e);super({...r,initialUserInput:a},!1),this.#n=o,this.#i=e,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.#e.segmentIndex,this.#n.length-1)),n=this.#n[r];if(n)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,n.len-1)),{segment:n,index:r}}#u(r){this.inlineError="",this.#a=null;let n=this.#f();n&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+r)),this.#e.positionInSegment=0,this.#o=!0)}#m(r){let n=this.#f();if(!n)return;let{segment:e}=n,o=this.#r[e.type],i=!o||o.replace(/_/g,"")==="",t=Number.parseInt((o||"0").replace(/_/g,"0"),10)||0,a=ci(e.type,Gr(this.#r),this.#t,this.#s),s;i?s=r===1?a.min:a.max:s=Math.max(Math.min(a.max,t+r),a.min),this.#r={...this.#r,[e.type]:s.toString().padStart(e.len,"0")},this.#o=!0,this.#a=null,this.#c()}#d(r){if(r)switch(r){case"right":return this.#u(1);case"left":return this.#u(-1);case"up":return this.#m(1);case"down":return this.#m(-1)}}#g(r,n){if(n?.name==="backspace"||n?.sequence==="\x7F"||n?.sequence==="\b"||r==="\x7F"||r==="\b"){this.inlineError="";let e=this.#f();if(!e)return;if(!this.#r[e.segment.type].replace(/_/g,"")){this.#u(-1);return}this.#r[e.segment.type]="_".repeat(e.segment.len),this.#o=!0,this.#e.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let e=this.#f();if(!e)return;let o=n.shift?-1:1,i=e.index+o;i>=0&&i<this.#n.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#o=!0);return}if(r&&/^[0-9]$/.test(r)){let e=this.#f();if(!e)return;let{segment:o}=e,i=!this.#r[o.type].replace(/_/g,"");if(this.#o&&this.#a!==null&&!i){let p=this.#a+r,h={...this.#r,[o.type]:p},l=this.#l(h,o);if(l){this.inlineError=l,this.#a=null,this.#o=!1;return}this.inlineError="",this.#r[o.type]=p,this.#a=null,this.#o=!1,this.#c(),e.index<this.#n.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#o=!0);return}this.#o&&!i&&(this.#r[o.type]="_".repeat(o.len),this.#e.positionInSegment=0),this.#o=!1,this.#a=null;let t=this.#r[o.type],a=t.indexOf("_"),s=a>=0?a:Math.min(this.#e.positionInSegment,o.len-1);if(s<0||s>=o.len)return;let c=t.slice(0,s)+r+t.slice(s+1),f=!1;if(s===0&&t==="__"&&(o.type==="month"||o.type==="day")){let p=Number.parseInt(r,10);c=`0${r}`,f=p<=(o.type==="month"?1:2)}if(o.type==="year"&&(c=(t.replace(/_/g,"")+r).padStart(o.len,"_")),!c.includes("_")){let p={...this.#r,[o.type]:c},h=this.#l(p,o);if(h){this.inlineError=h;return}}this.inlineError="",this.#r[o.type]=c;let d=c.includes("_")?void 0:Re(this.#r);if(d){let{year:p,month:h}=d,l=kn(p,h);this.#r={year:String(Math.max(0,Math.min(9999,p))).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.#o=!0,this.#a=r):g>=0?this.#e.positionInSegment=g:a>=0&&e.index<this.#n.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#o=!0):this.#e.positionInSegment=Math.min(s+1,o.len-1)}}#l(r,n){let{month:e,day:o}=Gr(r);if(n.type==="month"&&(e<0||e>12))return M.date.messages.invalidMonth;if(n.type==="day"&&(o<0||o>31))return M.date.messages.invalidDay(31,"any month")}#h(r){let{year:n,month:e,day:o}=Gr(this.#r);if(n&&e&&o){let i=kn(n,e);this.#r={...this.#r,day:String(Math.min(o,i)).padStart(2,"0")}}this.value=$e(this.#r)??r.defaultValue??void 0}}var fi=class extends T{options;cursor=0;#n;getGroupItems(n){return this.options.filter((e)=>e.group===n)}isGroupSelected(n){let e=this.getGroupItems(n),o=this.value;return o===void 0?!1:e.every((i)=>o.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let e=n.value,o=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>o.findIndex((t)=>t.value===i)===-1):this.value=[...this.value,...o.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(n.value);this.value=e?this.value.filter((o)=>o!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:e}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([o,i])=>[{value:o,group:!0,label:o},...i.map((t)=>({...t,group:o}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:o})=>o===n.cursorAt),this.#n?0:1),this.on("cursor",(o)=>{switch(o){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(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 i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},ui=new Set(["up","down","left","right"]);class Le extends T{#n=!1;#i;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),e=r.slice(this.cursor,this.cursor+1),o=r.slice(this.cursor+1);return e===`
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
|
|
29
|
-
${
|
|
30
|
-
|
|
31
|
-
`).map((
|
|
32
|
-
`),
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
${
|
|
37
|
-
`
|
|
38
|
-
`),
|
|
39
|
-
`).length,
|
|
40
|
-
|
|
41
|
-
${f}`)}
|
|
42
|
-
${d}
|
|
43
|
-
`}default:{let f=i?`${u("cyan",$)} `:"",d=a.split(`
|
|
44
|
-
`).length,g=o?Me(Fi,i):i?[u("cyan",ir)]:[],p=g.join(`
|
|
45
|
-
`),h=g.length+1;return`${a}${f}${jn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:d+h,style:c}).join(`
|
|
46
|
-
${f}`)}
|
|
3
|
+
var Nn=Object.create;var{getPrototypeOf:Mn,defineProperty:ur,getOwnPropertyNames:Un}=Object;var cr=Object.prototype.hasOwnProperty;function jn(t){return this[t]}var Vn,Gn,pr=(t,e,r)=>{var n=t!=null&&typeof t==="object";if(n){var i=e?Vn??=new WeakMap:Gn??=new WeakMap,s=i.get(t);if(s)return s}r=t!=null?Nn(Mn(t)):{};let o=e||!t||!t.__esModule||!cr.call(t,"default")?ur(r,"default",{value:t,enumerable:!0}):r;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Un(t))if(!cr.call(o,a))ur(o,a,{get:jn.bind(t,a),enumerable:!0})}if(n)i.set(t,o);return o};var Hn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var _e=Hn(function($o,Er){var Pe={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let r="";if(t<0)r+=`\x1B[${-t}D`;else if(t>0)r+=`\x1B[${t}C`;if(e<0)r+=`\x1B[${-e}A`;else if(e>0)r+=`\x1B[${e}B`;return r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ni={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},ii={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?Pe.up():"");if(t)e+=Pe.left;return e}};Er.exports={cursor:Pe,scroll:ni,erase:ii,beep:"\x07"}});class X extends Error{constructor(t="Operation cancelled"){super(t)}}class v extends Error{hint;exitCode;constructor(t,e,r=1){super(t);this.hint=e;this.exitCode=r}}import{styleText as si}from"util";import{stdout as Te,stdin as Pr}from"process";import*as st from"readline";import oi from"readline";var dr=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let r=0;t.lastIndex=0;while(t.test(e))r+=1;return e.length-r}})(),mr=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,hr=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var Bn=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Wn=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,fr=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Kn=/\t{1,1000}/y,gr=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Jn=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,qn=/\p{M}+/gu,zn={limit:1/0,ellipsis:""},yr=(t,e={},r={})=>{let n=e.limit??1/0,i=e.ellipsis??"",s=e?.ellipsisWidth??(i?yr(i,zn,r).width:0),o=0,a=r.controlWidth??0,l=r.tabWidth??8,u=r.emojiWidth??2,m=2,f=r.regularWidth??1,p=r.wideWidth??2,g=[[Jn,f],[Bn,0],[Wn,a],[Kn,l],[gr,u],[fr,p]],h=0,y=0,E=t.length,_=0,x=!1,k=E,D=Math.max(0,n-s),S=0,L=0,O=0,b=0;t:while(!0){if(L>S||y>=E&&y>h){let I=t.slice(S,L)||t.slice(h,y);_=0;for(let V of I.replaceAll(qn,"")){let B=V.codePointAt(0)||0;if(mr(B))b=2;else if(hr(B))b=p;else b=f;if(O+b>D)k=Math.min(k,Math.max(S,h)+_);if(O+b>n){x=!0;break t}_+=V.length,O+=b}S=L=0}if(y>=E)break t;for(let I=0,V=g.length;I<V;I++){let[B,Nt]=g[I];if(B.lastIndex=y,B.test(t)){if(_=B===fr?dr(t.slice(y,B.lastIndex)):B===gr?1:B.lastIndex-y,b=_*Nt,O+b>D)k=Math.min(k,y+Math.floor((D-O)/Nt));if(O+b>n){x=!0;break t}O+=b,S=h,L=y,y=h=B.lastIndex;continue t}}y+=1}return{width:x?D:O,index:x?k:E,truncated:x,ellipsed:x&&n>=s}},$r=yr;var Yn={limit:1/0,ellipsis:"",ellipsisWidth:0},Xn=(t,e={})=>$r(t,Yn,e).width,W=Xn;var Ut="\x1B",xr="\x9B",Zn=39,Ee="\x07",Sr="[",Qn="]",Rr="m",Ie=`${Qn}8;;`,vr=new RegExp(`(?:\\${Sr}(?<code>\\d+)m|\\${Ie}(?<uri>.*)${Ee})`,"y"),wr=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},br=(t)=>`${Ut}${Sr}${t}${Rr}`,Cr=(t)=>`${Ut}${Ie}${t}${Ee}`,Re=(t,e,r)=>{let n=e[Symbol.iterator](),i=!1,s=!1,o=t.at(-1),a=o===void 0?0:W(o),l=n.next(),u=n.next(),m=0;while(!l.done){let f=l.value,p=W(f);if(a+p<=r)t[t.length-1]+=f;else t.push(f),a=0;if(f===Ut||f===xr)i=!0,s=e.startsWith(Ie,m+1);if(i){if(s){if(f===Ee)i=!1,s=!1}else if(f===Rr)i=!1}else if(a+=p,a===r&&!u.done)t.push(""),a=0;l=u,u=n.next(),m+=f.length}if(o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1)t[t.length-2]+=t.pop()},ti=(t)=>{let e=t.split(" "),r=e.length;while(r){if(W(e[r-1]))break;r--}if(r===e.length)return t;return e.slice(0,r).join(" ")+e.slice(r).join("")},ei=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",i,s,o=t.split(" "),a=[""],l=0;for(let f=0;f<o.length;f++){let p=o[f];if(r.trim!==!1){let h=a.at(-1)??"",y=h.trimStart();if(h.length!==y.length)a[a.length-1]=y,l=W(y)}if(f!==0){if(l>=e&&(r.wordWrap===!1||r.trim===!1))a.push(""),l=0;if(l||r.trim===!1)a[a.length-1]+=" ",l++}let g=W(p);if(r.hard&&g>e){let h=e-l,y=1+Math.floor((g-h-1)/e);if(Math.floor((g-1)/e)<y)a.push("");Re(a,p,e),l=W(a.at(-1)??"");continue}if(l+g>e&&l&&g){if(r.wordWrap===!1&&l<e){Re(a,p,e),l=W(a.at(-1)??"");continue}a.push(""),l=0}if(l+g>e&&r.wordWrap===!1){Re(a,p,e),l=W(a.at(-1)??"");continue}a[a.length-1]+=p,l+=g}if(r.trim!==!1)a=a.map((f)=>ti(f));let u=a.join(`
|
|
4
|
+
`),m=!1;for(let f=0;f<u.length;f++){let p=u[f];if(n+=p,!m){if(m=p>="\uD800"&&p<="\uDBFF",m)continue}else m=!1;if(p===Ut||p===xr){vr.lastIndex=f+1;let h=vr.exec(u)?.groups;if(h?.code!==void 0){let y=Number.parseFloat(h.code);i=y===Zn?void 0:y}else if(h?.uri!==void 0)s=h.uri.length===0?void 0:h.uri}if(u[f+1]===`
|
|
5
|
+
`){if(s)n+=Cr("");let g=i?wr(i):void 0;if(i&&g)n+=br(g)}else if(p===`
|
|
6
|
+
`){if(i&&wr(i))n+=br(i);if(s)n+=Cr(s)}}return n},ri=/\r?\n/;function Z(t,e,r){return String(t).normalize().split(ri).map((n)=>ei(n,e,r)).join(`
|
|
7
|
+
`)}var G=pr(_e(),1);import{ReadStream as Ir}from"tty";function ut(t,e,r){if(!r.some((o)=>!o.disabled))return t;let n=t+e,i=Math.max(r.length-1,0),s=n<0?i:n>i?0:n;return r[s]?.disabled?ut(s,e<0?-1:1,r):s}var ai=["up","down","left","right","space","enter","cancel"],li=["January","February","March","April","May","June","July","August","September","October","November","December"],j={actions:new Set(ai),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:[...li],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function De(t,e){if(typeof t=="string")return j.aliases.get(t)===e;for(let r of t)if(r!==void 0&&De(r,e))return!0;return!1}function ui(t,e){if(t===e)return;let r=t.split(`
|
|
8
|
+
`),n=e.split(`
|
|
9
|
+
`),i=Math.max(r.length,n.length),s=[];for(let o=0;o<i;o++)r[o]!==n[o]&&s.push(o);return{lines:s,numLinesBefore:r.length,numLinesAfter:n.length,numLines:i}}var ci=globalThis.process.platform.startsWith("win"),Ae=Symbol("clack:cancel");function Rt(t){return t===Ae}function jt(t,e){let r=t;r.isTTY&&r.setRawMode(e)}function _r({input:t=Pr,output:e=Te,overwrite:r=!0,hideCursor:n=!0}={}){let i=st.createInterface({input:t,output:e,prompt:"",tabSize:1});st.emitKeypressEvents(t,i),t instanceof Ir&&t.isTTY&&t.setRawMode(!0);let s=(o,{name:a,sequence:l})=>{let u=String(o);if(De([u,a,l],"cancel")){n&&e.write(G.cursor.show),process.exit(0);return}if(!r)return;st.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{st.clearLine(e,1,()=>{t.once("keypress",s)})})};return n&&e.write(G.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),n&&e.write(G.cursor.show),t instanceof Ir&&t.isTTY&&!ci&&t.setRawMode(!1),i.terminal=!1,i.close()}}var Et=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,Oe=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function ot(t,e,r,n=r,i=r,s){let o=Et(t??Te);return Z(e,o-r.length,{hard:!0,trim:!1}).split(`
|
|
10
|
+
`).map((a,l,u)=>{let m=s?s(a,l):a;return l===0?`${n}${m}`:l===u.length-1?`${i}${m}`:`${r}${m}`}).join(`
|
|
11
|
+
`)}function Ar(t,e){if("~standard"in t){let r=t["~standard"].validate(e);if(r instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return r.issues?.at(0)?.message}return t(e)}class It{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:r=Pr,output:n=Te,render:i,signal:s,...o}=t;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=e,this._abortSignal=s,this.input=r,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let r=this._subscribers.get(t)??[];r.push(e),this._subscribers.set(t,r)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let r=this._subscribers.get(t)??[],n=[];for(let i of r)i.cb(...e),i.once&&n.push(()=>r.splice(r.indexOf(i),1));for(let i of n)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Ae);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=oi.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),jt(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(G.cursor.show),this.output.off("resize",this.render),jt(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(G.cursor.show),this.output.off("resize",this.render),jt(this.input,!1),t(Ae)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),e?.name&&(!this._track&&j.aliases.has(e.name)&&this.emit("cursor",j.aliases.get(e.name)),j.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let r=Ar(this.opts.validate,this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}De([t,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
12
|
+
`),jt(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Z(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
|
+
`).length-1;this.output.write(G.cursor.move(-999,t*-1))}render(){let t=Z(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(G.cursor.hide);else{let e=ui(this._prevFrame,t),r=Oe(this.output);if(this.restoreCursor(),e){let n=Math.max(0,e.numLinesAfter-r),i=Math.max(0,e.numLinesBefore-r),s=e.lines.find((o)=>o>=n);if(s===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(G.cursor.move(0,s-i)),this.output.write(G.erase.lines(1));let o=t.split(`
|
|
14
|
+
`);this.output.write(o[s]),this._prevFrame=t,this.output.write(G.cursor.move(0,o.length-s-1));return}else if(e.lines.length>1){if(n<i)s=n;else{let a=s-i;a>0&&this.output.write(G.cursor.move(0,a))}this.output.write(G.erase.down());let o=t.split(`
|
|
15
|
+
`).slice(s);this.output.write(o.join(`
|
|
16
|
+
`)),this._prevFrame=t;return}}this.output.write(G.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}class ke extends It{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(G.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class Le extends It{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((r)=>r.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((r)=>!t.includes(r.value));this.value=e.map((r)=>r.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),0);this.cursor=this.options[e]?.disabled?ut(e,1,this.options):e,this.on("key",(r,n)=>{n.name==="a"&&this.toggleAll(),n.name==="i"&&this.toggleInvert()}),this.on("cursor",(r)=>{switch(r){case"left":case"up":this.cursor=ut(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ut(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Tr=class extends It{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let r=this.options.findIndex(({value:i})=>i===e.initialValue),n=r===-1?0:r;this.cursor=this.options[n]?.disabled?ut(n,1,this.options):n,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=ut(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ut(this.cursor,1,this.options);break}this.changeValue()})}};class Fe extends It{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let e=t.slice(0,this.cursor),r=t.slice(this.cursor,this.cursor+1),n=t.slice(this.cursor+1);return`${e}${si("inverse",r)}${n}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as c,stripVTControlCharacters as ko}from"util";import q from"process";var _t=pr(_e(),1);function pi(){if(q.platform!=="win32")return q.env.TERM!=="linux";return Boolean(q.env.CI)||Boolean(q.env.WT_SESSION)||Boolean(q.env.TERMINUS_SUBLIME)||q.env.ConEmuTask==="{cmd::Cmder}"||q.env.TERM_PROGRAM==="Terminus-Sublime"||q.env.TERM_PROGRAM==="vscode"||q.env.TERM==="xterm-256color"||q.env.TERM==="alacritty"||q.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Ne=pi(),di=()=>process.env.CI==="true";var A=(t,e)=>Ne?t:e,mi=A("\u25C6","*"),Fr=A("\u25A0","x"),Nr=A("\u25B2","x"),Ht=A("\u25C7","o"),hi=A("\u250C","T"),R=A("\u2502","|"),at=A("\u2514","\u2014"),Mo=A("\u2510","T"),Uo=A("\u2518","\u2014"),Me=A("\u25CF",">"),Gt=A("\u25CB"," "),fi=A("\u25FB","[\u2022]"),Dr=A("\u25FC","[+]"),Or=A("\u25FB","[ ]"),jo=A("\u25AA","\u2022"),kr=A("\u2500","-"),gi=A("\u256E","+"),yi=A("\u251C","+"),$i=A("\u256F","+"),vi=A("\u2570","+"),Vo=A("\u256D","+"),wi=A("\u25CF","\u2022"),bi=A("\u25C6","*"),Ci=A("\u25B2","!"),xi=A("\u25A0","x"),Bt=(t)=>{switch(t){case"initial":case"active":return c("cyan",mi);case"cancel":return c("red",Fr);case"error":return c("yellow",Nr);case"submit":return c("green",Ht)}},Mr=(t)=>{switch(t){case"initial":case"active":return c("cyan",R);case"cancel":return c("red",R);case"error":return c("yellow",R);case"submit":return c("green",R)}};function Ur(t,e){let r=[`${e?`${c("cyan",R)} `:""}${t.join(" \u2022 ")}`];return e&&r.push(c("cyan",at)),r}var Lr=(t,e,r,n,i,s=!1)=>{let o=e,a=0;if(s)for(let l=n-1;l>=r;l--){let u=t[l];if(u&&(o-=u.length),a++,o<=i)break}else for(let l=r;l<n;l++){let u=t[l];if(u&&(o-=u.length),a++,o<=i)break}return{lineCount:o,removals:a}},Ue=({cursor:t,options:e,style:r,output:n=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Et(n)-s,l=Oe(n),u=c("dim","..."),m=Math.max(l-o,0),f=Math.max(Math.min(i,m),5),p=0;t>=f-3&&(p=Math.max(Math.min(t-f+3,e.length-f),0));let g=f<e.length&&p>0,h=f<e.length&&p+f<e.length,y=Math.min(p+f,e.length),E=[],_=0;g&&_++,h&&_++;let x=p+(g?1:0),k=y-(h?1:0);for(let S=x;S<k;S++){let L=e[S],O=L?r(L,S===t):"",b=Z(O,a,{hard:!0,trim:!1}).split(`
|
|
17
|
+
`);E.push(b),_+=b.length}if(_>m){let S=0,L=0,O=_,b=t-x,I=m,V=()=>Lr(E,O,0,b,I),B=()=>Lr(E,O,b+1,E.length,I,!0);g?({lineCount:O,removals:S}=V(),O>I&&(h||(I-=1),{lineCount:O,removals:L}=B())):(h||(I-=1),{lineCount:O,removals:L}=B(),O>I&&(I-=1,{lineCount:O,removals:S}=V())),S>0&&(g=!0,E.splice(0,S)),L>0&&(h=!0,E.splice(E.length-L,L))}let D=[];g&&D.push(u);for(let S of E)for(let L of S)D.push(L);return h&&D.push(u),D};var jr=(t)=>{let e=t.active??"Yes",r=t.inactive??"No";return new ke({active:e,inactive:r,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let n=t.withGuide??j.withGuide,i=`${Bt(this.state)} `,s=n?`${c("gray",R)} `:"",o=ot(t.output,t.message,s,i),a=`${n?`${c("gray",R)}
|
|
18
|
+
`:""}${o}
|
|
19
|
+
`,l=this.value?e:r;switch(this.state){case"submit":{let u=n?`${c("gray",R)} `:"";return`${a}${u}${c("dim",l)}`}case"cancel":{let u=n?`${c("gray",R)} `:"";return`${a}${u}${c(["strikethrough","dim"],l)}${n?`
|
|
20
|
+
${c("gray",R)}`:""}`}default:{let u=n?`${c("cyan",R)} `:"",m=n?c("cyan",at):"";return`${a}${u}${this.value?`${c("green",Me)} ${e}`:`${c("dim",Gt)} ${c("dim",e)}`}${t.vertical?n?`
|
|
21
|
+
${c("cyan",R)} `:`
|
|
22
|
+
`:` ${c("dim","/")} `}${this.value?`${c("dim",Gt)} ${c("dim",r)}`:`${c("green",Me)} ${r}`}
|
|
23
|
+
${m}
|
|
24
|
+
`}}}}).prompt()};var Wt=async(t,e)=>{let r={},n=Object.keys(t);for(let i of n){let s=t[i],o=await s({results:r})?.catch((a)=>{throw a});if(typeof e?.onCancel=="function"&&Rt(o)){r[i]="canceled",e.onCancel({results:r});continue}r[i]=o}return r},Si=[`${c("dim","\u2191/\u2193")} to navigate`,`${c("dim","Space:")} select`,`${c("dim","Enter:")} confirm`],Pt=(t,e)=>t.split(`
|
|
25
|
+
`).map((r)=>e(r)).join(`
|
|
26
|
+
`),Vr=(t)=>{let e=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${c("gray",Or)} ${Pt(o,(a)=>c(["strikethrough","gray"],a))}${i.hint?` ${c("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${c("cyan",fi)} ${o}${i.hint?` ${c("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${c("green",Dr)} ${Pt(o,(a)=>c("dim",a))}${i.hint?` ${c("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${Pt(o,(a)=>c(["strikethrough","dim"],a))}`:s==="active-selected"?`${c("green",Dr)} ${o}${i.hint?` ${c("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${Pt(o,(a)=>c("dim",a))}`:`${c("dim",Or)} ${Pt(o,(a)=>c("dim",a))}`},r=t.required??!0,n=t.showInstructions??!0;return new Le({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:r,cursorAt:t.cursorAt,validate(i){if(r&&(i===void 0||i.length===0))return`Please select at least one option.
|
|
27
|
+
${c("reset",c("dim",`Press ${c(["gray","bgWhite","inverse"]," space ")} to select, ${c("gray",c("bgWhite",c("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??j.withGuide,s=ot(t.output,t.message,i?`${Mr(this.state)} `:"",`${Bt(this.state)} `),o=`${i?`${c("gray",R)}
|
|
28
|
+
`:""}${s}
|
|
29
|
+
`,a=this.value??[],l=(u,m)=>{if(u.disabled)return e(u,"disabled");let f=a.includes(u.value);return m&&f?e(u,"active-selected"):f?e(u,"selected"):e(u,m?"active":"inactive")};switch(this.state){case"submit":{let u=this.options.filter(({value:f})=>a.includes(f)).map((f)=>e(f,"submitted")).join(c("dim",", "))||c("dim","none"),m=ot(t.output,u,i?`${c("gray",R)} `:"");return`${o}${m}`}case"cancel":{let u=this.options.filter(({value:f})=>a.includes(f)).map((f)=>e(f,"cancelled")).join(c("dim",", "));if(u.trim()==="")return`${o}${c("gray",R)}`;let m=ot(t.output,u,i?`${c("gray",R)} `:"");return`${o}${m}${i?`
|
|
30
|
+
${c("gray",R)}`:""}`}case"error":{let u=i?`${c("yellow",R)} `:"",m=this.error.split(`
|
|
31
|
+
`).map((g,h)=>h===0?`${i?`${c("yellow",at)} `:""}${c("yellow",g)}`:` ${g}`).join(`
|
|
32
|
+
`),f=o.split(`
|
|
33
|
+
`).length,p=m.split(`
|
|
34
|
+
`).length+1;return`${o}${u}${Ue({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:f+p,style:l}).join(`
|
|
35
|
+
${u}`)}
|
|
36
|
+
${m}
|
|
37
|
+
`}default:{let u=i?`${c("cyan",R)} `:"",m=o.split(`
|
|
38
|
+
`).length,f=n?Ur(Si,i):i?[c("cyan",at)]:[],p=f.join(`
|
|
39
|
+
`),g=f.length+1;return`${o}${u}${Ue({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:m+g,style:l}).join(`
|
|
40
|
+
${u}`)}
|
|
47
41
|
${p}
|
|
48
|
-
`}}}}).prompt()};var
|
|
49
|
-
`);if(
|
|
42
|
+
`}}}}).prompt()};var w={message:(t=[],{symbol:e=c("gray",R),secondarySymbol:r=c("gray",R),output:n=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??j.withGuide,l=a?r:"",u=a?`${e} `:"",m=a?`${r} `:"";for(let p=0;p<i;p++)o.push(l);let f=Array.isArray(t)?t:t.split(`
|
|
43
|
+
`);if(f.length>0){let[p,...g]=f;p.length>0?o.push(`${u}${p}`):o.push(a?e:"");for(let h of g)h.length>0?o.push(`${m}${h}`):o.push(a?r:"")}n.write(`${o.join(`
|
|
50
44
|
`)}
|
|
51
|
-
`)},info:(
|
|
52
|
-
`)},
|
|
53
|
-
${
|
|
45
|
+
`)},info:(t,e)=>{w.message(t,{...e,symbol:c("blue",wi)})},success:(t,e)=>{w.message(t,{...e,symbol:c("green",bi)})},step:(t,e)=>{w.message(t,{...e,symbol:c("green",Ht)})},warn:(t,e)=>{w.message(t,{...e,symbol:c("yellow",Ci)})},warning:(t,e)=>{w.warn(t,e)},error:(t,e)=>{w.message(t,{...e,symbol:c("red",xi)})}};var Kt=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??j.withGuide?`${c("gray",hi)} `:"";r.write(`${n}${t}
|
|
46
|
+
`)},Jt=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??j.withGuide?`${c("gray",R)}
|
|
47
|
+
${c("gray",at)} `:"";r.write(`${n}${t}
|
|
54
48
|
|
|
55
|
-
`)};var Ri=(
|
|
56
|
-
`),
|
|
57
|
-
`).map(
|
|
58
|
-
`),
|
|
59
|
-
`:"",
|
|
49
|
+
`)};var Ri=(t)=>t,Ei=(t,e,r)=>{let n={hard:!0,trim:!1},i=Z(t,e,n).split(`
|
|
50
|
+
`),s=i.reduce((l,u)=>Math.max(W(u),l),0),o=i.map(r).reduce((l,u)=>Math.max(W(u),l),0),a=e-(o-s);return Z(t,a,n)},yt=(t="",e="",r)=>{let n=r?.output??q.stdout,i=r?.withGuide??j.withGuide,s=r?.format??Ri,o=["",...Ei(t,Et(n)-6,s).split(`
|
|
51
|
+
`).map(s),""],a=W(e),l=Math.max(o.reduce((p,g)=>{let h=W(g);return h>p?h:p},0),a)+2,u=o.map((p)=>`${c("gray",R)} ${p}${" ".repeat(l-W(p))}${c("gray",R)}`).join(`
|
|
52
|
+
`),m=i?`${c("gray",R)}
|
|
53
|
+
`:"",f=i?yi:vi;n.write(`${m}${c("green",Ht)} ${c("reset",e)} ${c("gray",kr.repeat(Math.max(l-a-1,1))+gi)}
|
|
54
|
+
${u}
|
|
55
|
+
${c("gray",f+kr.repeat(l+2)+$i)}
|
|
56
|
+
`)};var Ii=(t)=>c("magenta",t),K=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:i,frames:s=Ne?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Ne?80:120,signal:a,...l}={})=>{let u=di(),m,f,p=!1,g=!1,h="",y,E=performance.now(),_=Et(r),x=l?.styleFrame??Ii,k=(F)=>{let J=F>1?i??j.messages.error:n??j.messages.cancel;g=F===1,p&&(St(J,F),g&&typeof e=="function"&&e())},D=()=>k(2),S=()=>k(1),L=()=>{process.on("uncaughtExceptionMonitor",D),process.on("unhandledRejection",D),process.on("SIGINT",S),process.on("SIGTERM",S),process.on("exit",k),a&&a.addEventListener("abort",S)},O=()=>{process.removeListener("uncaughtExceptionMonitor",D),process.removeListener("unhandledRejection",D),process.removeListener("SIGINT",S),process.removeListener("SIGTERM",S),process.removeListener("exit",k),a&&a.removeEventListener("abort",S)},b=()=>{if(y===void 0)return;u&&r.write(`
|
|
57
|
+
`);let F=Z(y,_,{hard:!0,trim:!1}).split(`
|
|
58
|
+
`);F.length>1&&r.write(_t.cursor.up(F.length-1)),r.write(_t.cursor.to(0)),r.write(_t.erase.down())},I=(F)=>F.replace(/\.+$/,""),V=(F)=>{let J=(performance.now()-F)/1000,et=Math.floor(J/60),rt=Math.floor(J%60);return et>0?`[${et}m ${rt}s]`:`[${rt}s]`},B=l.withGuide??j.withGuide,Nt=(F="")=>{p=!0,m=_r({output:r}),h=I(F),E=performance.now(),B&&r.write(`${c("gray",R)}
|
|
59
|
+
`);let J=0,et=0;L(),f=setInterval(()=>{if(u&&h===y)return;b(),y=h;let rt=x(s[J]),Mt;if(u)Mt=`${rt} ${h}...`;else if(t==="timer")Mt=`${rt} ${h} ${V(E)}`;else{let Fn=".".repeat(Math.floor(et)).slice(0,3);Mt=`${rt} ${h}${Fn}`}let Ln=Z(Mt,_,{hard:!0,trim:!1});r.write(Ln),J=J+1<s.length?J+1:0,et=et<4?et+0.125:0},o)},St=(F="",J=0,et=!1)=>{if(!p)return;p=!1,clearInterval(f),b();let rt=J===0?c("green",Ht):J===1?c("red",Fr):c("red",Nr);h=F??h,et||(t==="timer"?r.write(`${rt} ${h} ${V(E)}
|
|
60
|
+
`):r.write(`${rt} ${h}
|
|
61
|
+
`)),O(),m()};return{start:Nt,stop:(F="")=>St(F,0),message:(F="")=>{h=I(F??h)},cancel:(F="")=>St(F,1),error:(F="")=>St(F,2),clear:()=>St("",0,!0),get isCancelled(){return g}}},Go={light:A("\u2500","-"),heavy:A("\u2501","="),block:A("\u2588","#")};var Pi=[`${c("dim","\u2191/\u2193")} to navigate`,`${c("dim","Enter:")} confirm`],Vt=(t,e)=>t.includes(`
|
|
62
|
+
`)?t.split(`
|
|
63
|
+
`).map((r)=>e(r)).join(`
|
|
64
|
+
`):e(t),Gr=(t)=>{let e=(n,i)=>{if(n===void 0)return"";let s=n.label??String(n.value);switch(i){case"disabled":return`${c("gray",Gt)} ${Vt(s,(o)=>c("gray",o))}${n.hint?` ${c("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${Vt(s,(o)=>c("dim",o))}`;case"active":return`${c("green",Me)} ${s}${n.hint?` ${c("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${Vt(s,(o)=>c(["strikethrough","dim"],o))}`;default:return`${c("dim",Gt)} ${Vt(s,(o)=>c("dim",o))}`}},r=t.showInstructions??!0;return new Tr({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let n=t.withGuide??j.withGuide,i=`${Bt(this.state)} `,s=`${Mr(this.state)} `,o=ot(t.output,t.message,s,i),a=`${n?`${c("gray",R)}
|
|
65
|
+
`:""}${o}
|
|
66
|
+
`;switch(this.state){case"submit":{let l=n?`${c("gray",R)} `:"",u=ot(t.output,e(this.options[this.cursor],"selected"),l);return`${a}${u}`}case"cancel":{let l=n?`${c("gray",R)} `:"",u=ot(t.output,e(this.options[this.cursor],"cancelled"),l);return`${a}${u}${n?`
|
|
67
|
+
${c("gray",R)}`:""}`}default:{let l=n?`${c("cyan",R)} `:"",u=a.split(`
|
|
68
|
+
`).length,m=r?Ur(Pi,n):n?[c("cyan",at)]:[],f=m.join(`
|
|
69
|
+
`),p=m.length+1;return`${a}${l}${Ue({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:u+p,style:(g,h)=>e(g,g.disabled?"disabled":h?"active":"inactive")}).join(`
|
|
70
|
+
${l}`)}
|
|
60
71
|
${f}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
`)
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
`).map((e)=>n(e)).join(`
|
|
70
|
-
`)
|
|
71
|
-
`:""}${a}
|
|
72
|
-
|
|
73
|
-
${
|
|
74
|
-
`)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
`
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
${
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
`}}}}).prompt();var Ei=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Je=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Hi=["bold","dim","italic","underline","reset"],Ke={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Ui={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"},Ni={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},We={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function Zr(r){return(n)=>Ei?`${r}${n}${Ke.reset}`:n}function Ai(r){for(let n=0;n<r.length;n++){let e=r.charCodeAt(n);if(e<32&&e!==27)return!1}return!0}function Ye({bright:r=!1,color:n}){let e=Bun.color(n,"ansi"),o=typeof e==="string"&&e.length>0&&Ai(e)?e:Ui[n];if(!o)return"";return r&&o in We?We[o]:o}var ji=Je.reduce((r,n)=>{let e=Ye({color:n});if(e)r[n]=Zr(e);let o=Ye({bright:!0,color:n});if(o)r[`${n}Bright`]=Zr(o);return r},{}),Mi=Hi.reduce((r,n)=>{return r[n]=Zr(Ke[n]),r},{}),Gi=Je.reduce((r,n)=>{let e=Ni[n];if(e){let o=`bg${n.charAt(0).toUpperCase()}${n.slice(1)}`;r[o]=Zr(e)}return r},{}),m={...ji,...Mi,...Gi};function Qr(r){if(Cr(r))throw new Q;return r}function qi(r){return r.map((n)=>n.key?`${m.bold(n.key)} ${m.dim(n.text)}`:m.dim(n.text)).join(m.dim(" \xB7 "))}function Xr(r){v.info(qi(r))}var Sr={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 sr(r){return Xr(Sr.confirm),Qr(await Ge(r))}async function rr(r){return Xr(Sr.text),Qr(await ze(r))}async function cr(r){return Xr(Sr.select),Qr(await qe({showInstructions:!1,...r}))}async function fr(r){return Xr(Sr.multiselect),Qr(await xe({showInstructions:!1,...r}))}var zi=4;function dr(r,n=0){if(n>=zi)return;let e=[...r instanceof AggregateError?r.errors:[],...r.cause!==void 0?[r.cause]:[]];for(let o of e){if(v.info(m.dim(`caused by: ${o instanceof Error?o.message:String(o)}`)),o instanceof w&&o.hint)v.info(m.dim(` ${o.hint}`));if(o instanceof Error)dr(o,n+1)}}function Mn(r){return r==null?[]:Array.isArray(r)?r:[r]}function Wi(r,n,e,o){var i,t=r[n],a=~o.string.indexOf(n)?e==null||e===!0?"":String(e):typeof e==="boolean"?e:~o.boolean.indexOf(n)?e==="false"?!1:e==="true"||(r._.push((i=+e,i*0===0)?i:e),!!e):(i=+e,i*0===0)?i:e;r[n]=t==null?a:Array.isArray(t)?t.concat(a):[t,a]}function Vr(r,n){r=r||[],n=n||{};var e,o,i,t,a,s={_:[]},c=0,f=0,d=0,g=r.length;let p=n.alias!==void 0,h=n.unknown!==void 0,l=n.default!==void 0;if(n.alias=n.alias||{},n.string=Mn(n.string),n.boolean=Mn(n.boolean),p)for(e in n.alias){o=n.alias[e]=Mn(n.alias[e]);for(c=0;c<o.length;c++)(n.alias[o[c]]=o.concat(e)).splice(c,1)}for(c=n.boolean.length;c-- >0;){o=n.alias[n.boolean[c]]||[];for(f=o.length;f-- >0;)n.boolean.push(o[f])}for(c=n.string.length;c-- >0;){o=n.alias[n.string[c]]||[];for(f=o.length;f-- >0;)n.string.push(o[f])}if(l){for(e in n.default)if(t=typeof n.default[e],o=n.alias[e]=n.alias[e]||[],n[t]!==void 0){n[t].push(e);for(c=0;c<o.length;c++)n[t].push(o[c])}}let b=h?Object.keys(n.alias):[];for(c=0;c<g;c++){if(i=r[c],i==="--"){s._=s._.concat(r.slice(++c));break}for(f=0;f<i.length;f++)if(i.charCodeAt(f)!==45)break;if(f===0)s._.push(i);else if(i.substring(f,f+3)==="no-"){if(t=i.substring(f+3),h&&!~b.indexOf(t))return n.unknown(i);s[t]=!1}else{for(d=f+1;d<i.length;d++)if(i.charCodeAt(d)===61)break;t=i.substring(f,d),a=i.substring(++d)||(c+1===g||(""+r[c+1]).charCodeAt(0)===45||r[++c]),o=f===2?[t]:t;for(d=0;d<o.length;d++){if(t=o[d],h&&!~b.indexOf(t))return n.unknown("-".repeat(f)+t);Wi(s,t,d+1<o.length||a,n)}}}if(l){for(e in n.default)if(s[e]===void 0)s[e]=n.default[e]}if(p)for(e in s){o=n.alias[e]||[];while(o.length>0)s[o.shift()]=s[e]}return s}var Yi=1;function gr(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Oe(r){let n={alias:{},boolean:[],default:{},string:[]};for(let[e,o]of Object.entries(r)){if(o.type==="boolean")n.boolean.push(e);else n.string.push(e);if(o.alias)n.alias[o.alias]=e;let i=gr(e);if(i!==e)n.alias[i]=e;if(o.default!==void 0)n.default[e]=o.default}return n}function Ji(r,n){if(r in n)return`--${gr(r)}`;let e=Object.entries(n).find(([,o])=>o.alias===r)?.[0];if(e)return`--${gr(e)}`;return r.length===Yi?`-${r}`:`--${gr(r)}`}function Ze(r,n){for(let[o,i]of Object.entries(r))if(Array.isArray(i))throw new w(`${Ji(o,n)} can only be provided once`);let e={...r};for(let[o,i]of Object.entries(n)){if(i.type!=="number")continue;let t=r[o];if(t===void 0||typeof t==="boolean")continue;let a=Number(t);if(Number.isNaN(a))throw Error(`Invalid number for --${o}: "${t}"`);e[o]=a}return e}function Qe(r,n){let e=Oe(n),o=Vr(r,e),i=o._[0],t=i?r.indexOf(i):-1,{_:a,...s}=o,c=Object.fromEntries(Object.entries(s).filter(([d])=>(d in n)||(d in e.alias))),f=Ze(c,n);return{command:i,flags:f,restArgs:t>=0?r.slice(t+1):[]}}function Gn(r,n={}){let e=Oe(n),o=Vr(r,e),{_:i,...t}=o;return{args:Ze(t,n),rawPositionals:i}}function xn(r,n){let e={},o=Object.entries(n);for(let[i,[t,a]]of o.entries())e[t]=a.variadic?r.slice(i):r[i];return e}function Xe(r,n){for(let[e,o]of Object.entries(n)){if(!o.required)continue;let i=r[e];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${e}${o.variadic?"...":""}>`}return null}var Ki=(r)=>r,C={arg:m.magenta,cmd:m.cyan,default:m.bold,desc:Ki,flag:m.green,header:(r)=>m.bold(m.yellow(r)),hint:m.dim,name:(r)=>m.bold(m.cyan(r)),placeholder:m.magenta};class qn{metadata;commands;globalArgs;constructor(r,n,e){this.metadata=r;this.commands=n;this.globalArgs=e}version(){return`${C.name(this.metadata.name)} ${C.hint(this.metadata.version??"0.0.0")}`}global(){let r=[],{name:n,bin:e,version:o,description:i}=this.metadata;if(r.push(`${C.name(n)}${o?` ${C.hint(`v${o}`)}`:""}`),i)r.push(C.desc(i));r.push(""),r.push(C.header("Usage:")),r.push(` ${C.cmd(e)} ${C.placeholder("[command]")} ${C.placeholder("[options]")}`),r.push(""),r.push(C.header("Commands:"));let t=Array.from(this.commands.values()).map((a)=>[` ${C.cmd(a.name)}`,C.desc(a.description)]);return r.push(...this.formatColumns(t)),r.push(""),r.push(C.header("Options:")),r.push(...this.formatArgDefs(this.globalArgs)),r.push(""),r.push(`${C.hint("Run")} ${C.cmd(`${e} <command> --help`)} ${C.hint("for command details.")}`),r.join(`
|
|
87
|
-
`)
|
|
88
|
-
`).
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
`)
|
|
92
|
-
`).
|
|
93
|
-
`)}function mr(r){let n=r,e=0;while(n>=to&&e<ao.length-1)n/=to,e++;return`${e===0?String(n):n.toFixed(nt)} ${ao[e]??"B"}`}var uo="actions/runner",st={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},po=["bin"],mo=["externals"];class on{profile;sharedPath=null;constructor(r){this.profile=r}async download(){let r=st[this.profile.os],n=await this.getLatestVersion(),e=D(ur,"github",n);if(Er(e))return this.sharedPath=e,{path:e,version:n};await On(e,{recursive:!0});let o=`actions-runner-${r}-${n}.tar.gz`,i=D(e,o),t=`https://github.com/${uo}/releases/download/v${n}/${o}`;return await Bun.$`curl -sL -o ${i} ${t}`,await Bun.$`tar xzf ${i} -C ${e}`,await fo(i),this.sharedPath=e,{path:e,version:n}}async create(r){let n=await this.ensureDownloaded(),e=[];for(let o of r){let i=D(this.profile.directory,o);await this.setupRunnerDir(n,i),await this.registerRunner(i,o),e.push({directory:i,id:o,name:o,status:"registered"})}return e}async remove(r){for(let n of r){let e=D(this.profile.directory,n);if(!Er(D(e,".runner")))continue;let o=await this.fetchRemovalToken(e);await Bun.$`bash ./config.sh remove --token ${o}`.cwd(e).quiet().nothrow()}}async start(r){for(let n of r){let e=D(this.profile.directory,n),o=await this.readPidFile(e);if(o&&this.isProcessRunning(o))continue;let i=Bun.spawn(["bash","./run.sh"],{cwd:en(e),stderr:"pipe",stdout:"pipe"});i.unref(),await this.writePidFile(e,i.pid)}}async stop(r){for(let n of r){let e=D(this.profile.directory,n);if(!await this.readPidFile(e))continue;let i=en(e);await Bun.$`pkill -f ${i}`.quiet().nothrow(),await this.removePidFile(e)}}async list(){let r=this.profile.directory;if(!Er(r))return[];let n=await co(r,{withFileTypes:!0}),e=[];for(let o of n){if(!o.isDirectory())continue;let i=D(r,o.name);e.push(await this.getRunnerStatus(i,o.name))}return e}async currentVersion(r){let n=D(this.profile.directory,r);return this.detectVersion(n)}async logFiles(r){return Ir(D(this.profile.directory,r,Dr))}async update(r){let n=await this.ensureDownloaded();for(let e of r){let o=D(this.profile.directory,e);await this.removeRunnerBinaries(o),await this.setupRunnerDir(n,o)}}async getRunnerStatus(r,n){let e=await this.readRunnerName(r),o=await this.readPidFile(r),i=o!==null&&this.isProcessRunning(o),t="unknown";if(i)t="running";else if(Er(D(r,".runner")))t="registered";return{directory:r,id:n,name:e,pid:i?o: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 On(n,{recursive:!0});for(let e of po)await this.hardLinkDir(D(r,e),D(n,e));for(let e of mo){let o=en(r,e),i=D(n,e);if(!Er(i))await tt(o,i)}for(let e of["*.sh","*.sh.template"]){let o=await Array.fromAsync(new Bun.Glob(e).scan(r));for(let i of o)await et(D(r,i),D(n,i))}}async registerRunner(r,n){let e=await this.fetchRegistrationToken(),o=["--url",this.profile.url,"--token",e,"--name",n,"--unattended"];if(this.profile.labels)o.push("--labels",this.profile.labels);if(this.profile.runnerGroup)o.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${o}`.cwd(r).quiet()}async fetchRegistrationToken(){return this.fetchRunnerToken(pr(this.profile.url),"registration-token")}async fetchRemovalToken(r){let n=await Zn(D(r,".runner"),"utf-8"),o=JSON.parse(this.stripBom(n)).gitHubUrl;if(!o)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(pr(o),"remove-token")}async fetchRunnerToken(r,n){let e=r.kind==="repo"?`repos/${r.owner}/${r.repo}/actions/runners/${n}`:`orgs/${r.org}/actions/runners/${n}`,o=r.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",i=await Bun.$`gh api ${e} --method POST --jq .token`.quiet().nothrow();if(i.exitCode!==0){let a=i.stderr.toString().trim();throw Error(`gh api ${e} failed for ${rn(r)} (${o})${a?`: ${a}`:""}`)}let t=i.stdout.toString().trim();if(!t)throw Error(`Failed to fetch ${n} for ${rn(r)}`);return t}async getLatestVersion(){return(await Bun.$`gh api repos/${uo}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(r){return en(r,".pid")}async writePidFile(r,n){await at(this.pidFilePath(r),String(n))}async readPidFile(r){try{let n=await Zn(this.pidFilePath(r),"utf-8");return Number.parseInt(n.trim(),10)}catch{return null}}async removePidFile(r){try{await fo(this.pidFilePath(r))}catch{}}async readRunnerName(r){try{let n=await Zn(D(r,".runner"),"utf-8");return JSON.parse(this.stripBom(n)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(r,n){await On(n,{recursive:!0});let e=await co(r,{withFileTypes:!0});for(let o of e){let i=D(r,o.name),t=D(n,o.name);if(o.isDirectory())await this.hardLinkDir(i,t);else await ot(i,t)}}async detectVersion(r){try{return(await it(D(r,"externals"))).match(/github\/([^/]+)/)?.[1]??null}catch{return null}}async removeRunnerBinaries(r){for(let n of po)await Qn(D(r,n),{force:!0,recursive:!0});for(let n of mo)await Qn(D(r,n),{force:!0});for(let n of["*.sh","*.sh.template"]){let e=await Array.fromAsync(new Bun.Glob(n).scan(r));for(let o of e)await Qn(D(r,o),{force:!0})}}stripBom(r){return r.replace(/^\uFEFF/,"")}isProcessRunning(r){try{return process.kill(r,0),!0}catch{return!1}}}import{existsSync as Sn}from"fs";import{readdir as Vn,readFile as ct,readlink as ft,rm as Bn,stat as ut}from"fs/promises";import{join as ar}from"path";var lo="_work",pt="externals",mt=".pid",lt="github",dt=/github\/([^/]+)/,gt=["runner","worker"],ht=24,go=3600000,Xn=10;function tn(r){return{auto:r?.auto??ro,intervalHours:r?.intervalHours??no,lastRun:r?.lastRun,olderThanDays:r?.olderThanDays??Tr,targets:r?.targets??eo}}function ho(r,n){return r-n*ht*go}function _n(r,n){if(!r.lastRun)return!0;let e=Date.parse(r.lastRun);if(Number.isNaN(e))return!0;return n-e>=r.intervalHours*go}function bo(r,n){let e=nn(r),o=new Set;for(let i of gt){let t=e.find((a)=>a.type===i);if(t)o.add(t.path)}return e.filter((i)=>!o.has(i.path)&&i.mtime.getTime()<n)}function wo(r){return[...r].sort($t)[0]??null}function vo(r,n){let e=wo(r),o=new Set(n);return r.filter((i)=>i!==e&&!o.has(i))}function Co(r){return r.match(dt)?.[1]??null}function an(r){return Object.values(r).reduce((n,e)=>n+e.freedBytes,0)}async function $o(r){try{let n=await ct(ar(r,mt),"utf-8"),e=Number.parseInt(n.trim(),Xn);if(Number.isNaN(e))return!1;return process.kill(e,0),!0}catch{return!1}}async function sn(r){if(!Sn(r))return 0;let n=await Vn(r,{withFileTypes:!0}),e=0;for(let o of n){if(o.isSymbolicLink())continue;let i=ar(r,o.name);if(o.isDirectory()){e+=await sn(i);continue}if(o.isFile()){let t=await ut(i);e+=t.size}}return e}async function cn(r){let n=ho(r.now,r.olderThanDays),e={};for(let o of r.targets)switch(o){case"logs":e.logs=await bt(r.entries,n,r.dryRun);break;case"work":e.work=await wt(r.entries,r.dryRun);break;case"shared":e.shared=await vt(r.entries,r.dryRun,r.sharedDir);break}return e}async function bt(r,n,e){let o={freedBytes:0,removed:0,skipped:[]};for(let i of r){let t=await Ir(ar(i.directory,Dr));for(let a of bo(t,n)){if(!e)await Bn(a.path,{force:!0});o.removed++,o.freedBytes+=a.size}}return o}async function wt(r,n){let e={freedBytes:0,removed:0,skipped:[]};for(let o of r){if(await $o(o.directory)){e.skipped.push(o.id);continue}let i=ar(o.directory,lo);if(!Sn(i))continue;let t=await Vn(i);if(t.length===0)continue;if(e.freedBytes+=await sn(i),e.removed+=t.length,n)continue;for(let a of t)await Bn(ar(i,a),{force:!0,recursive:!0})}return e}async function vt(r,n,e){let o={freedBytes:0,removed:0,skipped:[]},i=e??ar(ur,lt);if(!Sn(i))return o;let a=(await Vn(i,{withFileTypes:!0})).filter((c)=>c.isDirectory()).map((c)=>c.name),s=await Ct(r);for(let c of vo(a,s)){let f=ar(i,c);if(o.freedBytes+=await sn(f),o.removed++,!n)await Bn(f,{force:!0,recursive:!0})}return o}async function Ct(r){let n=[];for(let e of r)try{let o=await ft(ar(e.directory,pt)),i=Co(o);if(i)n.push(i)}catch{}return n}function $t(r,n){let e=r.split(".").map((t)=>Number.parseInt(t,Xn)),o=n.split(".").map((t)=>Number.parseInt(t,Xn)),i=Math.max(e.length,o.length);for(let t=0;t<i;t++){let a=e[t]??0,s=o[t]??0,c=Number.isNaN(a)?0:a,f=Number.isNaN(s)?0:s;if(c!==f)return f-c}return 0}function x(r){switch(r.provider){case"github":return new on(r);default:throw Error(`Runner provider "${r.provider}" is not yet implemented`)}}var yo=0,yt={logs:"file(s)",shared:"version(s)",work:"item(s)"},Pt=tr({days:{alias:"d",default:yo,description:"Override log retention",displayDefault:`config or ${Tr} days`,type:"number"},dryRun:{alias:"n",default:!1,description:"Preview cleanup without deleting",type:"boolean"},logs:{alias:"l",default:!1,description:"Remove old diagnostic logs",type:"boolean"},shared:{alias:"s",default:!1,description:"Remove unused runner versions",type:"boolean"},work:{alias:"w",default:!1,description:"Clear stopped runners' workspaces",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip workspace confirmation",type:"boolean"}});class fn extends k{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=Pt;async execute(r){let n=r.config.get("profiles");if(Object.keys(n).length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let e=tn(r.config.get("cleanup")),o=this.explicitTargets(r),i=o.length>0?o:e.targets,t=r.args.days>yo?r.args.days:e.olderThanDays;if(i.includes("work")&&!r.args.dryRun&&!r.args.yes){if(!await sr({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))i=i.filter((c)=>c!=="work")}let a=await cn({dryRun:r.args.dryRun,entries:r.config.get("runners")??[],now:Date.now(),olderThanDays:t,targets:i});if(this.printReport(a,r.args.dryRun),r.args.dryRun)return;r.config.set("cleanup",{...r.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(r){let n=[];if(r.args.logs)n.push("logs");if(r.args.work)n.push("work");if(r.args.shared)n.push("shared");return n}printReport(r,n){let e=[];for(let[t,a]of Object.entries(r)){if(!a)continue;let s=yt[t],c=mr(a.freedBytes),f=n?`would remove ${a.removed} ${s}, ${c}`:`removed ${a.removed} ${s}, freed ${c}`;if(e.push(`${m.bold(t)}: ${a.removed>0?f:m.dim("nothing to do")}`),a.skipped.length>0)e.push(m.dim(` skipped running runner(s): ${a.skipped.join(", ")}`))}if(e.length===0){v.info(m.dim("Nothing to clean."));return}let o=an(r),i=n?"Would free":"Freed";e.push(m.dim(`${i} ${mr(o)} total`)),v.info(e.join(`
|
|
94
|
-
`))}}async function Hr(r){try{let n=tn(r.config.get("cleanup"));if(!n.auto)return;if(!_n(n,Date.now()))return;let e=await cn({dryRun:!1,entries:r.config.get("runners")??[],now:Date.now(),olderThanDays:n.olderThanDays,targets:n.targets});r.config.set("cleanup",{...r.config.get("cleanup"),lastRun:new Date().toISOString()});let o=an(e);if(o>0)v.info(m.dim(`Auto cleanup freed ${mr(o)}`))}catch(n){let e=n instanceof Error?n.message:String(n);v.warn(m.yellow(`Auto cleanup failed: ${e}`))}}import{join as Ft}from"path";function wr(r,n){if(r.length===0)return n;for(let e of r)if(!n.includes(e))throw new w(`Runner "${e}" not found`);return r}function z(r,n){let e=r.get("profiles");if(Object.keys(e).length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let o=n??r.get("defaultProfile")??Lr,i=e[o];if(!i)throw new w(`Profile "${o}" not found`);return{name:o,profile:i}}async function Z(r){let n=r.get("profiles"),e=Object.keys(n);if(e.length===0)throw new w("No profiles configured","Run hydra init to set up a profile");if(e.length===1)return e[0];return cr({message:"Select profile",options:e.map((o)=>({label:o,value:o,hint:n[o]?.url}))})}var Rt=G({profile:{description:"Profile to use"},count:{description:"Runner count override"}});class un extends k{name="create";description="Download and register runners";positionals=Rt;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Z(r.config)):z(r.config,r.positionals.profile),o=r.interactive?await this.promptCount(e.numberOfMachines):r.positionals.count?Number.parseInt(r.positionals.count,10):e.numberOfMachines;if(!o||o<1)throw new w("Runner count must be at least 1");let i=x(e),t=J();t.start("Downloading runner binary...");let{version:a}=await i.download();t.stop(`Runner v${a} ready`);let s=r.config.get("runners")??[],c=s.filter((l)=>l.profile===n),f=o-c.length;if(f<=0){v.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=`${e.name}-${g++}`;if(d.has(b))continue;l++,t.start(`Registering ${b}...`),await i.create([b]),t.stop(`${m.green("+")} ${b}`),s.push({createdAt:new Date().toISOString(),directory:Ft(e.directory,b),id:b,name:b,profile:n,provider:e.provider,url:e.url})}r.config.set("runners",s);let h=n===r.config.get("defaultProfile")?"":` ${n}`;v.info(`${m.green("Created")} ${f} runner(s) for "${n}". Run ${m.green(`hydra start${h}`)} to start them.`)}async promptCount(r){let n=await rr({initialValue:String(r),message:"Number of runners to create",validate:(e)=>{let o=Number.parseInt(e??"",10);if(Number.isNaN(o)||o<1)return"Must be a positive number";return}});return Number.parseInt(n,10)}}import{existsSync as Po}from"fs";import{mkdir as Fo}from"fs/promises";var kt=G({url:{description:"GitHub repository or organization URL"}}),Lt=tr({force:{alias:"f",default:!1,description:"Overwrite an existing profile",type:"boolean"},labels:{alias:"l",description:"Set comma-separated runner labels",type:"string"},name:{alias:"n",description:"Set the runner name prefix",type:"string"},profile:{alias:"p",description:"Set the profile name",type:"string"},runners:{alias:"c",description:"Set the runner count",type:"number"}});class pn extends k{name="init";description="Set up a runner profile";positionals=kt;args=Lt;prompts=!0;async execute(r){let n=r.interactive?await this.promptProfileName(r):r.args.profile??Lr,e=!r.config.exists();if(!e&&r.config.get("profiles")[n]&&!r.args.force){if(!r.interactive)throw new w(`Profile "${n}" already exists. Use --force to overwrite.`);if(!await sr({initialValue:!1,message:`Profile "${n}" already exists. Overwrite?`}))return}await this.ensureDirectories();let i=r.interactive?await this.runInitForm():this.buildProfileFromArgs(r),t=e?{}:{...r.config.get("profiles")};if(t[n]=i,r.config.set("profiles",t),!r.config.get("defaultProfile"))r.config.set("defaultProfile",n);lr([`${m.dim("Profile:")} ${n}`,`${m.dim("URL:")} ${i.url}`,`${m.dim("Runners:")} ${i.numberOfMachines}`,`${m.dim("Name:")} ${i.name}`,i.labels?`${m.dim("Labels:")} ${i.labels}`:"","",`Run ${m.green(`${_r} create${n!==r.config.get("defaultProfile")?` ${n}`:""}`)} to provision runners.`].filter(Boolean).join(`
|
|
95
|
-
`),m.green(e?"Hydra initialized":`Profile "${n}" added`))}async promptProfileName(r){return rr({initialValue:r.args.profile??Lr,message:"Profile name"})}async ensureDirectories(){if(!Po(ur))await Fo(ur,{recursive:!0});if(!Po(kr))await Fo(kr,{recursive:!0})}async runInitForm(){let r=await Jr({url:()=>rr({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{pr(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 e=Number.parseInt(n,10);if(Number.isNaN(e)||e<1)return"Must be a positive number";return}}),labels:()=>rr({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new Q}});return{directory:kr,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 w("URL is required","Usage: hydra init <url>");return this.validateUrl(r.positionals.url),this.validateRunnerCount(r.args.runners),{directory:kr,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{pr(r)}catch(n){throw new w(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 w("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 Dt}from"fs";import{readFile as It}from"fs/promises";var Et=100,Ht={runner:"runner daemon log",worker:"job log"},Ut=tr({lines:{alias:"n",default:Et,description:"Number of lines to show",type:"number"},list:{alias:"l",default:!1,description:"List log files instead of showing one",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner log instead of a job log",type:"boolean"}}),Nt=G({id:{description:"Runner ID"}});class mn extends k{name="logs";description="Show recent runner logs";args=Ut;positionals=Nt;async execute(r){let n=r.config.get("runners")??[];if(n.length===0)throw new w("No runners found","Run hydra create to provision runners");let e=await this.resolveEntry(r,n),o=r.config.get("profiles")[e.profile];if(!o)throw new w(`Profile "${e.profile}" not found for runner "${e.id}"`,"Run hydra init to set it up");if(!Dt(e.directory))throw new w(`Runner directory not found: ${e.directory}`,"Run hydra create to provision this runner");let t=await x(o).logFiles(e.id);if(t.length===0)this.noLogs(e.id);if(r.args.list){this.printList(e,t);return}let a=this.selectFile(r,e,t);if(r.args.open){await this.openFile(a);return}await this.printTail(e,a,r.args.lines)}async resolveEntry(r,n){let e=r.positionals.id;if(e){let i=n.find((t)=>t.id===e);if(!i)throw new w(`Runner "${e}" not found`,`Known runners: ${n.map((t)=>t.id).join(", ")}`);return i}if(r.interactive)return cr({message:"Select runner",options:n.map((i)=>({hint:i.profile,label:i.name,value:i}))});let o=n[0];if(n.length===1&&o)return o;throw new w("Multiple runners found",`Pass a runner id: hydra logs <id> (${n.map((i)=>i.id).join(", ")})`)}selectFile(r,n,e){if(r.args.runner){let i=e.find((t)=>t.type==="runner");if(!i)throw new w(`No runner daemon logs found for "${n.id}"`,"Start the runner first: hydra start");return i}let o=Jn(e,"worker");if(!o)this.noLogs(n.id);if(o.fallback)v.warn(m.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return o.file}noLogs(r){throw new w(`No logs found for runner "${r}"`,"Logs appear once the runner has started; run hydra start")}printList(r,n){let e=[`${m.bold(r.name)} ${m.dim(r.directory)}`];for(let o of n){let i=o.type==="worker"?m.green("worker"):m.blue("runner");e.push(` ${i} ${o.name} ${m.dim(`${o.mtime.toISOString()} \xB7 ${mr(o.size)}`)}`)}v.info(e.join(`
|
|
96
|
-
`))}async printTail(r,n,e){let o=await It(n.path,"utf-8"),i=[`${m.bold(r.name)} ${m.dim(Ht[n.type])}`,m.dim(n.path),m.dim(`Last modified: ${n.mtime.toISOString()}`)];v.info(i.join(`
|
|
97
|
-
`)),console.log(Kn(o,e))}async openFile(r){let n=(process.env.EDITOR??"").split(" ").filter(Boolean),e=n[0];if(e){await Bun.spawn([e,...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 w("No editor configured","Set $EDITOR to open log files")}}var At=G({name:{description:"Profile name to set as default"}});class Tn extends k{name="default";description="Set the default profile";positionals=At;async execute(r){let n=r.interactive?await Z(r.config):r.positionals.name;if(!n)throw new w("Profile name is required","Usage: hydra profile default <name>");let{name:e}=z(r.config,n);if(r.config.get("defaultProfile")===e){v.info(`"${e}" is already the default profile.`);return}r.config.set("defaultProfile",e),v.info(`${m.green("Default profile set to")} "${e}".`)}}class re extends k{name="list";description="List profiles";async execute(r){let n=r.config.get("profiles"),e=Object.keys(n);if(e.length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let o=r.config.get("runners")??[],i=r.config.get("defaultProfile");for(let t of e){let a=n[t],c=await x(a).list(),f=o.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,p=t===i,h=[`${m.dim("URL:")} ${a.url}`,`${m.dim("Provider:")} ${a.provider}`,`${m.dim("OS:")} ${a.os}`,`${m.dim("Name:")} ${a.name}`,`${m.dim("Runners:")} ${f.length}/${a.numberOfMachines} created, ${m.green(`${g} running`)}`];if(a.labels)h.push(`${m.dim("Labels:")} ${a.labels}`);let l=p?`${t} ${m.dim("(default)")}`:t;lr(h.join(`
|
|
98
|
-
`),l)}v.info(m.dim(`${e.length} profile(s)`))}}import{rm as jt}from"fs/promises";import{join as Mt}from"path";var Gt=G({name:{description:"Profile name to remove"}});class ne extends k{name="remove";description="Delete a profile and its runners";positionals=Gt;async execute(r){let n=r.interactive?await Z(r.config):r.positionals.name;if(!n)throw new w("Profile name is required","Usage: hydra profile remove <name>");let{profile:e}=z(r.config,n),o=r.config.get("runners")??[],i=o.filter((c)=>c.profile===n);if(i.length>0){if(!await sr({initialValue:!0,message:`This will stop and remove ${i.length} runner(s). Continue?`}))return;await this.removeRunners(e,i.map((d)=>d.id));let f=o.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])}v.info(`${m.green("Removed")} profile "${n}".`)}async removeRunners(r,n){let e=x(r),o=J();for(let i of n)o.start(`Stopping and removing ${i}...`),await e.stop([i]),await e.remove([i]),await jt(Mt(r.directory,i),{force:!0,recursive:!0}),o.stop(`${m.red("-")} ${i}`)}}class ln extends k{name="profile";description="Manage profiles";init(){this.registerSubcommands([new re,new ne,new Tn])}}import{rm as xt}from"fs/promises";import{join as qt}from"path";var zt=G({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class dn extends k{name="remove";description="Deregister and delete runners";positionals=zt;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Z(r.config)):z(r.config,r.positionals.profile),o=r.config.get("runners")??[],i=o.filter((f)=>f.profile===n);if(i.length===0)throw new w(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=r.interactive?await this.promptRunnerSelection(i.map((f)=>f.id)):wr(r.positionals.ids??[],i.map((f)=>f.id)),a=x(e),s=J();for(let f of t)s.start(`Stopping and removing ${f}...`),await a.stop([f]),await a.remove([f]),await xt(qt(e.directory,f),{force:!0,recursive:!0}),s.stop(`${m.red("-")} ${f}`);let c=o.filter((f)=>!t.includes(f.id));r.config.set("runners",c),v.info(`${m.green("Removed")} ${t.length} runner(s).`)}async promptRunnerSelection(r){return fr({message:"Select runners to remove",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Wt=G({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class gn extends k{name="start";description="Start runners";positionals=Wt;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Z(r.config)):z(r.config,r.positionals.profile),i=(r.config.get("runners")??[]).filter((p)=>p.profile===n);if(i.length===0)throw new w(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=x(e),a=J();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((p)=>p.status==="running").map((p)=>p.id)),f=i.map((p)=>p.id).filter((p)=>!c.has(p)),d=r.interactive?await this.promptRunnerSelection(f):wr(r.positionals.ids??[],i.map((p)=>p.id)),g=0;for(let p of d){if(c.has(p)){a.start(""),a.stop(`${m.dim("\u25CF")} ${p} ${m.dim("already running")}`);continue}a.start(`Starting ${p}...`),await t.start([p]),a.stop(`${m.green("\u25B6")} ${p}`),g++}v.info(`${m.green("Started")} ${g} runner(s).`),await Hr(r)}async promptRunnerSelection(r){if(r.length===0)throw new w("All runners are already running");return fr({message:"Select runners to start",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Yt={registered:m.yellow,running:m.green,stopped:m.red,unknown:m.dim};class hn extends k{name="status";description="Show status across profiles";async execute(r){let n=r.config.get("profiles"),e=Object.keys(n);if(e.length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let o=r.config.get("runners")??[],i=0,t=0,a=[];for(let s of e){let c=n[s],d=await x(c).list();if(a.length>0)a.push("");a.push(`${m.bold(s)} ${m.dim(c.url)}`);let g=new Set(o.filter((h)=>h.profile===s).map((h)=>h.id)),p=d.filter((h)=>g.has(h.id)).sort((h,l)=>h.name.localeCompare(l.name,void 0,{numeric:!0}));this.formatRunners(p,a),i+=p.length,t+=p.filter((h)=>h.status==="running").length}a.push(""),a.push(m.dim(`${i} runner(s) total, ${t} running`)),v.info(a.join(`
|
|
99
|
-
`))}formatRunners(r,n){if(r.length===0){n.push(m.dim(" No runners."));return}for(let e of r){let o=Yt[e.status]??m.dim,i=e.pid?m.dim(` (pid: ${e.pid})`):"";n.push(` ${o("\u25CF")} ${e.name} ${o(e.status)}${i}`)}}}var Jt=G({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class bn extends k{name="stop";description="Stop runners";positionals=Jt;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Z(r.config)):z(r.config,r.positionals.profile),i=(r.config.get("runners")??[]).filter((p)=>p.profile===n);if(i.length===0)throw new w(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=x(e),a=J();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((p)=>p.status==="running").map((p)=>p.id)),f=i.map((p)=>p.id).filter((p)=>c.has(p)),d=r.interactive?await this.promptRunnerSelection(f):wr(r.positionals.ids??[],i.map((p)=>p.id)),g=0;for(let p of d){if(!c.has(p)){a.start(""),a.stop(`${m.dim("\u25CF")} ${p} ${m.dim("not running")}`);continue}a.start(`Stopping ${p}...`),await t.stop([p]),a.stop(`${m.red("\u25A0")} ${p}`),g++}v.info(`${m.green("Stopped")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new w("No runners are currently running");return fr({message:"Select runners to stop",options:r.map((n)=>({label:n,value:n})),required:!0})}}class wn extends k{name="update";description="Update runner binaries";async execute(r){let n=r.config.get("profiles"),e=r.config.get("runners")??[];if(e.length===0)throw new w("No runners found","Run hydra create to provision runners");let o=J(),i=Map.groupBy(e,(c)=>c.profile),t=null,a="",s=!1;for(let[c,f]of i){let d=n[c],g=f[0];if(!d||!g)continue;let p=x(d);if(!s){if(s=!0,o.start("Checking for updates..."),a=(await p.download()).version,t=await p.currentVersion(g.id),o.stop(`Current: v${t??"unknown"} | Latest: v${a}`),t===a){v.info(`Already on latest version ${m.dim(`(v${a})`)}`),await Hr(r);return}}let h=await p.list(),l=new Set(h.filter((b)=>b.status==="running").map((b)=>b.id));for(let b of f){let F=l.has(b.id);if(o.start(`Updating ${b.id}...`),F)await p.stop([b.id]);if(await p.update([b.id]),F)await p.start([b.id]);let I=F?` ${m.dim("(restarted)")}`:"";o.stop(`${m.green("\u2713")} ${b.id}${I}`)}}v.info(`${m.green("Updated")} ${e.length} runner(s) from v${t} to v${a}`),await Hr(r)}}class Ro extends Wn{constructor(){super(new Yn(_e,Te),{bin:_r,clearOnStart:!0,description:"Manage GitHub Actions runners on this machine.",exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:Be})}init(){this.registerCommands([new pn,new un,new gn,new bn,new hn,new mn,new fn,new dn,new wn,new ln])}}var Kt=new Ro;Kt.run();
|
|
72
|
+
`}}}}).prompt()};var Ho=`${c("gray",R)} `;var Hr=(t)=>new Fe({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??j.withGuide,r=`${`${e?`${c("gray",R)}
|
|
73
|
+
`:""}${Bt(this.state)} `}${t.message}
|
|
74
|
+
`,n=t.placeholder&&t.placeholder.length>0?c("inverse",t.placeholder[0])+c("dim",t.placeholder.slice(1)):c(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:n,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${c("yellow",this.error)}`:"",a=e?`${c("yellow",R)} `:"",l=e?c("yellow",at):"";return`${r.trim()}
|
|
75
|
+
${a}${i}
|
|
76
|
+
${l}${o}
|
|
77
|
+
`}case"submit":{let o=s?` ${c("dim",s)}`:"",a=e?c("gray",R):"";return`${r}${a}${o}`}case"cancel":{let o=s?` ${c(["strikethrough","dim"],s)}`:"",a=e?c("gray",R):"";return`${r}${a}${o}${s.trim()?`
|
|
78
|
+
${a}`:""}`}default:{let o=e?`${c("cyan",R)} `:"",a=e?c("cyan",at):"";return`${r}${o}${i}
|
|
79
|
+
${a}
|
|
80
|
+
`}}}}).prompt();var Ai=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Kr=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Ti=["bold","dim","italic","underline","reset"],Jr={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Di={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"},Oi={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"},Br={"\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 qt(t){return(e)=>Ai?`${t}${e}${Jr.reset}`:e}function ki(t){for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r<32&&r!==27)return!1}return!0}function Wr({bright:t=!1,color:e}){let r=Bun.color(e,"ansi"),n=typeof r==="string"&&r.length>0&&ki(r)?r:Di[e];if(!n)return"";return t&&n in Br?Br[n]:n}var Li=Kr.reduce((t,e)=>{let r=Wr({color:e});if(r)t[e]=qt(r);let n=Wr({bright:!0,color:e});if(n)t[`${e}Bright`]=qt(n);return t},{}),Fi=Ti.reduce((t,e)=>(t[e]=qt(Jr[e]),t),{}),Ni=Kr.reduce((t,e)=>{let r=Oi[e];if(r){let n=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[n]=qt(r)}return t},{}),d={...Li,...Fi,...Ni};function zt(t){if(Rt(t))throw new X;return t}function Ui(t){return t.map((e)=>e.key?`${d.bold(e.key)} ${d.dim(e.text)}`:d.dim(e.text)).join(d.dim(" \xB7 "))}function Yt(t){w.info(Ui(t))}var Xt={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 ct(t){return Yt(Xt.confirm),zt(await jr(t))}async function nt(t){return Yt(Xt.text),zt(await Hr(t))}async function pt(t){return Yt(Xt.select),zt(await Gr({showInstructions:!1,...t}))}async function dt(t){return Yt(Xt.multiselect),zt(await Vr({showInstructions:!1,...t}))}var ji=4;function $t(t,e=0){if(e>=ji)return;let r=[...t instanceof AggregateError?t.errors:[],...t.cause!==void 0?[t.cause]:[]];for(let n of r){if(w.info(d.dim(`caused by: ${n instanceof Error?n.message:String(n)}`)),n instanceof v&&n.hint)w.info(d.dim(` ${n.hint}`));if(n instanceof Error)$t(n,e+1)}}function je(t){return t==null?[]:Array.isArray(t)?t:[t]}function Vi(t,e,r,n){var i,s=t[e],o=~n.string.indexOf(e)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~n.boolean.indexOf(e)?r==="false"?!1:r==="true"||(t._.push((i=+r,i*0===0)?i:r),!!r):(i=+r,i*0===0)?i:r;t[e]=s==null?o:Array.isArray(s)?s.concat(o):[s,o]}function At(t,e){t=t||[],e=e||{};var r,n,i,s,o,a={_:[]},l=0,u=0,m=0,f=t.length;let p=e.alias!==void 0,g=e.unknown!==void 0,h=e.default!==void 0;if(e.alias=e.alias||{},e.string=je(e.string),e.boolean=je(e.boolean),p)for(r in e.alias){n=e.alias[r]=je(e.alias[r]);for(l=0;l<n.length;l++)(e.alias[n[l]]=n.concat(r)).splice(l,1)}for(l=e.boolean.length;l-- >0;){n=e.alias[e.boolean[l]]||[];for(u=n.length;u-- >0;)e.boolean.push(n[u])}for(l=e.string.length;l-- >0;){n=e.alias[e.string[l]]||[];for(u=n.length;u-- >0;)e.string.push(n[u])}if(h){for(r in e.default)if(s=typeof e.default[r],n=e.alias[r]=e.alias[r]||[],e[s]!==void 0){e[s].push(r);for(l=0;l<n.length;l++)e[s].push(n[l])}}let y=g?Object.keys(e.alias):[];for(l=0;l<f;l++){if(i=t[l],i==="--"){a._=a._.concat(t.slice(++l));break}for(u=0;u<i.length;u++)if(i.charCodeAt(u)!==45)break;if(u===0)a._.push(i);else if(i.substring(u,u+3)==="no-"){if(s=i.substring(u+3),g&&!~y.indexOf(s))return e.unknown(i);a[s]=!1}else{for(m=u+1;m<i.length;m++)if(i.charCodeAt(m)===61)break;s=i.substring(u,m),o=i.substring(++m)||(l+1===f||(""+t[l+1]).charCodeAt(0)===45||t[++l]),n=u===2?[s]:s;for(m=0;m<n.length;m++){if(s=n[m],g&&!~y.indexOf(s))return e.unknown("-".repeat(u)+s);Vi(a,s,m+1<n.length||o,e)}}}if(h){for(r in e.default)if(a[r]===void 0)a[r]=e.default[r]}if(p)for(r in a){n=e.alias[r]||[];while(n.length>0)a[n.shift()]=a[r]}return a}var qr=1,Gi=2;function vt(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Ve(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[r,n]of Object.entries(t)){if(n.type==="boolean")e.boolean.push(r);else e.string.push(r);if(n.alias)e.alias[n.alias]=r;let i=vt(r);if(i!==r)e.alias[i]=r;if(n.default!==void 0)e.default[r]=n.default}return e}function Zt(t,e){if(t in e)return`--${vt(t)}`;let r=Object.entries(e).find(([,n])=>n.alias===t)?.[0];if(r)return`--${vt(r)}`;return t.length===qr?`-${t}`:`--${vt(t)}`}function N(t,e,r){let{alias:n}=Ve(e),i=Object.keys(t).find((s)=>!Object.hasOwn(e,s)&&!Object.hasOwn(n,s));if(i!==void 0)throw new v(`Unknown option: ${Zt(i,e)}`,r)}function zr(t,e){for(let[n,i]of Object.entries(t))if(Array.isArray(i))throw new v(`${Zt(n,e)} can only be provided once`);let r={...t};for(let[n,i]of Object.entries(e)){if(i.type!=="number")continue;let s=t[n];if(s===void 0)continue;let o=Number(s);if(typeof s==="boolean"||typeof s==="string"&&s.trim().length===0||!Number.isFinite(o)){let a=Zt(n,e);throw new v(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}r[n]=o}return r}function Yr(t,e){let r=Ve(e);Xr(t,r,e,!0);let n=At(t,r),i=n._[0],s=i?t.indexOf(i):-1,o=At(s>=0?t.slice(0,s):t,r),{_:a,...l}=o;N(l,e,"Place command options after the command name");let{_:u,...m}=n,f=Object.fromEntries(Object.entries(m).filter(([g])=>(g in e)||(g in r.alias))),p=zr(f,e);return{command:i,flags:p,restArgs:s>=0?t.slice(s+1):[]}}function Ge(t,e={}){let r=Ve(e),n=Hi(t,r);Xr(n,r,e);let i=At(n,r),{_:s,...o}=i;return{args:zr(o,e),rawPositionals:s}}function Xr(t,e,r,n=!1){let i=new Set;for(let s of t){if(s==="--")break;let o=s.match(/^-+/)?.[0];if(!o)continue;let a=s.slice(o.length),l=a.split("=",qr)[0]??"",u=a.startsWith("no-")?[a.slice(3)]:o.length===Gi?[l]:[...l];for(let m of u){let f=Object.hasOwn(e.alias,m)?e.alias[m]??m:m;if(n&&!Object.hasOwn(r,f))continue;if(i.has(f))throw new v(`${Zt(f,r)} can only be provided once`);i.add(f)}}}function Hi(t,e){let r=!0;return t.map((n)=>{if(n==="--")r=!1;if(!r)return n;return n.replace(/^--(no-[^=]+)(=.*)?$/,(i,s,o)=>{let a=e.alias[s];return a&&e.boolean.includes(a)?`--${a}${o??""}`:i})})}function He(t,e){let r={},n=Object.entries(e);for(let[i,[s,o]]of n.entries())r[s]=o.variadic?t.slice(i):t[i];return r}function Zr(t,e){for(let[r,n]of Object.entries(e)){if(!n.required)continue;let i=t[r];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${r}${n.variadic?"...":""}>`}return null}var Bi=(t)=>t,C={arg:d.magenta,cmd:d.cyan,default:d.bold,desc:Bi,flag:d.green,header:(t)=>d.bold(d.yellow(t)),hint:d.dim,name:(t)=>d.bold(d.cyan(t)),placeholder:d.magenta};class Be{metadata;commands;globalArgs;constructor(t,e,r){this.metadata=t;this.commands=e;this.globalArgs=r}version(){return`${C.name(this.metadata.name)} ${C.hint(this.metadata.version??"0.0.0")}`}global(){let t=[],{name:e,bin:r,version:n,description:i}=this.metadata;if(t.push(`${C.name(e)}${n?` ${C.hint(`v${n}`)}`:""}`),i)t.push(C.desc(i));t.push(""),t.push(C.header("Usage:")),t.push(` ${C.cmd(r)} ${C.placeholder("[command]")} ${C.placeholder("[options]")}`),t.push(""),t.push(C.header("Commands:"));let s=Array.from(this.commands.values()).map((o)=>[` ${C.cmd(o.name)}`,C.desc(o.description)]);return t.push(...this.formatColumns(s)),t.push(""),t.push(C.header("Options:")),t.push(...this.formatArgDefs(this.globalArgs)),t.push(""),t.push(`${C.hint("Run")} ${C.cmd(`${r} <command> --help`)} ${C.hint("for command details.")}`),t.join(`
|
|
81
|
+
`).trimEnd()}command(t,e){let r=[],n=e??this.metadata.bin,i=`${n} ${t.name}`,s=`${C.cmd(n)} ${C.cmd(t.name)}`;r.push(C.name(i)),r.push(C.desc(t.description)),r.push(""),r.push(C.header("Usage:"));let o=this.formatPositionalUsage(t.positionals);if(t.hasSubcommands())r.push(` ${s} ${C.placeholder("<subcommand>")} ${C.placeholder("[options]")}`);else{let u=[s];if(o)u.push(o);u.push(C.placeholder("[options]")),r.push(` ${u.join(" ")}`)}if(t.prompts&&Object.keys(t.positionals).length>0)r.push(` ${C.hint("Omit positional arguments to run interactively.")}`);if(r.push(""),t.hasSubcommands()){r.push(C.header("Subcommands:"));let u=t.getSubcommands().map((m)=>[` ${C.cmd(m.name)}`,C.desc(m.description)]);r.push(...this.formatColumns(u)),r.push("")}if(Object.entries(t.positionals).length>0)r.push(C.header("Arguments:")),r.push(...this.formatPositionalDefs(t.positionals)),r.push("");if(Object.entries(t.args).length>0)r.push(C.header("Options:")),r.push(...this.formatArgDefs(t.args));return r.join(`
|
|
82
|
+
`).trimEnd()}formatPositionalUsage(t){return Object.entries(t).map(([e,r])=>{let n=r.variadic?`${e}...`:e;return r.required?C.arg(`<${n}>`):C.arg(`[${n}]`)}).join(" ")}formatPositionalDefs(t){let e=Object.entries(t).map(([r,n])=>{let i=n.variadic?`${r}...`:r,s=C.desc(n.description??""),o=n.required?"":C.hint(" (optional)");return[` ${C.arg(i)}`,`${s}${o}`]});return this.formatColumns(e)}formatArgDefs(t){let e=[];for(let[r,n]of Object.entries(t)){let i=n.alias?`${C.flag(`-${n.alias}`)}, `:" ",s=n.type==="boolean"?"":` ${C.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,o=`${i}${C.flag(`--${vt(r)}`)}${s}`,a=C.desc(n.description??""),l=this.formatDefault(n),u=l===void 0?"":` (default: ${C.default(l)})`;e.push([` ${o}`,`${a}${u}`])}return this.formatColumns(e)}formatDefault(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}formatColumns(t){if(t.length===0)return[];let e=Math.max(...t.map(([n])=>this.stripAnsi(n).length)),r=2;return t.map(([n,i])=>{let s=e-this.stripAnsi(n).length+r;return`${n}${" ".repeat(s)}${i}`})}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}}var it=new Uint32Array(65536),Wi=(t,e)=>{let r=t.length,n=e.length,i=1<<r-1,s=-1,o=0,a=r,l=r;while(l--)it[t.charCodeAt(l)]|=1<<l;for(l=0;l<n;l++){let u=it[e.charCodeAt(l)],m=u|o;if(u|=(u&s)+s^s,o|=~(u|s),s&=u,o&i)a++;if(s&i)a--;o=o<<1|1,s=s<<1|~(m|o),o&=m}l=r;while(l--)it[t.charCodeAt(l)]=0;return a},Ki=(t,e)=>{let r=e.length,n=t.length,i=[],s=[],o=Math.ceil(r/32),a=Math.ceil(n/32);for(let h=0;h<o;h++)s[h]=-1,i[h]=0;let l=0;for(;l<a-1;l++){let h=0,y=-1,E=l*32,_=Math.min(32,n)+E;for(let x=E;x<_;x++)it[t.charCodeAt(x)]|=1<<x;for(let x=0;x<r;x++){let k=it[e.charCodeAt(x)],D=s[x/32|0]>>>x&1,S=i[x/32|0]>>>x&1,L=k|h,O=((k|S)&y)+y^y|k|S,b=h|~(O|y),I=y&O;if(b>>>31^D)s[x/32|0]^=1<<x;if(I>>>31^S)i[x/32|0]^=1<<x;b=b<<1|D,I=I<<1|S,y=I|~(L|b),h=b&L}for(let x=E;x<_;x++)it[t.charCodeAt(x)]=0}let u=0,m=-1,f=l*32,p=Math.min(32,n-f)+f;for(let h=f;h<p;h++)it[t.charCodeAt(h)]|=1<<h;let g=n;for(let h=0;h<r;h++){let y=it[e.charCodeAt(h)],E=s[h/32|0]>>>h&1,_=i[h/32|0]>>>h&1,x=y|u,k=((y|_)&m)+m^m|y|_,D=u|~(k|m),S=m&k;if(g+=D>>>n-1&1,g-=S>>>n-1&1,D>>>31^E)s[h/32|0]^=1<<h;if(S>>>31^_)i[h/32|0]^=1<<h;D=D<<1|E,S=S<<1|_,m=S|~(x|D),u=D&x}for(let h=f;h<p;h++)it[t.charCodeAt(h)]=0;return g},Ji=(t,e)=>{if(t.length<e.length){let r=e;e=t,t=r}if(e.length===0)return t.length;if(t.length<=32)return Wi(t,e);return Ki(t,e)},Qr=(t,e)=>{let r=1/0,n=0;for(let i=0;i<e.length;i++){let s=Ji(t,e[i]);if(s<r)r=s,n=i}return e[n]};function Qt(t,e,r,n){let i=Qr(e,r);if(console.error(d.red(`Unknown ${t}: ${e}`)),i)console.error(d.yellow(`Did you mean "${i}"?`));console.error(`
|
|
83
|
+
Run "${n} --help" for usage.`),process.exit(1)}function te(t,e){if(Array.isArray(e))return[...e];if(!tn(t)||!tn(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([r,n])=>[r,te(Object.hasOwn(t,r)?t[r]:void 0,n)])])}function tn(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var We="__exit__";class wt{command;env;prefix;options;selections;constructor(t,e,r,n={}){this.command=t;this.env=e;this.prefix=r;this.options=n;this.selections=n.selections??new Map}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(t,e){if(e&&process.stdout.isTTY!==!0)throw new v("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(e)await this.routeInteractive();else await this.routeDirect(t)}async routeDirect(t){let[e,...r]=t;if(e&&this.command.hasSubcommands()){let n=this.command.getSubcommand(e);if(n){await this.handleSubcommandRoute(n,r);return}if(!e.startsWith("-")){this.handleUnknownSubcommand(e);return}}await this.executeCommand(t)}handleUnknownSubcommand(t){let e=this.command.getSubcommands().map((r)=>r.name);Qt("subcommand",t,e,this.commandPath)}async handleSubcommandRoute(t,e){await new wt(t,this.env,this.commandPath).route(e,!1)}async executeCommand(t){if(this.isHelpRequest(t)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:r,rawPositionals:n}=Ge(t,this.command.args),i=He(n,this.command.positionals),s=Zr(i,this.command.positionals);if(s)w.error(s),console.error(`
|
|
84
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&n.length===0&&process.stdout.isTTY===!0,a=this.buildContext(i,r,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:t}=Ge([],this.command.args),e=He([],this.command.positionals),r=this.buildContext(e,t,!0);await this.command.execute?.(r)}async runSubcommandMenu(){while(!0){let t=await this.promptSubcommandSelectionOrBack();if(t===null)return;if(t===We){this.options.onExit?.();return}let e=this.command.getSubcommand(t);if(e)this.selections.set(this.commandPath,t),await this.executeSubcommand(e)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(t){if(t instanceof X){if(this.options.isRoot)this.options.onExit?.();return null}throw t}}async executeSubcommand(t){try{await new wt(t,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(e){if(e instanceof X)return;if(e instanceof v){if(w.warn(d.yellow(e.message)),e.hint)w.info(d.dim(e.hint));$t(e);return}throw e}}promptSubcommandSelection(){let{isRoot:t}=this.options,e=t?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:We}:{hint:"Return to previous menu",label:"Back",value:We};return pt({message:t?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,initialValue:this.selections.get(this.commandPath),options:[...this.command.getSubcommands().map((r)=>({hint:r.description,label:r.name,value:r.name})),e]})}buildContext(t,e,r){return{...this.env,args:e,interactive:r,positionals:t}}isHelpRequest(t){let e=t.indexOf("--"),r=e<0?t:t.slice(0,e);return r.includes("--help")||r.includes("-h")}printHelp(t){let e=t===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(t,e))}}var qi={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Ke{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(t,e){this.configManager=t,this.metadata={...qi,...e},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Be({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(t){for(let e of t)e.init?.(),this.commands.set(e.name,e)}async run(t=process.argv.slice(2)){try{let{command:e,flags:r,restArgs:n}=Yr(t,this.globalArgs);if(r.version&&!e)return console.log(this.help.version());if(r.interactive&&!e)return await this.runInteractive();if(!e)return console.log(this.help.global());if(e==="help")return this.printHelpFor(n[0]);await this.runDirect(e,n,!!r.help)}catch(e){this.handleError(e)}}printHelpFor(t){if(!t)return console.log(this.help.global());let e=this.commands.get(t);if(!e)return this.handleUnknownCommand(t);console.log(this.help.command(e))}async runInteractive(){this.showIntro();let t=this.createVirtualRootCommand(),e={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},r=new wt(t,e,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await r.route([],!0)}catch(n){this.handleError(n)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(t)=>this.commands.get(t),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){Jt(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(t,e,r){let n=this.commands.get(t);if(!n)return this.handleUnknownCommand(t);let i=e.length>0&&!e[0]?.startsWith("-");if(r&&!i)return console.log(this.help.command(n));try{let s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new wt(n,s,this.bin).route(e,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let t=this.metadata.version?` v${this.metadata.version}`:"";Kt(`${d.bgCyan(d.black(` ${this.metadata.name}${t} `))}`)}handleUnknownCommand(t){let e=Array.from(this.commands.keys());Qt("command",t,e,this.bin)}handleError(t){if(this.metadata.onError?.(t))return;if(t instanceof X)process.exit(0);if(t instanceof v){if(w.warn(d.yellow(t.message)),t.hint)w.info(d.dim(t.hint));$t(t),process.exit(t.exitCode)}if(t instanceof Error)w.error(d.red(t.message)),$t(t),process.exit(1);console.error(d.red("Error:"),t),process.exit(1)}}class Tt{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(t){for(let e of t)e.init?.(),this.subcommands.set(e.name,e)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(t){return this.subcommands.get(t)}getSubcommands(){return Array.from(this.subcommands.values())}}function Q(t){return t}function M(t){return t}import z from"fs";import rn from"path";var ee=(t)=>(t.map=(e)=>ee((r)=>e(t(r))),t.or=(e)=>ee((r)=>{try{return t(r)}catch(n){return e(r)}}),t),bt=()=>"bad banditype"();var zi=(t)=>ee((e)=>typeof e===typeof t?e:bt());var re=()=>zi(0);var en=(t)=>ee((e)=>e instanceof t?e:bt());function qe(t,e){JSON.parse(t);let r=JSON.parse(JSON.stringify(e)),n=Yi(t),i=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",s=t.includes(`\r
|
|
85
|
+
`)?`\r
|
|
86
|
+
`:`
|
|
87
|
+
`,o=/\s/.test(t[n.start+1]??"")||n.entries.some((u)=>/:\s+$/.test(t.slice(u.start,u.node.start)))?" ":"";function a(u,m){let f=t.slice(u.start,u.end);if(JSON.stringify(u.value)===JSON.stringify(m))return f;let p=Array.isArray(m);if(m===null||typeof m!=="object"||u.value===null||typeof u.value!=="object"||Array.isArray(u.value)!==p)return l(m,u.start,f.includes(`
|
|
88
|
+
`));let g=p?m.map((b,I)=>String(I)):[...new Set([...u.entries.map((b)=>b.key).filter((b)=>Object.hasOwn(m,b)),...Object.keys(m)])];if(g.length===0)return p?"[]":"{}";let h=u.entries[0],y=u.entries.at(-1);if(!h||!y)return l(m,u.start,f.includes(`
|
|
89
|
+
`));let E=(b)=>p?m[Number(b)]:m[b];if(g.length===u.entries.length&&g.every((b,I)=>b===u.entries[I]?.key)){let b=u.start,I="";for(let V of u.entries)I+=t.slice(b,V.node.start)+a(V.node,E(V.key)),b=V.node.end;return I+t.slice(b,u.end)}let _=t.slice(u.start+1,h.start),x=t.slice(y.node.end,u.end-1),k=u.entries[1],D=k?t.slice(h.node.end,k.start):`,${_.includes(`
|
|
90
|
+
`)?_:o}`,S=p?"":t.slice(h.start,h.node.start).match(/:\s*$/)?.[0]??": ",L=new Map(u.entries.map((b)=>[b.key,b])),O=g.map((b)=>{let I=L.get(b);if(I)return t.slice(I.start,I.node.start)+a(I.node,E(b));return(p?"":JSON.stringify(b)+S)+l(E(b),h.start,_.includes(`
|
|
91
|
+
`))});return`${p?"[":"{"}${_}${O.join(D)}${x}${p?"]":"}"}`}function l(u,m,f){if(!f)return Je(u,o);let p=t.lastIndexOf(`
|
|
92
|
+
`,m-1)+1,g=t.slice(p,m).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(u,null,i).replaceAll(`
|
|
93
|
+
`,s+g)}return t.slice(0,n.start)+a(n,r)+t.slice(n.end)}function Je(t,e){if(Array.isArray(t))return`[${t.map((i)=>Je(i,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let r=Object.entries(t);if(r.length===0)return"{}";let n=r.map(([i,s])=>`${JSON.stringify(i)}:${e}${Je(s,e)}`);return`{${e}${n.join(`,${e}`)}${e}}`}function Yi(t){let e=t.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),r=e.next().value;function n(){if(!r)throw Error("Unexpected end of JSON");let s=r;return r=e.next().value,s}function i(){let s=n(),o=[],a=s[0]==="{";if(!a&&s[0]!=="[")return{end:s.index+s[0].length,entries:o,start:s.index,value:JSON.parse(s[0])};let l=a?"}":"]";while(r&&r[0]!==l){let m=r.index,f=a?JSON.parse(n()[0]):String(o.length);if(a)n();if(o.push({key:f,node:i(),start:m}),r?.[0]===",")n()}let u=n().index+1;return{end:u,entries:o,start:s.index,value:JSON.parse(t.slice(s.index,u))}}return i()}var Xi=2,Zi=en(Object);class ze{config;configPath;defaultConfig;loadError;constructor(t,e){this.configPath=rn.resolve(t),this.defaultConfig=e,this.config=this.loadConfig()}get path(){return this.configPath}get(t){return this.config[t]}set(t,e){this.config={...this.config,[t]:e},this.save()}delete(t){delete this.config[t],this.save()}exists(){return z.existsSync(this.configPath)}getAll(){return structuredClone(this.config)}save(t){if(this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(t)this.config={...t};this.ensureDirectoryExists();let e=this.exists()?z.realpathSync(this.configPath):this.configPath,r=`${e}.${crypto.randomUUID()}.tmp`;try{let n=this.exists()?z.statSync(this.configPath).mode:void 0,i=this.exists()?qe(z.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,Xi)}
|
|
94
|
+
`;if(z.writeFileSync(r,i,{flag:"wx",mode:n}),n!==void 0)z.chmodSync(r,n);z.renameSync(r,e)}catch(n){throw Error(`Failed to save config to ${this.configPath}`,{cause:n})}finally{z.rmSync(r,{force:!0})}}ensureDirectoryExists(){let t=rn.dirname(this.configPath);if(!z.existsSync(t))try{z.mkdirSync(t,{recursive:!0})}catch(e){throw Error(`Failed to create config directory at ${t}`,{cause:e})}}loadConfig(){if(!z.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let t=z.readFileSync(this.configPath,"utf-8"),e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");let r=Zi(e);return te(structuredClone(this.defaultConfig),r)}catch(t){return this.loadError=t,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}}var nn="0.10.0";class T extends Tt{}var ne="hydra";var sn=".hydra/config.json",tt=".hydra/shared",Dt=".hydra/runners",Ot="default",on={profiles:{}},an=!1,ln=24,ie=7,un=["logs","shared"];import{spawn as as}from"child_process";import{once as ls}from"events";import{existsSync as Ct}from"fs";import{cp as us,link as cs,mkdir as ae,mkdtemp as ps,readdir as fn,readFile as Ze,readlink as ds,rename as ms,rm as ft,stat as hs,symlink as fs,unlink as gn,writeFile as gs}from"fs/promises";import{join as P,resolve as Qe}from"path";var ts=new Set(["github.com","www.github.com"]);var cn=/\.git$/;function mt(t){let e;try{e=new URL(t)}catch{throw Error(`Invalid GitHub URL: ${t}`)}if(e.protocol!=="https:"&&e.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${t}`);if(!ts.has(e.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${t}`);let r=e.pathname.split("/").filter(Boolean);if(r.length===1){let n=r[0]?.replace(cn,"");if(!n)throw Error(`Invalid GitHub URL: ${t}`);return{kind:"org",org:n}}if(r.length===2){let n=r[0],i=r[1]?.replace(cn,"");if(!n||!i)throw Error(`Invalid GitHub URL: ${t}`);return{kind:"repo",owner:n,repo:i}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${t}`)}function se(t){return t.kind==="repo"?`${t.owner}/${t.repo}`:t.org}import{existsSync as es}from"fs";import{readdir as rs,stat as ns}from"fs/promises";import{join as is}from"path";var kt="_diag",pn={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},dn=1024,mn=["B","KB","MB","GB"],ss=1;function hn(t){if(pn.worker.test(t))return"worker";if(pn.runner.test(t))return"runner";return null}function oe(t){return[...t].sort((e,r)=>r.mtime.getTime()-e.mtime.getTime())}async function Lt(t){if(!es(t))return[];let e=await rs(t,{withFileTypes:!0}),r=[];for(let n of e){if(!n.isFile())continue;let i=hn(n.name);if(!i)continue;let s=is(t,n.name),o=await ns(s);r.push({mtime:o.mtime,name:n.name,path:s,size:o.size,type:i})}return oe(r)}function Ye(t,e){let r=t.find((i)=>i.type===e);if(r)return{fallback:!1,file:r};let n=t[0];return n?{fallback:!0,file:n}:null}function Xe(t,e){if(e<=0)return"";let r=t.endsWith(`
|
|
95
|
+
`)?t.slice(0,-1):t;if(r==="")return"";return r.split(`
|
|
96
|
+
`).slice(-e).join(`
|
|
97
|
+
`)}function ht(t){let e=t,r=0;while(e>=dn&&r<mn.length-1)e/=dn,r++;return`${r===0?String(e):e.toFixed(ss)} ${mn[r]??"B"}`}var os=/(?:^|\/)github\/([^/]+)\/externals$/;function Ft(t){return t.match(os)?.[1]??null}var yn="actions/runner",ys={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},tr=["bin"],er=["externals"],$s=1,vs=5000,ws=50,bs=5000,Cs=50;class le{profile;sharedPath=null;constructor(t){this.profile=t}async download(){let t=ys[this.profile.os],e=await this.getLatestVersion(),r=P(tt,"github",e);if(await this.isCompleteDownload(r))return this.sharedPath=r,{path:r,version:e};let n=P(tt,"github");await ae(n,{recursive:!0});let i=await ps(P(tt,`.github-${e}-`)),s=`actions-runner-${t}-${e}.tar.gz`,o=P(i,s),a=`https://github.com/${yn}/releases/download/v${e}/${s}`;try{if(await Bun.$`curl --fail --silent --show-error --location -o ${o} ${a}`,await Bun.$`tar xzf ${o} -C ${i}`,await gn(o),!await this.isCompleteDownload(i))throw new v(`Runner v${e} archive is incomplete`);await this.publishDownload(i,r,e)}finally{await ft(i,{force:!0,recursive:!0})}return this.sharedPath=r,{path:r,version:e}}async create(t){let e=await this.ensureDownloaded(),r=[];for(let n of t){let i=P(this.profile.directory,n);if(Ct(i))throw new v(`Runner directory already exists: ${i}`,"Remove or recover this runner before creating it again");try{await this.setupRunnerDir(e,i),await this.registerRunner(i,n)}catch(s){if(!Ct(P(i,".runner")))await ft(i,{force:!0,recursive:!0});throw s}r.push({directory:i,id:n,name:n,status:"registered"})}return r}async remove(t){for(let e of t){let r=P(this.profile.directory,e);if(!Ct(P(r,".runner")))continue;let n=await this.fetchRemovalToken(r),i=await Bun.$`bash ./config.sh remove --token ${n}`.cwd(r).quiet().nothrow();if(i.exitCode!==0)throw new v(`Failed to deregister runner ${e}`,i.stderr.toString().trim()||"Runner files have been preserved; retry removal")}}async start(t){for(let e of t){let r=P(this.profile.directory,e),n=await this.readPidFile(r);if(n&&this.isProcessRunning(n))continue;let i=as("bash",["./run.sh"],{cwd:Qe(r),detached:!0,stdio:"ignore"});if(await ls(i,"spawn"),i.pid===void 0)throw new v(`Failed to start runner ${e}`);i.unref(),await this.writePidFile(r,i.pid)}}async stop(t){for(let e of t){let r=P(this.profile.directory,e),n=await this.readPidFile(r);if(n&&this.isProcessRunning(n)){try{process.kill(-n,"SIGTERM")}catch(s){if(s.code!=="ESRCH")throw s;try{process.kill(n,"SIGTERM")}catch(o){if(o.code!=="ESRCH")throw o}}let i=Date.now()+vs;while(this.isProcessRunning(n)){if(Date.now()>=i)throw new v(`Runner ${e} did not stop`,"Wait for its current job to finish and retry");await Bun.sleep(ws)}}await this.removePidFile(r)}}async list(){let t=this.profile.directory;if(!Ct(t))return[];let e=await fn(t,{withFileTypes:!0}),r=[];for(let n of e){if(!n.isDirectory())continue;let i=P(t,n.name);r.push(await this.getRunnerStatus(i,n.name))}return r}async currentVersion(t){let e=P(this.profile.directory,t);return this.detectVersion(e)}async logFiles(t){return Lt(P(this.profile.directory,t,kt))}async update(t){let e=await this.ensureDownloaded();for(let r of t){let n=P(this.profile.directory,r);await this.removeRunnerBinaries(n),await this.setupRunnerDir(e,n)}}async getRunnerStatus(t,e){let r=await this.readRunnerName(t),n=await this.readPidFile(t),i=n!==null&&this.isProcessRunning(n),s="unknown";if(i)s="running";else if(Ct(P(t,".runner")))s="registered";return{directory:t,id:e,name:r,pid:i?n:void 0,status:s}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:t}=await this.download();return t}async isCompleteDownload(t){try{return(await Promise.all(["bin","externals","config.sh","run.sh"].map((r)=>hs(P(t,r))))).every((r,n)=>n<tr.length+er.length?r.isDirectory():r.isFile())}catch(e){if(e.code==="ENOENT")return!1;throw e}}async publishDownload(t,e,r){let n=P(tt,`.github-${r}.lock`),i=Date.now()+bs;while(!0)try{await ae(n);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=i)throw new v(`Runner download is locked: ${n}`,"Retry after other Hydra downloads finish; remove a stale lock only when no download is running");await Bun.sleep(Cs)}try{if(await this.isCompleteDownload(e))return;await ft(e,{force:!0,recursive:!0}),await ms(t,e)}finally{await ft(n,{force:!0,recursive:!0})}}async setupRunnerDir(t,e){await ae(e,{recursive:!0});for(let r of tr)await this.hardLinkDir(P(t,r),P(e,r));for(let r of er){let n=Qe(t,r),i=P(e,r);if(!Ct(i))await fs(n,i)}for(let r of["*.sh","*.sh.template"]){let n=await Array.fromAsync(new Bun.Glob(r).scan(t));for(let i of n)await us(P(t,i),P(e,i))}}async registerRunner(t,e){let r=await this.fetchRegistrationToken(),n=["--url",this.profile.url,"--token",r,"--name",e,"--unattended","--disableupdate"];if(this.profile.labels)n.push("--labels",this.profile.labels);if(this.profile.runnerGroup)n.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${n}`.cwd(t).quiet()}async fetchRegistrationToken(){return this.fetchRunnerToken(mt(this.profile.url),"registration-token")}async fetchRemovalToken(t){let e=await Ze(P(t,".runner"),"utf-8"),n=JSON.parse(this.stripBom(e)).gitHubUrl;if(!n)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(mt(n),"remove-token")}async fetchRunnerToken(t,e){let r=t.kind==="repo"?`repos/${t.owner}/${t.repo}/actions/runners/${e}`:`orgs/${t.org}/actions/runners/${e}`,n=t.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",i=await Bun.$`gh api ${r} --method POST --jq .token`.quiet().nothrow();if(i.exitCode!==0){let o=i.stderr.toString().trim();throw Error(`gh api ${r} failed for ${se(t)} (${n})${o?`: ${o}`:""}`)}let s=i.stdout.toString().trim();if(!s)throw Error(`Failed to fetch ${e} for ${se(t)}`);return s}async getLatestVersion(){return(await Bun.$`gh api repos/${yn}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(t){return Qe(t,".pid")}async writePidFile(t,e){await gs(this.pidFilePath(t),String(e))}async readPidFile(t){try{let e=await Ze(this.pidFilePath(t),"utf-8"),r=Number(e.trim());return Number.isSafeInteger(r)&&r>$s?r:null}catch{return null}}async removePidFile(t){try{await gn(this.pidFilePath(t))}catch{}}async readRunnerName(t){try{let e=await Ze(P(t,".runner"),"utf-8");return JSON.parse(this.stripBom(e)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(t,e){await ae(e,{recursive:!0});let r=await fn(t,{withFileTypes:!0});for(let n of r){let i=P(t,n.name),s=P(e,n.name);if(n.isDirectory())await this.hardLinkDir(i,s);else await cs(i,s)}}async detectVersion(t){try{let e=await ds(P(t,"externals"));return Ft(e)}catch{return null}}async removeRunnerBinaries(t){for(let e of tr)await ft(P(t,e),{force:!0,recursive:!0});for(let e of er)await ft(P(t,e),{force:!0});for(let e of["*.sh","*.sh.template"]){let r=await Array.fromAsync(new Bun.Glob(e).scan(t));for(let n of r)await ft(P(t,n),{force:!0})}}stripBom(t){return t.replace(/^\uFEFF/,"")}isProcessRunning(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}}import{existsSync as rr}from"fs";import{readdir as nr,readFile as xs,readlink as Ss,rm as ir,stat as Rs}from"fs/promises";import{join as lt}from"path";var vn="_work",Es="externals",Is=".pid",Ps="github",_s=["runner","worker"],As=24,wn=3600000,$n=10,Ts=1,Ds=re().map((t)=>Number.isSafeInteger(t)&&t>Ts?t:bt());function ue(t){return{auto:t?.auto??an,intervalHours:t?.intervalHours??ln,lastRun:t?.lastRun,olderThanDays:t?.olderThanDays??ie,targets:t?.targets??un}}function bn(t,e){return t-e*As*wn}function sr(t,e){if(!t.lastRun)return!0;let r=Date.parse(t.lastRun);if(Number.isNaN(r))return!0;return e-r>=t.intervalHours*wn}function Cn(t,e){let r=oe(t),n=new Set;for(let i of _s){let s=r.find((o)=>o.type===i);if(s)n.add(s.path)}return r.filter((i)=>!n.has(i.path)&&i.mtime.getTime()<e)}function xn(t){return[...t].sort(Ns)[0]??null}function Sn(t,e){let r=xn(t),n=new Set(e);return t.filter((i)=>i!==r&&!n.has(i))}function ce(t){return Object.values(t).reduce((e,r)=>e+r.freedBytes,0)}async function Rn(t){let e;try{e=await xs(lt(t,Is),"utf-8")}catch(n){if(n.code==="ENOENT")return!1;throw n}let r;try{r=Ds(Number(e.trim()))}catch{return!1}try{return process.kill(r,0),!0}catch(n){let i=n.code;if(i==="EPERM")return!0;if(i==="ESRCH")return!1;throw n}}async function pe(t){if(!rr(t))return 0;let e=await nr(t,{withFileTypes:!0}),r=0;for(let n of e){if(n.isSymbolicLink())continue;let i=lt(t,n.name);if(n.isDirectory()){r+=await pe(i);continue}if(n.isFile()){let s=await Rs(i);r+=s.size}}return r}async function de(t){let e=bn(t.now,t.olderThanDays),r={};for(let n of t.targets)switch(n){case"logs":r.logs=await Os(t.entries,e,t.dryRun);break;case"work":r.work=await ks(t.entries,t.dryRun);break;case"shared":r.shared=await Ls(t.entries,t.dryRun,t.sharedDir);break}return r}async function Os(t,e,r){let n={freedBytes:0,removed:0,skipped:[]};for(let i of t){let s=await Lt(lt(i.directory,kt));for(let o of Cn(s,e)){if(!r)await ir(o.path,{force:!0});n.removed++,n.freedBytes+=o.size}}return n}async function ks(t,e){let r={freedBytes:0,removed:0,skipped:[]};for(let n of t){if(await Rn(n.directory)){r.skipped.push(n.id);continue}let i=lt(n.directory,vn);if(!rr(i))continue;let s=await nr(i);if(s.length===0)continue;if(r.freedBytes+=await pe(i),r.removed+=s.length,e)continue;for(let o of s)await ir(lt(i,o),{force:!0,recursive:!0})}return r}async function Ls(t,e,r){let n={freedBytes:0,removed:0,skipped:[]},i=r??lt(tt,Ps);if(!rr(i))return n;let o=(await nr(i,{withFileTypes:!0})).filter((l)=>l.isDirectory()).map((l)=>l.name),a=await Fs(t);for(let l of Sn(o,a)){let u=lt(i,l);if(n.freedBytes+=await pe(u),n.removed++,!e)await ir(u,{force:!0,recursive:!0})}return n}async function Fs(t){let e=[];for(let r of t)try{let n=await Ss(lt(r.directory,Es)),i=Ft(n);if(i)e.push(i)}catch{}return e}function Ns(t,e){let r=t.split(".").map((s)=>Number.parseInt(s,$n)),n=e.split(".").map((s)=>Number.parseInt(s,$n)),i=Math.max(r.length,n.length);for(let s=0;s<i;s++){let o=r[s]??0,a=n[s]??0,l=Number.isNaN(o)?0:o,u=Number.isNaN(a)?0:a;if(l!==u)return u-l}return 0}function U(t){switch(t.provider){case"github":return new le(t);default:throw Error(`Runner provider "${t.provider}" is not yet implemented`)}}var In=0,Ms={logs:"file(s)",shared:"version(s)",work:"item(s)"},En=Q({days:{alias:"d",default:In,description:"Override log retention",displayDefault:`config or ${ie} days`,type:"number"},dryRun:{alias:"n",default:!1,description:"Preview cleanup without deleting",type:"boolean"},logs:{alias:"l",default:!1,description:"Remove old diagnostic logs",type:"boolean"},shared:{alias:"s",default:!1,description:"Remove unused runner versions",type:"boolean"},work:{alias:"w",default:!1,description:"Clear stopped runners' workspaces",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip workspace confirmation",type:"boolean"}});class me extends T{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=En;async execute(t){N(t.args,En,"Run 'hydra cleanup --help' for supported options");let e=t.config.get("profiles");if(Object.keys(e).length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let r=ue(t.config.get("cleanup")),n=this.explicitTargets(t),i=n.length>0?n:r.targets,s=t.args.days>In?t.args.days:r.olderThanDays;if(i.includes("work")&&!t.args.dryRun&&!t.args.yes){if(!await ct({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))i=i.filter((l)=>l!=="work")}let o=await de({dryRun:t.args.dryRun,entries:t.config.get("runners")??[],now:Date.now(),olderThanDays:s,targets:i});if(this.printReport(o,t.args.dryRun),t.args.dryRun)return;t.config.set("cleanup",{...t.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(t){let e=[];if(t.args.logs)e.push("logs");if(t.args.work)e.push("work");if(t.args.shared)e.push("shared");return e}printReport(t,e){let r=[];for(let[s,o]of Object.entries(t)){if(!o)continue;let a=Ms[s],l=ht(o.freedBytes),u=e?`would remove ${o.removed} ${a}, ${l}`:`removed ${o.removed} ${a}, freed ${l}`;if(r.push(`${d.bold(s)}: ${o.removed>0?u:d.dim("nothing to do")}`),o.skipped.length>0)r.push(d.dim(` skipped running runner(s): ${o.skipped.join(", ")}`))}if(r.length===0){w.info(d.dim("Nothing to clean."));return}let n=ce(t),i=e?"Would free":"Freed";r.push(d.dim(`${i} ${ht(n)} total`)),w.info(r.join(`
|
|
98
|
+
`))}}async function he(t){try{let e=ue(t.config.get("cleanup"));if(!e.auto)return;if(!sr(e,Date.now()))return;let r=await de({dryRun:!1,entries:t.config.get("runners")??[],now:Date.now(),olderThanDays:e.olderThanDays,targets:e.targets});t.config.set("cleanup",{...t.config.get("cleanup"),lastRun:new Date().toISOString()});let n=ce(r);if(n>0)w.info(d.dim(`Auto cleanup freed ${ht(n)}`))}catch(e){let r=e instanceof Error?e.message:String(e);w.warn(d.yellow(`Auto cleanup failed: ${r}`))}}import{existsSync as _n}from"fs";import{join as An}from"path";var Pn="Runner count must be a positive safe integer",Us=re().map((t)=>Number.isSafeInteger(t)&&t>0?t:bt());function gt(t){try{return Us(typeof t==="string"?Number(t):t)}catch{throw new v(Pn)}}function fe(t){try{gt(t);return}catch{return Pn}}function xt(t,e){if(t.length===0)return e;for(let r of t)if(!e.includes(r))throw new v(`Runner "${r}" not found`);return t}function H(t,e){let r=t.get("profiles");if(Object.keys(r).length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let n=e??t.get("defaultProfile")??Ot,i=Object.hasOwn(r,n)?r[n]:void 0;if(!i)throw new v(`Profile "${n}" not found`);return{name:n,profile:i}}async function Y(t){let e=t.get("profiles"),r=Object.keys(e);if(r.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");if(r.length===1)return r[0];return pt({message:"Select profile",options:r.map((n)=>({label:n,value:n,hint:e[n]?.url}))})}var js=M({profile:{description:"Profile to use"},count:{description:"Runner count override"}});class ge extends T{name="create";description="Download and register runners";positionals=js;async execute(t){N(t.args,this.args,"Run 'hydra create --help' for supported options");let{name:e,profile:r}=t.interactive?H(t.config,await Y(t.config)):H(t.config,t.positionals.profile),n=t.interactive?await this.promptCount(r.numberOfMachines):gt(t.positionals.count??r.numberOfMachines),i=t.config.get("runners")??[],s=i.filter((h)=>h.profile===e),o=n-s.length;if(o<=0){w.warn(`Already have ${s.length} runner(s) for profile "${e}". Nothing to create.`);return}let a=U(r),l=K();l.start("Downloading runner binary...");let{version:u}=await a.download();l.stop(`Runner v${u} ready`);let m=new Set(i.map((h)=>h.id)),f=1;for(let h=0;h<o;){let y=`${r.name}-${f++}`;if(m.has(y))continue;h++;let E={createdAt:new Date().toISOString(),directory:An(r.directory,y),id:y,name:y,profile:e,provider:r.provider,url:r.url},_=_n(E.directory);l.start(`Registering ${y}...`);try{await a.create([y])}finally{if(!_&&_n(An(E.directory,".runner")))i.push(E),t.config.set("runners",i)}l.stop(`${d.green("+")} ${y}`)}let g=e===t.config.get("defaultProfile")?"":` ${e}`;w.info(`${d.green("Created")} ${o} runner(s) for "${e}". Run ${d.green(`hydra start${g}`)} to start them.`)}async promptCount(t){let e=await nt({initialValue:String(t),message:"Number of runners to create",validate:fe});return gt(e)}}import{existsSync as Tn}from"fs";import{mkdir as Dn}from"fs/promises";var On=1,Vs=M({url:{description:"GitHub repository or organization URL"}}),Gs=Q({force:{alias:"f",default:!1,description:"Overwrite an existing profile",type:"boolean"},labels:{alias:"l",description:"Set comma-separated runner labels",type:"string"},name:{alias:"n",description:"Set the runner name prefix",type:"string"},profile:{alias:"p",description:"Set the profile name",type:"string"},runners:{alias:"c",description:"Set the runner count",type:"number"}});class ye extends T{name="init";description="Set up a runner profile";positionals=Vs;args=Gs;prompts=!0;async execute(t){N(t.args,this.args,"Run 'hydra init --help' for supported options");let e=t.interactive?await this.promptProfileName(t):t.args.profile??Ot,r=!t.config.exists();if(!r&&Object.hasOwn(t.config.get("profiles"),e)&&!t.args.force){if(!t.interactive)throw new v(`Profile "${e}" already exists. Use --force to overwrite.`);if(!await ct({initialValue:!1,message:`Profile "${e}" already exists. Overwrite?`}))return}let i=t.interactive?await this.runInitForm():this.buildProfileFromArgs(t);await this.ensureDirectories();let s={...r?{}:t.config.get("profiles"),[e]:i};if(t.config.set("profiles",s),!t.config.get("defaultProfile"))t.config.set("defaultProfile",e);yt([`${d.dim("Profile:")} ${e}`,`${d.dim("URL:")} ${i.url}`,`${d.dim("Runners:")} ${i.numberOfMachines}`,`${d.dim("Name:")} ${i.name}`,i.labels?`${d.dim("Labels:")} ${i.labels}`:"","",`Run ${d.green(`${ne} create${e!==t.config.get("defaultProfile")?` ${e}`:""}`)} to provision runners.`].filter(Boolean).join(`
|
|
99
|
+
`),d.green(r?"Hydra initialized":`Profile "${e}" added`))}async promptProfileName(t){return nt({initialValue:t.args.profile??Ot,message:"Profile name"})}async ensureDirectories(){if(!Tn(tt))await Dn(tt,{recursive:!0});if(!Tn(Dt))await Dn(Dt,{recursive:!0})}async runInitForm(){let t=await Wt({url:()=>nt({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(e)=>{if(!e)return"URL is required";try{mt(e)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>nt({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>nt({initialValue:String(On),message:"Number of runners",placeholder:"1",validate:fe}),labels:()=>nt({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new X}});return{directory:Dt,labels:t.labels||void 0,name:t.name,numberOfMachines:gt(t.runners),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:t.url}}buildProfileFromArgs(t){if(!t.positionals.url)throw new v("URL is required","Usage: hydra init <url>");return this.validateUrl(t.positionals.url),{directory:Dt,labels:t.args.labels,name:t.args.name??"runner",numberOfMachines:gt(t.args.runners??On),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:t.positionals.url}}validateUrl(t){try{mt(t)}catch(e){throw new v(e instanceof Error?e.message:`Invalid GitHub URL: ${t}`,"Expected https://github.com/<owner>/<repo> or https://github.com/<org>")}}detectOs(){let t=process.platform;if(t==="darwin")return"osx";if(t==="win32")return"windows";return"linux"}}import{existsSync as Hs}from"fs";import{readFile as Bs}from"fs/promises";var Ws=100,Ks={runner:"runner daemon log",worker:"job log"},Js=Q({lines:{alias:"n",default:Ws,description:"Number of lines to show",type:"number"},list:{alias:"l",default:!1,description:"List log files instead of showing one",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner log instead of a job log",type:"boolean"}}),qs=M({id:{description:"Runner ID"}});class $e extends T{name="logs";description="Show recent runner logs";args=Js;positionals=qs;async execute(t){let e=t.config.get("runners")??[];if(e.length===0)throw new v("No runners found","Run hydra create to provision runners");let r=await this.resolveEntry(t,e),n=t.config.get("profiles"),i=Object.hasOwn(n,r.profile)?n[r.profile]:void 0;if(!i)throw new v(`Profile "${r.profile}" not found for runner "${r.id}"`,"Run hydra init to set it up");if(!Hs(r.directory))throw new v(`Runner directory not found: ${r.directory}`,"Run hydra create to provision this runner");let o=await U(i).logFiles(r.id);if(o.length===0)this.noLogs(r.id);if(t.args.list){this.printList(r,o);return}let a=this.selectFile(t,r,o);if(t.args.open){await this.openFile(a);return}await this.printTail(r,a,t.args.lines)}async resolveEntry(t,e){let r=t.positionals.id;if(r){let i=e.find((s)=>s.id===r);if(!i)throw new v(`Runner "${r}" not found`,`Known runners: ${e.map((s)=>s.id).join(", ")}`);return i}if(t.interactive)return pt({message:"Select runner",options:e.map((i)=>({hint:i.profile,label:i.name,value:i}))});let n=e[0];if(e.length===1&&n)return n;throw new v("Multiple runners found",`Pass a runner id: hydra logs <id> (${e.map((i)=>i.id).join(", ")})`)}selectFile(t,e,r){if(t.args.runner){let i=r.find((s)=>s.type==="runner");if(!i)throw new v(`No runner daemon logs found for "${e.id}"`,"Start the runner first: hydra start");return i}let n=Ye(r,"worker");if(!n)this.noLogs(e.id);if(n.fallback)w.warn(d.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return n.file}noLogs(t){throw new v(`No logs found for runner "${t}"`,"Logs appear once the runner has started; run hydra start")}printList(t,e){let r=[`${d.bold(t.name)} ${d.dim(t.directory)}`];for(let n of e){let i=n.type==="worker"?d.green("worker"):d.blue("runner");r.push(` ${i} ${n.name} ${d.dim(`${n.mtime.toISOString()} \xB7 ${ht(n.size)}`)}`)}w.info(r.join(`
|
|
100
|
+
`))}async printTail(t,e,r){let n=await Bs(e.path,"utf-8"),i=[`${d.bold(t.name)} ${d.dim(Ks[e.type])}`,d.dim(e.path),d.dim(`Last modified: ${e.mtime.toISOString()}`)];w.info(i.join(`
|
|
101
|
+
`)),console.log(Xe(n,r))}async openFile(t){let e=(process.env.EDITOR??"").split(" ").filter(Boolean),r=e[0];if(r){await Bun.spawn([r,...e.slice(1),t.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${t.path}`.quiet();return}throw new v("No editor configured","Set $EDITOR to open log files")}}var zs=M({name:{description:"Profile name to set as default"}});class or extends T{name="default";description="Set the default profile";positionals=zs;async execute(t){N(t.args,this.args,"Run 'hydra profile default --help' for supported options");let e=t.interactive?await Y(t.config):t.positionals.name;if(!e)throw new v("Profile name is required","Usage: hydra profile default <name>");let{name:r}=H(t.config,e);if(t.config.get("defaultProfile")===r){w.info(`"${r}" is already the default profile.`);return}t.config.set("defaultProfile",r),w.info(`${d.green("Default profile set to")} "${r}".`)}}class ar extends T{name="list";description="List profiles";async execute(t){let e=t.config.get("profiles"),r=Object.keys(e);if(r.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let n=t.config.get("runners")??[],i=t.config.get("defaultProfile");for(let s of r){let o=e[s],l=await U(o).list(),u=n.filter((y)=>y.profile===s),m=new Set(l.filter((y)=>y.status==="running").map((y)=>y.id)),f=u.filter((y)=>m.has(y.id)).length,p=s===i,g=[`${d.dim("URL:")} ${o.url}`,`${d.dim("Provider:")} ${o.provider}`,`${d.dim("OS:")} ${o.os}`,`${d.dim("Name:")} ${o.name}`,`${d.dim("Runners:")} ${u.length}/${o.numberOfMachines} created, ${d.green(`${f} running`)}`];if(o.labels)g.push(`${d.dim("Labels:")} ${o.labels}`);let h=p?`${s} ${d.dim("(default)")}`:s;yt(g.join(`
|
|
102
|
+
`),h)}w.info(d.dim(`${r.length} profile(s)`))}}import{rm as Ys}from"fs/promises";import{join as Xs}from"path";var Zs=M({name:{description:"Profile name to remove"}}),Qs=Q({yes:{alias:"y",default:!1,description:"Skip runner removal confirmation",type:"boolean"}});class lr extends T{name="remove";description="Delete a profile and its runners";positionals=Zs;args=Qs;async execute(t){N(t.args,this.args,"Run 'hydra profile remove --help' for supported options");let e=t.interactive?await Y(t.config):t.positionals.name;if(!e)throw new v("Profile name is required","Usage: hydra profile remove <name>");let{profile:r}=H(t.config,e),n=t.config.get("runners")??[],i=n.filter((l)=>l.profile===e);if(i.length>0){if(!t.args.yes){if(!process.stdout.isTTY)throw new v("Runner removal requires confirmation","Pass --yes to remove the profile and its runners without a prompt");if(!await ct({initialValue:!0,message:`This will stop and remove ${i.length} runner(s). Continue?`}))return}await this.removeRunners(t,r,i.map((u)=>u.id));let l=n.filter((u)=>u.profile!==e);t.config.set("runners",l)}let{[e]:s,...o}=t.config.get("profiles");if(t.config.set("profiles",o),t.config.get("defaultProfile")===e){let l=Object.keys(o);t.config.set("defaultProfile",l[0])}w.info(`${d.green("Removed")} profile "${e}".`)}async removeRunners(t,e,r){let n=U(e),i=K();for(let s of r)i.start(`Stopping and removing ${s}...`),await n.stop([s]),await n.remove([s]),await Ys(Xs(e.directory,s),{force:!0,recursive:!0}),t.config.set("runners",(t.config.get("runners")??[]).filter((o)=>o.id!==s)),i.stop(`${d.red("-")} ${s}`)}}class ve extends T{name="profile";description="Manage profiles";init(){this.registerSubcommands([new ar,new lr,new or])}}import{rm as to}from"fs/promises";import{join as eo}from"path";var ro=M({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class we extends T{name="remove";description="Deregister and delete runners";positionals=ro;async execute(t){N(t.args,this.args,"Run 'hydra remove --help' for supported options");let{name:e,profile:r}=t.interactive?H(t.config,await Y(t.config)):H(t.config,t.positionals.profile),i=(t.config.get("runners")??[]).filter((l)=>l.profile===e);if(i.length===0)throw new v(`No runners found for profile "${e}"`,"Run hydra create to provision runners");let s=t.interactive?await this.promptRunnerSelection(i.map((l)=>l.id)):xt(t.positionals.ids??[],i.map((l)=>l.id)),o=U(r),a=K();for(let l of s)a.start(`Stopping and removing ${l}...`),await o.stop([l]),await o.remove([l]),await to(eo(r.directory,l),{force:!0,recursive:!0}),t.config.set("runners",(t.config.get("runners")??[]).filter((u)=>u.id!==l)),a.stop(`${d.red("-")} ${l}`);w.info(`${d.green("Removed")} ${s.length} runner(s).`)}async promptRunnerSelection(t){return dt({message:"Select runners to remove",options:t.map((e)=>({label:e,value:e})),required:!0})}}var no=M({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class be extends T{name="start";description="Start runners";positionals=no;async execute(t){N(t.args,this.args,"Run 'hydra start --help' for supported options");let{name:e,profile:r}=t.interactive?H(t.config,await Y(t.config)):H(t.config,t.positionals.profile),i=(t.config.get("runners")??[]).filter((p)=>p.profile===e);if(i.length===0)throw new v(`No runners found for profile "${e}"`,"Run hydra create to provision runners");let s=U(r),o=K();o.start("Fetching runner status...");let a=await s.list();o.stop("Runner status fetched");let l=new Set(a.filter((p)=>p.status==="running").map((p)=>p.id)),u=i.map((p)=>p.id).filter((p)=>!l.has(p)),m=t.interactive?await this.promptRunnerSelection(u):xt(t.positionals.ids??[],i.map((p)=>p.id)),f=0;for(let p of m){if(l.has(p)){o.start(""),o.stop(`${d.dim("\u25CF")} ${p} ${d.dim("already running")}`);continue}o.start(`Starting ${p}...`),await s.start([p]),o.stop(`${d.green("\u25B6")} ${p}`),f++}w.info(`${d.green("Started")} ${f} runner(s).`),await he(t)}async promptRunnerSelection(t){if(t.length===0)throw new v("All runners are already running");return dt({message:"Select runners to start",options:t.map((e)=>({label:e,value:e})),required:!0})}}var io={registered:d.yellow,running:d.green,stopped:d.red,unknown:d.dim};class Ce extends T{name="status";description="Show status across profiles";async execute(t){let e=t.config.get("profiles"),r=Object.keys(e);if(r.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let n=t.config.get("runners")??[],i=0,s=0,o=[];for(let a of r){let l=e[a],m=await U(l).list();if(o.length>0)o.push("");o.push(`${d.bold(a)} ${d.dim(l.url)}`);let f=new Set(n.filter((g)=>g.profile===a).map((g)=>g.id)),p=m.filter((g)=>f.has(g.id)).sort((g,h)=>g.name.localeCompare(h.name,void 0,{numeric:!0}));this.formatRunners(p,o),i+=p.length,s+=p.filter((g)=>g.status==="running").length}o.push(""),o.push(d.dim(`${i} runner(s) total, ${s} running`)),w.info(o.join(`
|
|
103
|
+
`))}formatRunners(t,e){if(t.length===0){e.push(d.dim(" No runners."));return}for(let r of t){let n=io[r.status]??d.dim,i=r.pid?d.dim(` (pid: ${r.pid})`):"";e.push(` ${n("\u25CF")} ${r.name} ${n(r.status)}${i}`)}}}var so=M({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class xe extends T{name="stop";description="Stop runners";positionals=so;async execute(t){N(t.args,this.args,"Run 'hydra stop --help' for supported options");let{name:e,profile:r}=t.interactive?H(t.config,await Y(t.config)):H(t.config,t.positionals.profile),i=(t.config.get("runners")??[]).filter((p)=>p.profile===e);if(i.length===0)throw new v(`No runners found for profile "${e}"`,"Run hydra create to provision runners");let s=U(r),o=K();o.start("Fetching runner status...");let a=await s.list();o.stop("Runner status fetched");let l=new Set(a.filter((p)=>p.status==="running").map((p)=>p.id)),u=i.map((p)=>p.id).filter((p)=>l.has(p)),m=t.interactive?await this.promptRunnerSelection(u):xt(t.positionals.ids??[],i.map((p)=>p.id)),f=0;for(let p of m){if(!l.has(p)){o.start(""),o.stop(`${d.dim("\u25CF")} ${p} ${d.dim("not running")}`);continue}o.start(`Stopping ${p}...`),await s.stop([p]),o.stop(`${d.red("\u25A0")} ${p}`),f++}w.info(`${d.green("Stopped")} ${f} runner(s).`)}async promptRunnerSelection(t){if(t.length===0)throw new v("No runners are currently running");return dt({message:"Select runners to stop",options:t.map((e)=>({label:e,value:e})),required:!0})}}class Se extends T{name="update";description="Update runner binaries";async execute(t){N(t.args,this.args,"Run 'hydra update --help' for supported options");let e=t.config.get("profiles"),r=t.config.get("runners")??[];if(r.length===0)throw new v("No runners found","Run hydra create to provision runners");let n=K(),i=Map.groupBy(r,(o)=>o.profile),s=0;for(let[o,a]of i){let l=Object.hasOwn(e,o)?e[o]:void 0;if(!l)continue;let u=U(l);n.start(`Checking for updates for "${o}"...`);let{version:m}=await u.download();n.stop(`Latest: v${m}`);let f=await u.list(),p=new Set(f.filter((g)=>g.status==="running").map((g)=>g.id));for(let g of a){if(await u.currentVersion(g.id)===m)continue;let h=p.has(g.id);if(n.start(`Updating ${g.id}...`),h)await u.stop([g.id]);if(await u.update([g.id]),h)await u.start([g.id]);s++;let y=h?` ${d.dim("(restarted)")}`:"";n.stop(`${d.green("\u2713")} ${g.id}${y}`)}}w.info(s>0?`${d.green("Updated")} ${s} runner(s).`:"All runners are already on the latest version."),await he(t)}}class kn extends Ke{constructor(){super(new ze(sn,on),{bin:ne,clearOnStart:!0,description:"Manage GitHub Actions runners on this machine.",exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:nn})}init(){this.registerCommands([new ye,new ge,new be,new xe,new Ce,new $e,new me,new we,new Se,new ve])}}var oo=new kn;oo.run();
|
package/package.json
CHANGED