@r5n/sisyphus 0.9.0 → 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/dist/cli.js CHANGED
@@ -1,224 +1,223 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var Mo=Object.create;var{getPrototypeOf:Do,defineProperty:ji,getOwnPropertyNames:Fo}=Object;var jo=Object.prototype.hasOwnProperty;function No(e){return this[e]}var To,Bo,Ni=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var i=t?To??=new WeakMap:Bo??=new WeakMap,s=i.get(e);if(s)return s}r=e!=null?Mo(Do(e)):{};let a=t||!e||!e.__esModule?ji(r,"default",{value:e,enumerable:!0}):r;for(let o of Fo(e))if(!jo.call(a,o))ji(a,o,{get:No.bind(e,o),enumerable:!0});if(n)i.set(e,a);return a};var Uo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Kr=Uo((fm,Xi)=>{var zr={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let r="";if(e<0)r+=`\x1B[${-e}D`;else if(e>0)r+=`\x1B[${e}C`;if(t<0)r+=`\x1B[${-t}A`;else if(t>0)r+=`\x1B[${t}B`;return r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ec={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},tc={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?zr.up():"");if(e)t+=zr.left;return t}};Xi.exports={cursor:zr,scroll:ec,erase:tc,beep:"\x07"}});class me extends Error{constructor(e="Operation cancelled"){super(e)}}class g extends Error{hint;exitCode;constructor(e,t,r=1){super(e);this.hint=t;this.exitCode=r}}import{styleText as Wt}from"util";import{stdout as Qr,stdin as rs}from"process";import*as Le from"readline";import rc from"readline";var Ti=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),Bi=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Ui=(e)=>{return e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141};var Go=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,qo=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Gi=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Ho=/\t{1,1000}/y,qi=/[\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,_o=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Vo=/\p{M}+/gu,Wo={limit:1/0,ellipsis:""},Hi=(e,t={},r={})=>{let n=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?Hi(i,Wo,r).width:0),a=0,o=r.controlWidth??0,c=r.tabWidth??8,p=r.emojiWidth??2,m=2,u=r.regularWidth??1,f=r.wideWidth??2,b=[[_o,u],[Go,0],[qo,o],[Ho,c],[qi,p],[Gi,f]],d=0,P=0,S=e.length,$=0,R=!1,_=S,F=Math.max(0,n-s),E=0,W=0,G=0,U=0;e:while(!0){if(W>E||P>=S&&P>d){let V=e.slice(E,W)||e.slice(d,P);$=0;for(let fe of V.replaceAll(Vo,"")){let ee=fe.codePointAt(0)||0;if(Bi(ee))U=2;else if(Ui(ee))U=f;else U=u;if(G+U>F)_=Math.min(_,Math.max(E,d)+$);if(G+U>n){R=!0;break e}$+=fe.length,G+=U}E=W=0}if(P>=S)break e;for(let V=0,fe=b.length;V<fe;V++){let[ee,Ut]=b[V];if(ee.lastIndex=P,ee.test(e)){if($=ee===Gi?Ti(e.slice(P,ee.lastIndex)):ee===qi?1:ee.lastIndex-P,U=$*Ut,G+U>F)_=Math.min(_,P+Math.floor((F-G)/Ut));if(G+U>n){R=!0;break e}G+=U,E=d,W=P,P=d=ee.lastIndex;continue e}}P+=1}return{width:R?F:G,index:R?_:S,truncated:R,ellipsed:R&&n>=s}},_i=Hi;var Jo={limit:1/0,ellipsis:"",ellipsisWidth:0},zo=(e,t={})=>{return _i(e,Jo,t).width},te=zo;var qt="\x1B",Ki="\x9B",Ko=39,Wr="\x07",Yi="[",Yo="]",Zi="m",Jr=`${Yo}8;;`,Vi=new RegExp(`(?:\\${Yi}(?<code>\\d+)m|\\${Jr}(?<uri>.*)${Wr})`,"y"),Wi=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},Ji=(e)=>`${qt}${Yi}${e}${Zi}`,zi=(e)=>`${qt}${Jr}${e}${Wr}`,Vr=(e,t,r)=>{let n=t[Symbol.iterator](),i=!1,s=!1,a=e.at(-1),o=a===void 0?0:te(a),c=n.next(),p=n.next(),m=0;while(!c.done){let u=c.value,f=te(u);if(o+f<=r)e[e.length-1]+=u;else e.push(u),o=0;if(u===qt||u===Ki)i=!0,s=t.startsWith(Jr,m+1);if(i){if(s){if(u===Wr)i=!1,s=!1}else if(u===Zi)i=!1}else if(o+=f,o===r&&!p.done)e.push(""),o=0;c=p,p=n.next(),m+=u.length}if(a=e.at(-1),!o&&a!==void 0&&a.length&&e.length>1)e[e.length-2]+=e.pop()},Zo=(e)=>{let t=e.split(" "),r=t.length;while(r){if(te(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},Xo=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,s,a=e.split(" "),o=[""],c=0;for(let u=0;u<a.length;u++){let f=a[u];if(r.trim!==!1){let d=o.at(-1)??"",P=d.trimStart();if(d.length!==P.length)o[o.length-1]=P,c=te(P)}if(u!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))o.push(""),c=0;if(c||r.trim===!1)o[o.length-1]+=" ",c++}let b=te(f);if(r.hard&&b>t){let d=t-c,P=1+Math.floor((b-d-1)/t);if(Math.floor((b-1)/t)<P)o.push("");Vr(o,f,t),c=te(o.at(-1)??"");continue}if(c+b>t&&c&&b){if(r.wordWrap===!1&&c<t){Vr(o,f,t),c=te(o.at(-1)??"");continue}o.push(""),c=0}if(c+b>t&&r.wordWrap===!1){Vr(o,f,t),c=te(o.at(-1)??"");continue}o[o.length-1]+=f,c+=b}if(r.trim!==!1)o=o.map((u)=>Zo(u));let p=o.join(`
4
- `),m=!1;for(let u=0;u<p.length;u++){let f=p[u];if(n+=f,!m){if(m=f>="\uD800"&&f<="\uDBFF",m)continue}else m=!1;if(f===qt||f===Ki){Vi.lastIndex=u+1;let d=Vi.exec(p)?.groups;if(d?.code!==void 0){let P=Number.parseFloat(d.code);i=P===Ko?void 0:P}else if(d?.uri!==void 0)s=d.uri.length===0?void 0:d.uri}if(p[u+1]===`
5
- `){if(s)n+=zi("");let b=i?Wi(i):void 0;if(i&&b)n+=Ji(b)}else if(f===`
6
- `){if(i&&Wi(i))n+=Ji(i);if(s)n+=zi(s)}}return n},Qo=/\r?\n/;function he(e,t,r){return String(e).normalize().split(Qo).map((n)=>Xo(n,t,r)).join(`
7
- `)}var X=Ni(Kr(),1);import{ReadStream as Qi}from"tty";function ve(e,t,r){if(!r.some((a)=>!a.disabled))return e;let n=e+t,i=Math.max(r.length-1,0),s=n<0?i:n>i?0:n;return r[s]?.disabled?ve(s,t<0?-1:1,r):s}function Ht(e,t,r,n){let i=n.split(`
8
- `),s=0,a=e;for(let c of i){if(a<=c.length)break;a-=c.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+r)),a=Math.min(a,i[s].length)+t;a<0&&s>0;)s--,a+=i[s].length+1;for(;a>i[s].length&&s<i.length-1;)a-=i[s].length+1,s++;a=Math.max(0,Math.min(i[s].length,a));let o=0;for(let c=0;c<s;c++)o+=i[c].length+1;return o+a}var nc=["up","down","left","right","space","enter","cancel"],ic=["January","February","March","April","May","June","July","August","September","October","November","December"],K={actions:new Set(nc),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:[...ic],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function en(e,t){if(typeof e=="string")return K.aliases.get(e)===t;for(let r of e)if(r!==void 0&&en(r,t))return!0;return!1}function sc(e,t){if(e===t)return;let r=e.split(`
9
- `),n=t.split(`
10
- `),i=Math.max(r.length,n.length),s=[];for(let a=0;a<i;a++)r[a]!==n[a]&&s.push(a);return{lines:s,numLinesBefore:r.length,numLinesAfter:n.length,numLines:i}}var ac=globalThis.process.platform.startsWith("win"),Zr=Symbol("clack:cancel");function dt(e){return e===Zr}function _t(e,t){let r=e;r.isTTY&&r.setRawMode(t)}function ns({input:e=rs,output:t=Qr,overwrite:r=!0,hideCursor:n=!0}={}){let i=Le.createInterface({input:e,output:t,prompt:"",tabSize:1});Le.emitKeypressEvents(e,i),e instanceof Qi&&e.isTTY&&e.setRawMode(!0);let s=(a,{name:o,sequence:c})=>{let p=String(a);if(en([p,o,c],"cancel")){n&&t.write(X.cursor.show),process.exit(0);return}if(!r)return;Le.moveCursor(t,o==="return"?0:-1,o==="return"?-1:0,()=>{Le.clearLine(t,1,()=>{e.once("keypress",s)})})};return n&&t.write(X.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),n&&t.write(X.cursor.show),e instanceof Qi&&e.isTTY&&!ac&&e.setRawMode(!1),i.terminal=!1,i.close()}}var ft=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,tn=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function Ae(e,t,r,n=r,i=r,s){let a=ft(e??Qr);return he(t,a-r.length,{hard:!0,trim:!1}).split(`
11
- `).map((o,c,p)=>{let m=s?s(o,c):o;return c===0?`${n}${m}`:c===p.length-1?`${i}${m}`:`${r}${m}`}).join(`
12
- `)}function is(e,t){if("~standard"in e){let r=e["~standard"].validate(t);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 e(t)}class Re{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:r=rs,output:n=Qr,render:i,signal:s,...a}=e;this.opts=a,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=t,this._abortSignal=s,this.input=r,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let r=this._subscribers.get(e)??[];r.push(t),this._subscribers.set(e,r)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let r=this._subscribers.get(e)??[],n=[];for(let i of r)i.cb(...t),i.once&&n.push(()=>r.splice(r.indexOf(i),1));for(let i of n)i()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Zr);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=rc.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),_t(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(X.cursor.show),this.output.off("resize",this.render),_t(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(X.cursor.show),this.output.off("resize",this.render),_t(this.input,!1),e(Zr)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&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(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&K.aliases.has(t.name)&&this.emit("cursor",K.aliases.get(t.name)),K.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let r=is(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")}en([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
13
- `),_t(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=he(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
14
- `).length-1;this.output.write(X.cursor.move(-999,e*-1))}render(){let e=he(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(X.cursor.hide);else{let t=sc(this._prevFrame,e),r=tn(this.output);if(this.restoreCursor(),t){let n=Math.max(0,t.numLinesAfter-r),i=Math.max(0,t.numLinesBefore-r),s=t.lines.find((a)=>a>=n);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(X.cursor.move(0,s-i)),this.output.write(X.erase.lines(1));let a=e.split(`
15
- `);this.output.write(a[s]),this._prevFrame=e,this.output.write(X.cursor.move(0,a.length-s-1));return}else if(t.lines.length>1){if(n<i)s=n;else{let o=s-i;o>0&&this.output.write(X.cursor.move(0,o))}this.output.write(X.erase.down());let a=e.split(`
16
- `).slice(s);this.output.write(a.join(`
17
- `)),this._prevFrame=e;return}}this.output.write(X.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function oc(e,t){if(e===void 0||t.length===0)return 0;let r=t.findIndex((n)=>n.value===e);return r!==-1?r:0}function cc(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function lc(e,t){if(t)return e?t:t[0]}var pc=class extends Re{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#i="";#e;#s;#o;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Wt(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this.cursor),r=this.userInput.slice(this.cursor,this.cursor+1),n=this.userInput.slice(this.cursor+1);return`${t}${Wt("inverse",r)}${n}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#o=t.placeholder;let r=this.options;this.filteredOptions=[...r],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??cc;let n;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?n=t.initialValue:n=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(n=[this.options[0]?.value]),n)for(let i of n){let s=r.findIndex((a)=>a.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#r(i,s)),this.on("userInput",(i)=>this.#n(i))}_isActionKey(t,r){return t==="\t"||this.multiple&&this.isNavigating&&r.name==="space"&&t!==void 0&&t!==""}#r(t,r){let n=r.name==="up",i=r.name==="down",s=r.name==="return",a=this.userInput===""||this.userInput==="\t",o=this.#o,c=this.options,p=o!==void 0&&o!==""&&c.some((m)=>!m.disabled&&(this.#e?this.#e(o,m):!0));if(r.name==="tab"&&a&&p){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(o,!0),this.isNavigating=!1;return}n||i?(this.#t=ve(this.#t,n?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=lc(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(r.name==="tab"||this.isNavigating&&r.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((r)=>r!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#n(t){if(t!==this.#i){this.#i=t;let r=this.options;t&&this.#e?this.filteredOptions=r.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...r];let n=oc(this.focusedValue,this.filteredOptions);this.#t=ve(n,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class rn extends Re{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(X.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var gc={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function es(e){return[...e].map((t)=>gc[t])}function mc(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),r=[],n="/";for(let i of t)i.type==="literal"?n=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&r.push({type:i.type,len:i.type==="year"?4:2});return{segments:r,separator:n}}function Yr(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Vt(e){return{year:Yr(e.year),month:Yr(e.month),day:Yr(e.day)}}function Xr(e,t){return new Date(e||2001,t||1,0).getDate()}function ss(e){let{year:t,month:r,day:n}=Vt(e);if(!t||t<0||t>9999||!r||r<1||r>12||!n||n<1)return;let i=new Date(Date.UTC(t,r-1,n));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==r-1||i.getUTCDate()!==n))return{year:t,month:r,day:n}}function ts(e){let t=ss(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function uc(e,t,r,n){let i=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null,s=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:Xr(t.year,t.month)}}class as extends Re{#t;#i;#e;#s;#o;#r={segmentIndex:0,positionInSegment:0};#n=!0;#a=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#i}get formattedValue(){return this.#g(this.#e)}#g(e){return this.#t.map((t)=>e[t.type]).join(this.#i)}#c(){this._setUserInput(this.#g(this.#e)),this._setValue(ts(this.#e)??void 0)}constructor(e){let t=e.format?{segments:es(e.format),separator:e.separator??"/"}:mc(e.locale),r=e.separator??t.separator,n=e.format?es(e.format):t.segments,i=e.initialValue??e.defaultValue,s=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=n.map((o)=>s[o.type]).join(r);super({...e,initialUserInput:a},!1),this.#t=n,this.#i=r,this.#e=s,this.#s=e.minDate,this.#o=e.maxDate,this.#c(),this.on("cursor",(o)=>this.#d(o)),this.on("key",(o,c)=>this.#f(o,c)),this.on("finalize",()=>this.#h(e))}#l(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,t.len-1)),{segment:t,index:e}}#p(e){this.inlineError="",this.#a=null;let t=this.#l();t&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#r.positionInSegment=0,this.#n=!0)}#m(e){let t=this.#l();if(!t)return;let{segment:r}=t,n=this.#e[r.type],i=!n||n.replace(/_/g,"")==="",s=Number.parseInt((n||"0").replace(/_/g,"0"),10)||0,a=uc(r.type,Vt(this.#e),this.#s,this.#o),o;i?o=e===1?a.min:a.max:o=Math.max(Math.min(a.max,s+e),a.min),this.#e={...this.#e,[r.type]:o.toString().padStart(r.len,"0")},this.#n=!0,this.#a=null,this.#c()}#d(e){if(e)switch(e){case"right":return this.#p(1);case"left":return this.#p(-1);case"up":return this.#m(1);case"down":return this.#m(-1)}}#f(e,t){if(t?.name==="backspace"||t?.sequence==="\x7F"||t?.sequence==="\b"||e==="\x7F"||e==="\b"){this.inlineError="";let r=this.#l();if(!r)return;if(!this.#e[r.segment.type].replace(/_/g,"")){this.#p(-1);return}this.#e[r.segment.type]="_".repeat(r.segment.len),this.#n=!0,this.#r.positionInSegment=0,this.#c();return}if(t?.name==="tab"){this.inlineError="";let r=this.#l();if(!r)return;let n=t.shift?-1:1,i=r.index+n;i>=0&&i<this.#t.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#n=!0);return}if(e&&/^[0-9]$/.test(e)){let r=this.#l();if(!r)return;let{segment:n}=r,i=!this.#e[n.type].replace(/_/g,"");if(this.#n&&this.#a!==null&&!i){let f=this.#a+e,b={...this.#e,[n.type]:f},d=this.#u(b,n);if(d){this.inlineError=d,this.#a=null,this.#n=!1;return}this.inlineError="",this.#e[n.type]=f,this.#a=null,this.#n=!1,this.#c(),r.index<this.#t.length-1&&(this.#r.segmentIndex=r.index+1,this.#r.positionInSegment=0,this.#n=!0);return}this.#n&&!i&&(this.#e[n.type]="_".repeat(n.len),this.#r.positionInSegment=0),this.#n=!1,this.#a=null;let s=this.#e[n.type],a=s.indexOf("_"),o=a>=0?a:Math.min(this.#r.positionInSegment,n.len-1);if(o<0||o>=n.len)return;let c=s.slice(0,o)+e+s.slice(o+1),p=!1;if(o===0&&s==="__"&&(n.type==="month"||n.type==="day")){let f=Number.parseInt(e,10);c=`0${e}`,p=f<=(n.type==="month"?1:2)}if(n.type==="year"&&(c=(s.replace(/_/g,"")+e).padStart(n.len,"_")),!c.includes("_")){let f={...this.#e,[n.type]:c},b=this.#u(f,n);if(b){this.inlineError=b;return}}this.inlineError="",this.#e[n.type]=c;let m=c.includes("_")?void 0:ss(this.#e);if(m){let{year:f,month:b}=m,d=Xr(f,b);this.#e={year:String(Math.max(0,Math.min(9999,f))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,b))).padStart(2,"0"),day:String(Math.max(1,Math.min(d,m.day))).padStart(2,"0")}}this.#c();let u=c.indexOf("_");p?(this.#n=!0,this.#a=e):u>=0?this.#r.positionInSegment=u:a>=0&&r.index<this.#t.length-1?(this.#r.segmentIndex=r.index+1,this.#r.positionInSegment=0,this.#n=!0):this.#r.positionInSegment=Math.min(o+1,n.len-1)}}#u(e,t){let{month:r,day:n}=Vt(e);if(t.type==="month"&&(r<0||r>12))return K.date.messages.invalidMonth;if(t.type==="day"&&(n<0||n>31))return K.date.messages.invalidDay(31,"any month")}#h(e){let{year:t,month:r,day:n}=Vt(this.#e);if(t&&r&&n){let i=Xr(t,r);this.#e={...this.#e,day:String(Math.min(n,i)).padStart(2,"0")}}this.value=ts(this.#e)??e.defaultValue??void 0}}var dc=class extends Re{options;cursor=0;#t;getGroupItems(t){return this.options.filter((r)=>r.group===t)}isGroupSelected(t){let r=this.getGroupItems(t),n=this.value;return n===void 0?!1:r.every((i)=>n.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let r=t.value,n=this.getGroupItems(r);this.isGroupSelected(r)?this.value=this.value.filter((i)=>n.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...n.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let r=this.value.includes(t.value);this.value=r?this.value.filter((n)=>n!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:r}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(r).flatMap(([n,i])=>[{value:n,group:!0,label:n},...i.map((s)=>({...s,group:n}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),this.#t?0:1),this.on("cursor",(n)=>{switch(n){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.#t&&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.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},fc=new Set(["up","down","left","right"]);class os extends Re{#t=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}\u2588`;let t=e.slice(0,this.cursor),r=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return r===`
18
- `?`${t}\u2588
19
- ${n}`:`${t}${Wt("inverse",r)}${n}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#s(e){let t=this.value??"";switch(e){case"up":this._cursor=Ht(this._cursor,0,-1,t);return;case"down":this._cursor=Ht(this._cursor,0,1,t);return;case"left":this._cursor=Ht(this._cursor,-1,0,t);return;case"right":this._cursor=Ht(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#i)return this.focused==="submit"?!0:(this.#e(`
20
- `),this._cursor++,!1);let r=this.#t;return this.#t=!0,r&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
21
- `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
22
- `),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#i=e.showSubmit??!1,this.on("key",(r,n)=>{if(n?.name&&fc.has(n.name)){this.#t=!1,this.#s(n.name);return}if(r==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(n?.name!=="return"){if(this.#t=!1,n?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(n?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}r&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#e(r??""),this._cursor++)}}),this.on("userInput",(r)=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class nn extends Re{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((r)=>r.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((r)=>!e.includes(r.value));this.value=t.map((r)=>r.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),0);this.cursor=this.options[t]?.disabled?ve(t,1,this.options):t,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=ve(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ve(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var cs=class extends Re{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let r=this.options.findIndex(({value:i})=>i===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n]?.disabled?ve(n,1,this.options):n,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=ve(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ve(this.cursor,1,this.options);break}this.changeValue()})}};class sn extends Re{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),r=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return`${t}${Wt("inverse",r)}${n}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as h,stripVTControlCharacters as Em}from"util";import le from"process";var wt=Ni(Kr(),1);function hc(){if(le.platform!=="win32")return le.env.TERM!=="linux";return Boolean(le.env.CI)||Boolean(le.env.WT_SESSION)||Boolean(le.env.TERMINUS_SUBLIME)||le.env.ConEmuTask==="{cmd::Cmder}"||le.env.TERM_PROGRAM==="Terminus-Sublime"||le.env.TERM_PROGRAM==="vscode"||le.env.TERM==="xterm-256color"||le.env.TERM==="alacritty"||le.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var an=hc(),wc=()=>process.env.CI==="true";var D=(e,t)=>an?e:t,yc=D("\u25C6","*"),us=D("\u25A0","x"),ds=D("\u25B2","x"),Kt=D("\u25C7","o"),bc=D("\u250C","T"),C=D("\u2502","|"),xe=D("\u2514","\u2014"),xm=D("\u2510","T"),Om=D("\u2518","\u2014"),on=D("\u25CF",">"),zt=D("\u25CB"," "),Pc=D("\u25FB","[\u2022]"),ls=D("\u25FC","[+]"),ps=D("\u25FB","[ ]"),Mm=D("\u25AA","\u2022"),gs=D("\u2500","-"),vc=D("\u256E","+"),Rc=D("\u251C","+"),kc=D("\u256F","+"),$c=D("\u2570","+"),Dm=D("\u256D","+"),Cc=D("\u25CF","\u2022"),Sc=D("\u25C6","*"),Ec=D("\u25B2","!"),Ic=D("\u25A0","x"),Yt=(e)=>{switch(e){case"initial":case"active":return h("cyan",yc);case"cancel":return h("red",us);case"error":return h("yellow",ds);case"submit":return h("green",Kt)}},fs=(e)=>{switch(e){case"initial":case"active":return h("cyan",C);case"cancel":return h("red",C);case"error":return h("yellow",C);case"submit":return h("green",C)}};function hs(e,t){let r=[`${t?`${h("cyan",C)} `:""}${e.join(" \u2022 ")}`];return t&&r.push(h("cyan",xe)),r}var ms=(e,t,r,n,i,s=!1)=>{let a=t,o=0;if(s)for(let c=n-1;c>=r;c--){let p=e[c];if(p&&(a-=p.length),o++,a<=i)break}else for(let c=r;c<n;c++){let p=e[c];if(p&&(a-=p.length),o++,a<=i)break}return{lineCount:a,removals:o}},cn=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:a=4})=>{let o=ft(n)-s,c=tn(n),p=h("dim","..."),m=Math.max(c-a,0),u=Math.max(Math.min(i,m),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let b=u<t.length&&f>0,d=u<t.length&&f+u<t.length,P=Math.min(f+u,t.length),S=[],$=0;b&&$++,d&&$++;let R=f+(b?1:0),_=P-(d?1:0);for(let E=R;E<_;E++){let W=t[E],G=W?r(W,E===e):"",U=he(G,o,{hard:!0,trim:!1}).split(`
23
- `);S.push(U),$+=U.length}if($>m){let E=0,W=0,G=$,U=e-R,V=m,fe=()=>ms(S,G,0,U,V),ee=()=>ms(S,G,U+1,S.length,V,!0);b?({lineCount:G,removals:E}=fe(),G>V&&(d||(V-=1),{lineCount:G,removals:W}=ee())):(d||(V-=1),{lineCount:G,removals:W}=ee(),G>V&&(V-=1,{lineCount:G,removals:E}=fe())),E>0&&(b=!0,S.splice(0,E)),W>0&&(d=!0,S.splice(S.length-W,W))}let F=[];b&&F.push(p);for(let E of S)for(let W of E)F.push(W);return d&&F.push(p),F};var ws=(e)=>{let t=e.active??"Yes",r=e.inactive??"No";return new rn({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let n=e.withGuide??K.withGuide,i=`${Yt(this.state)} `,s=n?`${h("gray",C)} `:"",a=Ae(e.output,e.message,s,i),o=`${n?`${h("gray",C)}
24
- `:""}${a}
25
- `,c=this.value?t:r;switch(this.state){case"submit":{let p=n?`${h("gray",C)} `:"";return`${o}${p}${h("dim",c)}`}case"cancel":{let p=n?`${h("gray",C)} `:"";return`${o}${p}${h(["strikethrough","dim"],c)}${n?`
26
- ${h("gray",C)}`:""}`}default:{let p=n?`${h("cyan",C)} `:"",m=n?h("cyan",xe):"";return`${o}${p}${this.value?`${h("green",on)} ${t}`:`${h("dim",zt)} ${h("dim",t)}`}${e.vertical?n?`
27
- ${h("cyan",C)} `:`
28
- `:` ${h("dim","/")} `}${this.value?`${h("dim",zt)} ${h("dim",r)}`:`${h("green",on)} ${r}`}
29
- ${m}
30
- `}}}}).prompt()};var Zt=async(e,t)=>{let r={},n=Object.keys(e);for(let i of n){let s=e[i],a=await s({results:r})?.catch((o)=>{throw o});if(typeof t?.onCancel=="function"&&dt(a)){r[i]="canceled",t.onCancel({results:r});continue}r[i]=a}return r},Lc=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Space:")} select`,`${h("dim","Enter:")} confirm`],ht=(e,t)=>e.split(`
3
+ var Jc=Object.create;var{getPrototypeOf:zc,defineProperty:Si,getOwnPropertyNames:Kc}=Object;var Ci=Object.prototype.hasOwnProperty;function Yc(e){return this[e]}var Xc,Zc,ki=(e,t,r)=>{var s=e!=null&&typeof e==="object";if(s){var n=t?Xc??=new WeakMap:Zc??=new WeakMap,i=n.get(e);if(i)return i}r=e!=null?Jc(zc(e)):{};let o=t||!e||!e.__esModule||!Ci.call(e,"default")?Si(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Kc(e))if(!Ci.call(o,a))Si(o,a,{get:Yc.bind(e,a),enumerable:!0})}if(s)n.set(e,o);return o};var Qc=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ks=Qc(function(cm,Ui){var Cs={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let r="";if(e<0)r+=`\x1B[${-e}D`;else if(e>0)r+=`\x1B[${e}C`;if(t<0)r+=`\x1B[${-t}A`;else if(t>0)r+=`\x1B[${t}B`;return r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},gl={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},ml={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?Cs.up():"");if(e)t+=Cs.left;return t}};Ui.exports={cursor:Cs,scroll:gl,erase:ml,beep:"\x07"}});class fe extends Error{constructor(e="Operation cancelled"){super(e)}}class u extends Error{hint;exitCode;constructor(e,t,r=1){super(e);this.hint=t;this.exitCode=r}}import{styleText as hl}from"util";import{stdout as Ts,stdin as Gi}from"process";import*as Le from"readline";import fl from"readline";var xi=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),Ti=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ei=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var el=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,tl=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ii=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,rl=/\t{1,1000}/y,Ai=/[\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,sl=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,nl=/\p{M}+/gu,il={limit:1/0,ellipsis:""},Oi=(e,t={},r={})=>{let s=t.limit??1/0,n=t.ellipsis??"",i=t?.ellipsisWidth??(n?Oi(n,il,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,d=2,g=r.regularWidth??1,h=r.wideWidth??2,f=[[sl,g],[el,0],[tl,a],[rl,c],[Ai,l],[Ii,h]],m=0,y=0,R=e.length,S=0,C=!1,q=R,L=Math.max(0,s-i),T=0,K=0,V=0,U=0;e:while(!0){if(K>T||y>=R&&y>m){let W=e.slice(T,K)||e.slice(m,y);S=0;for(let Pe of W.replaceAll(nl,"")){let re=Pe.codePointAt(0)||0;if(Ti(re))U=2;else if(Ei(re))U=h;else U=g;if(V+U>L)q=Math.min(q,Math.max(T,m)+S);if(V+U>s){C=!0;break e}S+=Pe.length,V+=U}T=K=0}if(y>=R)break e;for(let W=0,Pe=f.length;W<Pe;W++){let[re,cr]=f[W];if(re.lastIndex=y,re.test(e)){if(S=re===Ii?xi(e.slice(y,re.lastIndex)):re===Ai?1:re.lastIndex-y,U=S*cr,V+U>L)q=Math.min(q,y+Math.floor((L-V)/cr));if(V+U>s){C=!0;break e}V+=U,T=m,K=y,y=m=re.lastIndex;continue e}}y+=1}return{width:C?L:V,index:C?q:R,truncated:C,ellipsed:C&&s>=i}},_i=Oi;var ol={limit:1/0,ellipsis:"",ellipsisWidth:0},al=(e,t={})=>_i(e,ol,t).width,se=al;var ur="\x1B",ji="\x9B",cl=39,Rs="\x07",Bi="[",ll="]",Fi="m",Ss=`${ll}8;;`,Mi=new RegExp(`(?:\\${Bi}(?<code>\\d+)m|\\${Ss}(?<uri>.*)${Rs})`,"y"),Li=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},Di=(e)=>`${ur}${Bi}${e}${Fi}`,Ni=(e)=>`${ur}${Ss}${e}${Rs}`,Ps=(e,t,r)=>{let s=t[Symbol.iterator](),n=!1,i=!1,o=e.at(-1),a=o===void 0?0:se(o),c=s.next(),l=s.next(),d=0;while(!c.done){let g=c.value,h=se(g);if(a+h<=r)e[e.length-1]+=g;else e.push(g),a=0;if(g===ur||g===ji)n=!0,i=t.startsWith(Ss,d+1);if(n){if(i){if(g===Rs)n=!1,i=!1}else if(g===Fi)n=!1}else if(a+=h,a===r&&!l.done)e.push(""),a=0;c=l,l=s.next(),d+=g.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},ul=(e)=>{let t=e.split(" "),r=t.length;while(r){if(se(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},pl=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let s="",n,i,o=e.split(" "),a=[""],c=0;for(let g=0;g<o.length;g++){let h=o[g];if(r.trim!==!1){let m=a.at(-1)??"",y=m.trimStart();if(m.length!==y.length)a[a.length-1]=y,c=se(y)}if(g!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let f=se(h);if(r.hard&&f>t){let m=t-c,y=1+Math.floor((f-m-1)/t);if(Math.floor((f-1)/t)<y)a.push("");Ps(a,h,t),c=se(a.at(-1)??"");continue}if(c+f>t&&c&&f){if(r.wordWrap===!1&&c<t){Ps(a,h,t),c=se(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>t&&r.wordWrap===!1){Ps(a,h,t),c=se(a.at(-1)??"");continue}a[a.length-1]+=h,c+=f}if(r.trim!==!1)a=a.map((g)=>ul(g));let l=a.join(`
4
+ `),d=!1;for(let g=0;g<l.length;g++){let h=l[g];if(s+=h,!d){if(d=h>="\uD800"&&h<="\uDBFF",d)continue}else d=!1;if(h===ur||h===ji){Mi.lastIndex=g+1;let m=Mi.exec(l)?.groups;if(m?.code!==void 0){let y=Number.parseFloat(m.code);n=y===cl?void 0:y}else if(m?.uri!==void 0)i=m.uri.length===0?void 0:m.uri}if(l[g+1]===`
5
+ `){if(i)s+=Ni("");let f=n?Li(n):void 0;if(n&&f)s+=Di(f)}else if(h===`
6
+ `){if(n&&Li(n))s+=Di(n);if(i)s+=Ni(i)}}return s},dl=/\r?\n/;function Re(e,t,r){return String(e).normalize().split(dl).map((s)=>pl(s,t,r)).join(`
7
+ `)}var te=ki(ks(),1);import{ReadStream as Vi}from"tty";function ze(e,t,r){if(!r.some((o)=>!o.disabled))return e;let s=e+t,n=Math.max(r.length-1,0),i=s<0?n:s>n?0:s;return r[i]?.disabled?ze(i,t<0?-1:1,r):i}var yl=["up","down","left","right","space","enter","cancel"],wl=["January","February","March","April","May","June","July","August","September","October","November","December"],Q={actions:new Set(yl),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:[...wl],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Es(e,t){if(typeof e=="string")return Q.aliases.get(e)===t;for(let r of e)if(r!==void 0&&Es(r,t))return!0;return!1}function bl(e,t){if(e===t)return;let r=e.split(`
8
+ `),s=t.split(`
9
+ `),n=Math.max(r.length,s.length),i=[];for(let o=0;o<n;o++)r[o]!==s[o]&&i.push(o);return{lines:i,numLinesBefore:r.length,numLinesAfter:s.length,numLines:n}}var vl=globalThis.process.platform.startsWith("win"),xs=Symbol("clack:cancel");function Tt(e){return e===xs}function pr(e,t){let r=e;r.isTTY&&r.setRawMode(t)}function Hi({input:e=Gi,output:t=Ts,overwrite:r=!0,hideCursor:s=!0}={}){let n=Le.createInterface({input:e,output:t,prompt:"",tabSize:1});Le.emitKeypressEvents(e,n),e instanceof Vi&&e.isTTY&&e.setRawMode(!0);let i=(o,{name:a,sequence:c})=>{let l=String(o);if(Es([l,a,c],"cancel")){s&&t.write(te.cursor.show),process.exit(0);return}if(!r)return;Le.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Le.clearLine(t,1,()=>{e.once("keypress",i)})})};return s&&t.write(te.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),s&&t.write(te.cursor.show),e instanceof Vi&&e.isTTY&&!vl&&e.setRawMode(!1),n.terminal=!1,n.close()}}var Et=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Is=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function De(e,t,r,s=r,n=r,i){let o=Et(e??Ts);return Re(t,o-r.length,{hard:!0,trim:!1}).split(`
10
+ `).map((a,c,l)=>{let d=i?i(a,c):a;return c===0?`${s}${d}`:c===l.length-1?`${n}${d}`:`${r}${d}`}).join(`
11
+ `)}function qi(e,t){if("~standard"in e){let r=e["~standard"].validate(t);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 e(t)}class It{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:r=Gi,output:s=Ts,render:n,signal:i,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=n.bind(this),this._track=t,this._abortSignal=i,this.input=r,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let r=this._subscribers.get(e)??[];r.push(t),this._subscribers.set(e,r)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let r=this._subscribers.get(e)??[],s=[];for(let n of r)n.cb(...t),n.once&&s.push(()=>r.splice(r.indexOf(n),1));for(let n of s)n()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(xs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=fl.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),pr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(te.cursor.show),this.output.off("resize",this.render),pr(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(te.cursor.show),this.output.off("resize",this.render),pr(this.input,!1),e(xs)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&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(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&Q.aliases.has(t.name)&&this.emit("cursor",Q.aliases.get(t.name)),Q.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let r=qi(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")}Es([e,t?.name,t?.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
+ `),pr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Re(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
+ `).length-1;this.output.write(te.cursor.move(-999,e*-1))}render(){let e=Re(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(te.cursor.hide);else{let t=bl(this._prevFrame,e),r=Is(this.output);if(this.restoreCursor(),t){let s=Math.max(0,t.numLinesAfter-r),n=Math.max(0,t.numLinesBefore-r),i=t.lines.find((o)=>o>=s);if(i===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(te.cursor.move(0,i-n)),this.output.write(te.erase.lines(1));let o=e.split(`
14
+ `);this.output.write(o[i]),this._prevFrame=e,this.output.write(te.cursor.move(0,o.length-i-1));return}else if(t.lines.length>1){if(s<n)i=s;else{let a=i-n;a>0&&this.output.write(te.cursor.move(0,a))}this.output.write(te.erase.down());let o=e.split(`
15
+ `).slice(i);this.output.write(o.join(`
16
+ `)),this._prevFrame=e;return}}this.output.write(te.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}class As extends It{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(te.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class Os extends It{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((r)=>r.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((r)=>!e.includes(r.value));this.value=t.map((r)=>r.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),0);this.cursor=this.options[t]?.disabled?ze(t,1,this.options):t,this.on("key",(r,s)=>{s.name==="a"&&this.toggleAll(),s.name==="i"&&this.toggleInvert()}),this.on("cursor",(r)=>{switch(r){case"left":case"up":this.cursor=ze(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ze(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Wi=class extends It{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let r=this.options.findIndex(({value:n})=>n===t.initialValue),s=r===-1?0:r;this.cursor=this.options[s]?.disabled?ze(s,1,this.options):s,this.changeValue(),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=ze(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ze(this.cursor,1,this.options);break}this.changeValue()})}};class _s extends It{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),r=e.slice(this.cursor,this.cursor+1),s=e.slice(this.cursor+1);return`${t}${hl("inverse",r)}${s}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as w,stripVTControlCharacters as Sm}from"util";import ue from"process";var Ot=ki(ks(),1);function $l(){if(ue.platform!=="win32")return ue.env.TERM!=="linux";return Boolean(ue.env.CI)||Boolean(ue.env.WT_SESSION)||Boolean(ue.env.TERMINUS_SUBLIME)||ue.env.ConEmuTask==="{cmd::Cmder}"||ue.env.TERM_PROGRAM==="Terminus-Sublime"||ue.env.TERM_PROGRAM==="vscode"||ue.env.TERM==="xterm-256color"||ue.env.TERM==="alacritty"||ue.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Ms=$l(),Pl=()=>process.env.CI==="true";var M=(e,t)=>Ms?e:t,Rl=M("\u25C6","*"),Xi=M("\u25A0","x"),Zi=M("\u25B2","x"),mr=M("\u25C7","o"),Sl=M("\u250C","T"),x=M("\u2502","|"),Ne=M("\u2514","\u2014"),Tm=M("\u2510","T"),Em=M("\u2518","\u2014"),Ls=M("\u25CF",">"),gr=M("\u25CB"," "),Cl=M("\u25FB","[\u2022]"),Ji=M("\u25FC","[+]"),zi=M("\u25FB","[ ]"),Im=M("\u25AA","\u2022"),Ki=M("\u2500","-"),kl=M("\u256E","+"),xl=M("\u251C","+"),Tl=M("\u256F","+"),El=M("\u2570","+"),Am=M("\u256D","+"),Il=M("\u25CF","\u2022"),Al=M("\u25C6","*"),Ol=M("\u25B2","!"),_l=M("\u25A0","x"),hr=(e)=>{switch(e){case"initial":case"active":return w("cyan",Rl);case"cancel":return w("red",Xi);case"error":return w("yellow",Zi);case"submit":return w("green",mr)}},Qi=(e)=>{switch(e){case"initial":case"active":return w("cyan",x);case"cancel":return w("red",x);case"error":return w("yellow",x);case"submit":return w("green",x)}};function eo(e,t){let r=[`${t?`${w("cyan",x)} `:""}${e.join(" \u2022 ")}`];return t&&r.push(w("cyan",Ne)),r}var Yi=(e,t,r,s,n,i=!1)=>{let o=t,a=0;if(i)for(let c=s-1;c>=r;c--){let l=e[c];if(l&&(o-=l.length),a++,o<=n)break}else for(let c=r;c<s;c++){let l=e[c];if(l&&(o-=l.length),a++,o<=n)break}return{lineCount:o,removals:a}},Ds=({cursor:e,options:t,style:r,output:s=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=Et(s)-i,c=Is(s),l=w("dim","..."),d=Math.max(c-o,0),g=Math.max(Math.min(n,d),5),h=0;e>=g-3&&(h=Math.max(Math.min(e-g+3,t.length-g),0));let f=g<t.length&&h>0,m=g<t.length&&h+g<t.length,y=Math.min(h+g,t.length),R=[],S=0;f&&S++,m&&S++;let C=h+(f?1:0),q=y-(m?1:0);for(let T=C;T<q;T++){let K=t[T],V=K?r(K,T===e):"",U=Re(V,a,{hard:!0,trim:!1}).split(`
17
+ `);R.push(U),S+=U.length}if(S>d){let T=0,K=0,V=S,U=e-C,W=d,Pe=()=>Yi(R,V,0,U,W),re=()=>Yi(R,V,U+1,R.length,W,!0);f?({lineCount:V,removals:T}=Pe(),V>W&&(m||(W-=1),{lineCount:V,removals:K}=re())):(m||(W-=1),{lineCount:V,removals:K}=re(),V>W&&(W-=1,{lineCount:V,removals:T}=Pe())),T>0&&(f=!0,R.splice(0,T)),K>0&&(m=!0,R.splice(R.length-K,K))}let L=[];f&&L.push(l);for(let T of R)for(let K of T)L.push(K);return m&&L.push(l),L};var to=(e)=>{let t=e.active??"Yes",r=e.inactive??"No";return new As({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let s=e.withGuide??Q.withGuide,n=`${hr(this.state)} `,i=s?`${w("gray",x)} `:"",o=De(e.output,e.message,i,n),a=`${s?`${w("gray",x)}
18
+ `:""}${o}
19
+ `,c=this.value?t:r;switch(this.state){case"submit":{let l=s?`${w("gray",x)} `:"";return`${a}${l}${w("dim",c)}`}case"cancel":{let l=s?`${w("gray",x)} `:"";return`${a}${l}${w(["strikethrough","dim"],c)}${s?`
20
+ ${w("gray",x)}`:""}`}default:{let l=s?`${w("cyan",x)} `:"",d=s?w("cyan",Ne):"";return`${a}${l}${this.value?`${w("green",Ls)} ${t}`:`${w("dim",gr)} ${w("dim",t)}`}${e.vertical?s?`
21
+ ${w("cyan",x)} `:`
22
+ `:` ${w("dim","/")} `}${this.value?`${w("dim",gr)} ${w("dim",r)}`:`${w("green",Ls)} ${r}`}
23
+ ${d}
24
+ `}}}}).prompt()};var fr=async(e,t)=>{let r={},s=Object.keys(e);for(let n of s){let i=e[n],o=await i({results:r})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Tt(o)){r[n]="canceled",t.onCancel({results:r});continue}r[n]=o}return r},Ml=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Space:")} select`,`${w("dim","Enter:")} confirm`],At=(e,t)=>e.split(`
31
25
  `).map((r)=>t(r)).join(`
32
- `),ys=(e)=>{let t=(i,s)=>{let a=i.label??String(i.value);return s==="disabled"?`${h("gray",ps)} ${ht(a,(o)=>h(["strikethrough","gray"],o))}${i.hint?` ${h("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${h("cyan",Pc)} ${a}${i.hint?` ${h("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${h("green",ls)} ${ht(a,(o)=>h("dim",o))}${i.hint?` ${h("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${ht(a,(o)=>h(["strikethrough","dim"],o))}`:s==="active-selected"?`${h("green",ls)} ${a}${i.hint?` ${h("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${ht(a,(o)=>h("dim",o))}`:`${h("dim",ps)} ${ht(a,(o)=>h("dim",o))}`},r=e.required??!0,n=e.showInstructions??!0;return new nn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(i){if(r&&(i===void 0||i.length===0))return`Please select at least one option.
33
- ${h("reset",h("dim",`Press ${h(["gray","bgWhite","inverse"]," space ")} to select, ${h("gray",h("bgWhite",h("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??K.withGuide,s=Ae(e.output,e.message,i?`${fs(this.state)} `:"",`${Yt(this.state)} `),a=`${i?`${h("gray",C)}
34
- `:""}${s}
35
- `,o=this.value??[],c=(p,m)=>{if(p.disabled)return t(p,"disabled");let u=o.includes(p.value);return m&&u?t(p,"active-selected"):u?t(p,"selected"):t(p,m?"active":"inactive")};switch(this.state){case"submit":{let p=this.options.filter(({value:u})=>o.includes(u)).map((u)=>t(u,"submitted")).join(h("dim",", "))||h("dim","none"),m=Ae(e.output,p,i?`${h("gray",C)} `:"");return`${a}${m}`}case"cancel":{let p=this.options.filter(({value:u})=>o.includes(u)).map((u)=>t(u,"cancelled")).join(h("dim",", "));if(p.trim()==="")return`${a}${h("gray",C)}`;let m=Ae(e.output,p,i?`${h("gray",C)} `:"");return`${a}${m}${i?`
36
- ${h("gray",C)}`:""}`}case"error":{let p=i?`${h("yellow",C)} `:"",m=this.error.split(`
37
- `).map((b,d)=>d===0?`${i?`${h("yellow",xe)} `:""}${h("yellow",b)}`:` ${b}`).join(`
38
- `),u=a.split(`
39
- `).length,f=m.split(`
40
- `).length+1;return`${a}${p}${cn({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:p.length,rowPadding:u+f,style:c}).join(`
41
- ${p}`)}
42
- ${m}
43
- `}default:{let p=i?`${h("cyan",C)} `:"",m=a.split(`
44
- `).length,u=n?hs(Lc,i):i?[h("cyan",xe)]:[],f=u.join(`
45
- `),b=u.length+1;return`${a}${p}${cn({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:p.length,rowPadding:m+b,style:c}).join(`
46
- ${p}`)}
47
- ${f}
48
- `}}}}).prompt()};var y={message:(e=[],{symbol:t=h("gray",C),secondarySymbol:r=h("gray",C),output:n=process.stdout,spacing:i=1,withGuide:s}={})=>{let a=[],o=s??K.withGuide,c=o?r:"",p=o?`${t} `:"",m=o?`${r} `:"";for(let f=0;f<i;f++)a.push(c);let u=Array.isArray(e)?e:e.split(`
49
- `);if(u.length>0){let[f,...b]=u;f.length>0?a.push(`${p}${f}`):a.push(o?t:"");for(let d of b)d.length>0?a.push(`${m}${d}`):a.push(o?r:"")}n.write(`${a.join(`
26
+ `),ro=(e)=>{let t=(n,i)=>{let o=n.label??String(n.value);return i==="disabled"?`${w("gray",zi)} ${At(o,(a)=>w(["strikethrough","gray"],a))}${n.hint?` ${w("dim",`(${n.hint??"disabled"})`)}`:""}`:i==="active"?`${w("cyan",Cl)} ${o}${n.hint?` ${w("dim",`(${n.hint})`)}`:""}`:i==="selected"?`${w("green",Ji)} ${At(o,(a)=>w("dim",a))}${n.hint?` ${w("dim",`(${n.hint})`)}`:""}`:i==="cancelled"?`${At(o,(a)=>w(["strikethrough","dim"],a))}`:i==="active-selected"?`${w("green",Ji)} ${o}${n.hint?` ${w("dim",`(${n.hint})`)}`:""}`:i==="submitted"?`${At(o,(a)=>w("dim",a))}`:`${w("dim",zi)} ${At(o,(a)=>w("dim",a))}`},r=e.required??!0,s=e.showInstructions??!0;return new Os({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(n){if(r&&(n===void 0||n.length===0))return`Please select at least one option.
27
+ ${w("reset",w("dim",`Press ${w(["gray","bgWhite","inverse"]," space ")} to select, ${w("gray",w("bgWhite",w("inverse"," enter ")))} to submit`))}`},render(){let n=e.withGuide??Q.withGuide,i=De(e.output,e.message,n?`${Qi(this.state)} `:"",`${hr(this.state)} `),o=`${n?`${w("gray",x)}
28
+ `:""}${i}
29
+ `,a=this.value??[],c=(l,d)=>{if(l.disabled)return t(l,"disabled");let g=a.includes(l.value);return d&&g?t(l,"active-selected"):g?t(l,"selected"):t(l,d?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:g})=>a.includes(g)).map((g)=>t(g,"submitted")).join(w("dim",", "))||w("dim","none"),d=De(e.output,l,n?`${w("gray",x)} `:"");return`${o}${d}`}case"cancel":{let l=this.options.filter(({value:g})=>a.includes(g)).map((g)=>t(g,"cancelled")).join(w("dim",", "));if(l.trim()==="")return`${o}${w("gray",x)}`;let d=De(e.output,l,n?`${w("gray",x)} `:"");return`${o}${d}${n?`
30
+ ${w("gray",x)}`:""}`}case"error":{let l=n?`${w("yellow",x)} `:"",d=this.error.split(`
31
+ `).map((f,m)=>m===0?`${n?`${w("yellow",Ne)} `:""}${w("yellow",f)}`:` ${f}`).join(`
32
+ `),g=o.split(`
33
+ `).length,h=d.split(`
34
+ `).length+1;return`${o}${l}${Ds({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:g+h,style:c}).join(`
35
+ ${l}`)}
36
+ ${d}
37
+ `}default:{let l=n?`${w("cyan",x)} `:"",d=o.split(`
38
+ `).length,g=s?eo(Ml,n):n?[w("cyan",Ne)]:[],h=g.join(`
39
+ `),f=g.length+1;return`${o}${l}${Ds({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:d+f,style:c}).join(`
40
+ ${l}`)}
41
+ ${h}
42
+ `}}}}).prompt()};var v={message:(e=[],{symbol:t=w("gray",x),secondarySymbol:r=w("gray",x),output:s=process.stdout,spacing:n=1,withGuide:i}={})=>{let o=[],a=i??Q.withGuide,c=a?r:"",l=a?`${t} `:"",d=a?`${r} `:"";for(let h=0;h<n;h++)o.push(c);let g=Array.isArray(e)?e:e.split(`
43
+ `);if(g.length>0){let[h,...f]=g;h.length>0?o.push(`${l}${h}`):o.push(a?t:"");for(let m of f)m.length>0?o.push(`${d}${m}`):o.push(a?r:"")}s.write(`${o.join(`
50
44
  `)}
51
- `)},info:(e,t)=>{y.message(e,{...t,symbol:h("blue",Cc)})},success:(e,t)=>{y.message(e,{...t,symbol:h("green",Sc)})},step:(e,t)=>{y.message(e,{...t,symbol:h("green",Kt)})},warn:(e,t)=>{y.message(e,{...t,symbol:h("yellow",Ec)})},warning:(e,t)=>{y.warn(e,t)},error:(e,t)=>{y.message(e,{...t,symbol:h("red",Ic)})}};var Xt=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??K.withGuide?`${h("gray",bc)} `:"";r.write(`${n}${e}
52
- `)},Qt=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??K.withGuide?`${h("gray",C)}
53
- ${h("gray",xe)} `:"";r.write(`${n}${e}
54
-
55
- `)};var Ac=(e)=>e,xc=(e,t,r)=>{let n={hard:!0,trim:!1},i=he(e,t,n).split(`
56
- `),s=i.reduce((c,p)=>Math.max(te(p),c),0),a=i.map(r).reduce((c,p)=>Math.max(te(p),c),0),o=t-(a-s);return he(e,o,n)},q=(e="",t="",r)=>{let n=r?.output??le.stdout,i=r?.withGuide??K.withGuide,s=r?.format??Ac,a=["",...xc(e,ft(n)-6,s).split(`
57
- `).map(s),""],o=te(t),c=Math.max(a.reduce((f,b)=>{let d=te(b);return d>f?d:f},0),o)+2,p=a.map((f)=>`${h("gray",C)} ${f}${" ".repeat(c-te(f))}${h("gray",C)}`).join(`
58
- `),m=i?`${h("gray",C)}
59
- `:"",u=i?Rc:$c;n.write(`${m}${h("green",Kt)} ${h("reset",t)} ${h("gray",gs.repeat(Math.max(c-o-1,1))+vc)}
60
- ${p}
61
- ${h("gray",u+gs.repeat(c+2)+kc)}
62
- `)};var Oc=(e)=>h("magenta",e),ne=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:i,frames:s=an?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=an?80:120,signal:o,...c}={})=>{let p=wc(),m,u,f=!1,b=!1,d="",P,S=performance.now(),$=ft(r),R=c?.styleFrame??Oc,_=(H)=>{let ce=H>1?i??K.messages.error:n??K.messages.cancel;b=H===1,f&&(ut(ce,H),b&&typeof t=="function"&&t())},F=()=>_(2),E=()=>_(1),W=()=>{process.on("uncaughtExceptionMonitor",F),process.on("unhandledRejection",F),process.on("SIGINT",E),process.on("SIGTERM",E),process.on("exit",_),o&&o.addEventListener("abort",E)},G=()=>{process.removeListener("uncaughtExceptionMonitor",F),process.removeListener("unhandledRejection",F),process.removeListener("SIGINT",E),process.removeListener("SIGTERM",E),process.removeListener("exit",_),o&&o.removeEventListener("abort",E)},U=()=>{if(P===void 0)return;p&&r.write(`
63
- `);let H=he(P,$,{hard:!0,trim:!1}).split(`
64
- `);H.length>1&&r.write(wt.cursor.up(H.length-1)),r.write(wt.cursor.to(0)),r.write(wt.erase.down())},V=(H)=>H.replace(/\.+$/,""),fe=(H)=>{let ce=(performance.now()-H)/1000,be=Math.floor(ce/60),Pe=Math.floor(ce%60);return be>0?`[${be}m ${Pe}s]`:`[${Pe}s]`},ee=c.withGuide??K.withGuide,Ut=(H="")=>{f=!0,m=ns({output:r}),d=V(H),S=performance.now(),ee&&r.write(`${h("gray",C)}
65
- `);let ce=0,be=0;W(),u=setInterval(()=>{if(p&&d===P)return;U(),P=d;let Pe=R(s[ce]),Gt;if(p)Gt=`${Pe} ${d}...`;else if(e==="timer")Gt=`${Pe} ${d} ${fe(S)}`;else{let Oo=".".repeat(Math.floor(be)).slice(0,3);Gt=`${Pe} ${d}${Oo}`}let xo=he(Gt,$,{hard:!0,trim:!1});r.write(xo),ce=ce+1<s.length?ce+1:0,be=be<4?be+0.125:0},a)},ut=(H="",ce=0,be=!1)=>{if(!f)return;f=!1,clearInterval(u),U();let Pe=ce===0?h("green",Kt):ce===1?h("red",us):h("red",ds);d=H??d,be||(e==="timer"?r.write(`${Pe} ${d} ${fe(S)}
66
- `):r.write(`${Pe} ${d}
67
- `)),G(),m()};return{start:Ut,stop:(H="")=>ut(H,0),message:(H="")=>{d=V(H??d)},cancel:(H="")=>ut(H,1),error:(H="")=>ut(H,2),clear:()=>ut("",0,!0),get isCancelled(){return b}}},Fm={light:D("\u2500","-"),heavy:D("\u2501","="),block:D("\u2588","#")};var Mc=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Enter:")} confirm`],Jt=(e,t)=>e.includes(`
45
+ `)},info:(e,t)=>{v.message(e,{...t,symbol:w("blue",Il)})},success:(e,t)=>{v.message(e,{...t,symbol:w("green",Al)})},step:(e,t)=>{v.message(e,{...t,symbol:w("green",mr)})},warn:(e,t)=>{v.message(e,{...t,symbol:w("yellow",Ol)})},warning:(e,t)=>{v.warn(e,t)},error:(e,t)=>{v.message(e,{...t,symbol:w("red",_l)})}};var yr=(e="",t)=>{let r=t?.output??process.stdout,s=t?.withGuide??Q.withGuide?`${w("gray",Sl)} `:"";r.write(`${s}${e}
46
+ `)},wr=(e="",t)=>{let r=t?.output??process.stdout,s=t?.withGuide??Q.withGuide?`${w("gray",x)}
47
+ ${w("gray",Ne)} `:"";r.write(`${s}${e}
48
+
49
+ `)};var Ll=(e)=>e,Dl=(e,t,r)=>{let s={hard:!0,trim:!1},n=Re(e,t,s).split(`
50
+ `),i=n.reduce((c,l)=>Math.max(se(l),c),0),o=n.map(r).reduce((c,l)=>Math.max(se(l),c),0),a=t-(o-i);return Re(e,a,s)},G=(e="",t="",r)=>{let s=r?.output??ue.stdout,n=r?.withGuide??Q.withGuide,i=r?.format??Ll,o=["",...Dl(e,Et(s)-6,i).split(`
51
+ `).map(i),""],a=se(t),c=Math.max(o.reduce((h,f)=>{let m=se(f);return m>h?m:h},0),a)+2,l=o.map((h)=>`${w("gray",x)} ${h}${" ".repeat(c-se(h))}${w("gray",x)}`).join(`
52
+ `),d=n?`${w("gray",x)}
53
+ `:"",g=n?xl:El;s.write(`${d}${w("green",mr)} ${w("reset",t)} ${w("gray",Ki.repeat(Math.max(c-a-1,1))+kl)}
54
+ ${l}
55
+ ${w("gray",g+Ki.repeat(c+2)+Tl)}
56
+ `)};var Nl=(e)=>w("magenta",e),ye=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:s,errorMessage:n,frames:i=Ms?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Ms?80:120,signal:a,...c}={})=>{let l=Pl(),d,g,h=!1,f=!1,m="",y,R=performance.now(),S=Et(r),C=c?.styleFrame??Nl,q=(H)=>{let le=H>1?n??Q.messages.error:s??Q.messages.cancel;f=H===1,h&&(xt(le,H),f&&typeof t=="function"&&t())},L=()=>q(2),T=()=>q(1),K=()=>{process.on("uncaughtExceptionMonitor",L),process.on("unhandledRejection",L),process.on("SIGINT",T),process.on("SIGTERM",T),process.on("exit",q),a&&a.addEventListener("abort",T)},V=()=>{process.removeListener("uncaughtExceptionMonitor",L),process.removeListener("unhandledRejection",L),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T),process.removeListener("exit",q),a&&a.removeEventListener("abort",T)},U=()=>{if(y===void 0)return;l&&r.write(`
57
+ `);let H=Re(y,S,{hard:!0,trim:!1}).split(`
58
+ `);H.length>1&&r.write(Ot.cursor.up(H.length-1)),r.write(Ot.cursor.to(0)),r.write(Ot.erase.down())},W=(H)=>H.replace(/\.+$/,""),Pe=(H)=>{let le=(performance.now()-H)/1000,Se=Math.floor(le/60),Ce=Math.floor(le%60);return Se>0?`[${Se}m ${Ce}s]`:`[${Ce}s]`},re=c.withGuide??Q.withGuide,cr=(H="")=>{h=!0,d=Hi({output:r}),m=W(H),R=performance.now(),re&&r.write(`${w("gray",x)}
59
+ `);let le=0,Se=0;K(),g=setInterval(()=>{if(l&&m===y)return;U(),y=m;let Ce=C(i[le]),lr;if(l)lr=`${Ce} ${m}...`;else if(e==="timer")lr=`${Ce} ${m} ${Pe(R)}`;else{let Wc=".".repeat(Math.floor(Se)).slice(0,3);lr=`${Ce} ${m}${Wc}`}let qc=Re(lr,S,{hard:!0,trim:!1});r.write(qc),le=le+1<i.length?le+1:0,Se=Se<4?Se+0.125:0},o)},xt=(H="",le=0,Se=!1)=>{if(!h)return;h=!1,clearInterval(g),U();let Ce=le===0?w("green",mr):le===1?w("red",Xi):w("red",Zi);m=H??m,Se||(e==="timer"?r.write(`${Ce} ${m} ${Pe(R)}
60
+ `):r.write(`${Ce} ${m}
61
+ `)),V(),d()};return{start:cr,stop:(H="")=>xt(H,0),message:(H="")=>{m=W(H??m)},cancel:(H="")=>xt(H,1),error:(H="")=>xt(H,2),clear:()=>xt("",0,!0),get isCancelled(){return f}}},Om={light:M("\u2500","-"),heavy:M("\u2501","="),block:M("\u2588","#")};var jl=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Enter:")} confirm`],dr=(e,t)=>e.includes(`
68
62
  `)?e.split(`
69
63
  `).map((r)=>t(r)).join(`
70
- `):t(e),bs=(e)=>{let t=(n,i)=>{if(n===void 0)return"";let s=n.label??String(n.value);switch(i){case"disabled":return`${h("gray",zt)} ${Jt(s,(a)=>h("gray",a))}${n.hint?` ${h("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${Jt(s,(a)=>h("dim",a))}`;case"active":return`${h("green",on)} ${s}${n.hint?` ${h("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${Jt(s,(a)=>h(["strikethrough","dim"],a))}`;default:return`${h("dim",zt)} ${Jt(s,(a)=>h("dim",a))}`}},r=e.showInstructions??!0;return new cs({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??K.withGuide,i=`${Yt(this.state)} `,s=`${fs(this.state)} `,a=Ae(e.output,e.message,s,i),o=`${n?`${h("gray",C)}
71
- `:""}${a}
72
- `;switch(this.state){case"submit":{let c=n?`${h("gray",C)} `:"",p=Ae(e.output,t(this.options[this.cursor],"selected"),c);return`${o}${p}`}case"cancel":{let c=n?`${h("gray",C)} `:"",p=Ae(e.output,t(this.options[this.cursor],"cancelled"),c);return`${o}${p}${n?`
73
- ${h("gray",C)}`:""}`}default:{let c=n?`${h("cyan",C)} `:"",p=o.split(`
74
- `).length,m=r?hs(Mc,n):n?[h("cyan",xe)]:[],u=m.join(`
75
- `),f=m.length+1;return`${o}${c}${cn({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:c.length,rowPadding:p+f,style:(b,d)=>t(b,b.disabled?"disabled":d?"active":"inactive")}).join(`
64
+ `):t(e),so=(e)=>{let t=(s,n)=>{if(s===void 0)return"";let i=s.label??String(s.value);switch(n){case"disabled":return`${w("gray",gr)} ${dr(i,(o)=>w("gray",o))}${s.hint?` ${w("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${dr(i,(o)=>w("dim",o))}`;case"active":return`${w("green",Ls)} ${i}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${dr(i,(o)=>w(["strikethrough","dim"],o))}`;default:return`${w("dim",gr)} ${dr(i,(o)=>w("dim",o))}`}},r=e.showInstructions??!0;return new Wi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??Q.withGuide,n=`${hr(this.state)} `,i=`${Qi(this.state)} `,o=De(e.output,e.message,i,n),a=`${s?`${w("gray",x)}
65
+ `:""}${o}
66
+ `;switch(this.state){case"submit":{let c=s?`${w("gray",x)} `:"",l=De(e.output,t(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=s?`${w("gray",x)} `:"",l=De(e.output,t(this.options[this.cursor],"cancelled"),c);return`${a}${l}${s?`
67
+ ${w("gray",x)}`:""}`}default:{let c=s?`${w("cyan",x)} `:"",l=a.split(`
68
+ `).length,d=r?eo(jl,s):s?[w("cyan",Ne)]:[],g=d.join(`
69
+ `),h=d.length+1;return`${a}${c}${Ds({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+h,style:(f,m)=>t(f,f.disabled?"disabled":m?"active":"inactive")}).join(`
76
70
  ${c}`)}
77
- ${u}
78
- `}}}}).prompt()};var jm=`${h("gray",C)} `;var Ps=(e)=>new sn({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??K.withGuide,r=`${`${t?`${h("gray",C)}
79
- `:""}${Yt(this.state)} `}${e.message}
80
- `,n=e.placeholder&&e.placeholder.length>0?h("inverse",e.placeholder[0])+h("dim",e.placeholder.slice(1)):h(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:n,s=this.value??"";switch(this.state){case"error":{let a=this.error?` ${h("yellow",this.error)}`:"",o=t?`${h("yellow",C)} `:"",c=t?h("yellow",xe):"";return`${r.trim()}
81
- ${o}${i}
82
- ${c}${a}
83
- `}case"submit":{let a=s?` ${h("dim",s)}`:"",o=t?h("gray",C):"";return`${r}${o}${a}`}case"cancel":{let a=s?` ${h(["strikethrough","dim"],s)}`:"",o=t?h("gray",C):"";return`${r}${o}${a}${s.trim()?`
84
- ${o}`:""}`}default:{let a=t?`${h("cyan",C)} `:"",o=t?h("cyan",xe):"";return`${r}${a}${i}
85
- ${o}
86
- `}}}}).prompt();var Fc=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),ks=["black","blue","cyan","gray","green","magenta","red","white","yellow"],jc=["bold","dim","italic","underline","reset"],$s={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Nc={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"},Tc={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"},vs={"\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 er(e){return(t)=>Fc?`${e}${t}${$s.reset}`:t}function Bc(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32&&r!==27)return!1}return!0}function Rs({bright:e=!1,color:t}){let r=Bun.color(t,"ansi"),n=typeof r==="string"&&r.length>0&&Bc(r)?r:Nc[t];if(!n)return"";return e&&n in vs?vs[n]:n}var Uc=ks.reduce((e,t)=>{let r=Rs({color:t});if(r)e[t]=er(r);let n=Rs({bright:!0,color:t});if(n)e[`${t}Bright`]=er(n);return e},{}),Gc=jc.reduce((e,t)=>{return e[t]=er($s[t]),e},{}),qc=ks.reduce((e,t)=>{let r=Tc[t];if(r){let n=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[n]=er(r)}return e},{}),l={...Uc,...Gc,...qc};function tr(e){if(dt(e))throw new me;return e}function _c(e){return e.map((t)=>t.key?`${l.bold(t.key)} ${l.dim(t.text)}`:l.dim(t.text)).join(l.dim(" \xB7 "))}function rr(e){y.info(_c(e))}var nr={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 T(e){return rr(nr.confirm),tr(await ws(e))}async function ie(e){return rr(nr.text),tr(await Ps(e))}async function Ge(e){return rr(nr.select),tr(await bs({showInstructions:!1,...e}))}async function ke(e){return rr(nr.multiselect),tr(await ys({showInstructions:!1,...e}))}function ln(e){return e==null?[]:Array.isArray(e)?e:[e]}function Vc(e,t,r,n){var i,s=e[t],a=~n.string.indexOf(t)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~n.boolean.indexOf(t)?r==="false"?!1:r==="true"||(e._.push((i=+r,i*0===0)?i:r),!!r):(i=+r,i*0===0)?i:r;e[t]=s==null?a:Array.isArray(s)?s.concat(a):[s,a]}function ir(e,t){e=e||[],t=t||{};var r,n,i,s,a,o={_:[]},c=0,p=0,m=0,u=e.length;let f=t.alias!==void 0,b=t.unknown!==void 0,d=t.default!==void 0;if(t.alias=t.alias||{},t.string=ln(t.string),t.boolean=ln(t.boolean),f)for(r in t.alias){n=t.alias[r]=ln(t.alias[r]);for(c=0;c<n.length;c++)(t.alias[n[c]]=n.concat(r)).splice(c,1)}for(c=t.boolean.length;c-- >0;){n=t.alias[t.boolean[c]]||[];for(p=n.length;p-- >0;)t.boolean.push(n[p])}for(c=t.string.length;c-- >0;){n=t.alias[t.string[c]]||[];for(p=n.length;p-- >0;)t.string.push(n[p])}if(d){for(r in t.default)if(s=typeof t.default[r],n=t.alias[r]=t.alias[r]||[],t[s]!==void 0){t[s].push(r);for(c=0;c<n.length;c++)t[s].push(n[c])}}let P=b?Object.keys(t.alias):[];for(c=0;c<u;c++){if(i=e[c],i==="--"){o._=o._.concat(e.slice(++c));break}for(p=0;p<i.length;p++)if(i.charCodeAt(p)!==45)break;if(p===0)o._.push(i);else if(i.substring(p,p+3)==="no-"){if(s=i.substring(p+3),b&&!~P.indexOf(s))return t.unknown(i);o[s]=!1}else{for(m=p+1;m<i.length;m++)if(i.charCodeAt(m)===61)break;s=i.substring(p,m),a=i.substring(++m)||(c+1===u||(""+e[c+1]).charCodeAt(0)===45||e[++c]),n=p===2?[s]:s;for(m=0;m<n.length;m++){if(s=n[m],b&&!~P.indexOf(s))return t.unknown("-".repeat(p)+s);Vc(o,s,m+1<n.length||a,t)}}}if(d){for(r in t.default)if(o[r]===void 0)o[r]=t.default[r]}if(f)for(r in o){n=t.alias[r]||[];while(n.length>0)o[n.shift()]=o[r]}return o}function sr(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Cs(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[r,n]of Object.entries(e)){if(n.type==="boolean")t.boolean.push(r);else t.string.push(r);if(n.alias)t.alias[n.alias]=r;let i=sr(r);if(i!==r)t.alias[i]=r;if(n.default!==void 0)t.default[r]=n.default}return t}function Ss(e,t){for(let[n,i]of Object.entries(e))if(Array.isArray(i))throw new g(`--${sr(n)} can only be provided once`);let r={...e};for(let[n,i]of Object.entries(t)){if(i.type!=="number")continue;let s=e[n];if(s===void 0||typeof s==="boolean")continue;let a=Number(s);if(Number.isNaN(a))throw Error(`Invalid number for --${n}: "${s}"`);r[n]=a}return r}function Es(e,t){let r=Cs(t),n=ir(e,r),i=n._[0],s=i?e.indexOf(i):-1,{_:a,...o}=n,c=Ss(o,t);return{command:i,flags:c,restArgs:s>=0?e.slice(s+1):[]}}function pn(e,t={}){let r=Cs(t),n=ir(e,r),{_:i,...s}=n;return{args:Ss(s,t),rawPositionals:i}}function gn(e,t){let r={},n=Object.entries(t);for(let[i,[s,a]]of n.entries())r[s]=a.variadic?e.slice(i):e[i];return r}function Is(e,t){for(let[r,n]of Object.entries(t)){if(!n.required)continue;let i=e[r];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${r}${n.variadic?"...":""}>`}return null}var Wc=(e)=>e,k={arg:l.magenta,cmd:l.cyan,default:l.bold,desc:Wc,flag:l.green,header:(e)=>l.bold(l.yellow(e)),hint:l.dim,name:(e)=>l.bold(l.cyan(e)),placeholder:l.magenta};class mn{metadata;commands;globalArgs;constructor(e,t,r){this.metadata=e;this.commands=t;this.globalArgs=r}version(){return`${k.name(this.metadata.name)} ${k.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:r,version:n,description:i}=this.metadata;if(e.push(`${k.name(t)}${n?` ${k.hint(`v${n}`)}`:""}`),i)e.push(k.desc(i));e.push(""),e.push(k.header("Usage:")),e.push(` ${k.cmd(r)} ${k.placeholder("[command]")} ${k.placeholder("[options]")}`),e.push(""),e.push(k.header("Commands:"));let s=Array.from(this.commands.values()).map((a)=>[` ${k.cmd(a.name)}`,k.desc(a.description)]);return e.push(...this.formatColumns(s)),e.push(""),e.push(k.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(`${k.hint("Run")} ${k.cmd(`${r} <command> --help`)} ${k.hint("for command details.")}`),e.join(`
87
- `).trimEnd()}command(e,t){let r=[],n=t??this.metadata.bin,i=`${n} ${e.name}`,s=`${k.cmd(n)} ${k.cmd(e.name)}`;r.push(k.name(i)),r.push(k.desc(e.description)),r.push(""),r.push(k.header("Usage:"));let a=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())r.push(` ${s} ${k.placeholder("<subcommand>")} ${k.placeholder("[options]")}`);else{let p=[s];if(a)p.push(a);p.push(k.placeholder("[options]")),r.push(` ${p.join(" ")}`)}if(e.prompts&&Object.keys(e.positionals).length>0)r.push(` ${k.hint("Omit positional arguments to run interactively.")}`);if(r.push(""),e.hasSubcommands()){r.push(k.header("Subcommands:"));let p=e.getSubcommands().map((m)=>[` ${k.cmd(m.name)}`,k.desc(m.description)]);r.push(...this.formatColumns(p)),r.push("")}if(Object.entries(e.positionals).length>0)r.push(k.header("Arguments:")),r.push(...this.formatPositionalDefs(e.positionals)),r.push("");if(Object.entries(e.args).length>0)r.push(k.header("Options:")),r.push(...this.formatArgDefs(e.args));return r.join(`
88
- `).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,r])=>{let n=r.variadic?`${t}...`:t;return r.required?k.arg(`<${n}>`):k.arg(`[${n}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([r,n])=>{let i=n.variadic?`${r}...`:r,s=k.desc(n.description??""),a=n.required?"":k.hint(" (optional)");return[` ${k.arg(i)}`,`${s}${a}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[r,n]of Object.entries(e)){let i=n.alias?`${k.flag(`-${n.alias}`)}, `:" ",s=n.type==="boolean"?"":` ${k.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,a=`${i}${k.flag(`--${sr(r)}`)}${s}`,o=k.desc(n.description??""),c=this.formatDefault(n),p=c===void 0?"":` (default: ${k.default(c)})`;t.push([` ${a}`,`${o}${p}`])}return this.formatColumns(t)}formatDefault(e){if(typeof e.displayDefault==="string")return e.displayDefault;if(e.default===void 0)return;if(e.type==="boolean"&&e.default===!1)return;if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([n])=>this.stripAnsi(n).length)),r=2;return e.map(([n,i])=>{let s=t-this.stripAnsi(n).length+r;return`${n}${" ".repeat(s)}${i}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var $e=new Uint32Array(65536),Jc=(e,t)=>{let r=e.length,n=t.length,i=1<<r-1,s=-1,a=0,o=r,c=r;while(c--)$e[e.charCodeAt(c)]|=1<<c;for(c=0;c<n;c++){let p=$e[t.charCodeAt(c)],m=p|a;if(p|=(p&s)+s^s,a|=~(p|s),s&=p,a&i)o++;if(s&i)o--;a=a<<1|1,s=s<<1|~(m|a),a&=m}c=r;while(c--)$e[e.charCodeAt(c)]=0;return o},zc=(e,t)=>{let r=t.length,n=e.length,i=[],s=[],a=Math.ceil(r/32),o=Math.ceil(n/32);for(let d=0;d<a;d++)s[d]=-1,i[d]=0;let c=0;for(;c<o-1;c++){let d=0,P=-1,S=c*32,$=Math.min(32,n)+S;for(let R=S;R<$;R++)$e[e.charCodeAt(R)]|=1<<R;for(let R=0;R<r;R++){let _=$e[t.charCodeAt(R)],F=s[R/32|0]>>>R&1,E=i[R/32|0]>>>R&1,W=_|d,G=((_|E)&P)+P^P|_|E,U=d|~(G|P),V=P&G;if(U>>>31^F)s[R/32|0]^=1<<R;if(V>>>31^E)i[R/32|0]^=1<<R;U=U<<1|F,V=V<<1|E,P=V|~(W|U),d=U&W}for(let R=S;R<$;R++)$e[e.charCodeAt(R)]=0}let p=0,m=-1,u=c*32,f=Math.min(32,n-u)+u;for(let d=u;d<f;d++)$e[e.charCodeAt(d)]|=1<<d;let b=n;for(let d=0;d<r;d++){let P=$e[t.charCodeAt(d)],S=s[d/32|0]>>>d&1,$=i[d/32|0]>>>d&1,R=P|p,_=((P|$)&m)+m^m|P|$,F=p|~(_|m),E=m&_;if(b+=F>>>n-1&1,b-=E>>>n-1&1,F>>>31^S)s[d/32|0]^=1<<d;if(E>>>31^$)i[d/32|0]^=1<<d;F=F<<1|S,E=E<<1|$,m=E|~(R|F),p=F&R}for(let d=u;d<f;d++)$e[e.charCodeAt(d)]=0;return b},Kc=(e,t)=>{if(e.length<t.length){let r=t;t=e,e=r}if(t.length===0)return e.length;if(e.length<=32)return Jc(e,t);return zc(e,t)},Ls=(e,t)=>{let r=1/0,n=0;for(let i=0;i<t.length;i++){let s=Kc(e,t[i]);if(s<r)r=s,n=i}return t[n]};function ar(e,t,r,n){let i=Ls(t,r);if(console.error(l.red(`Unknown ${e}: ${t}`)),i)console.error(l.yellow(`Did you mean "${i}"?`));console.error(`
89
- Run "${n} --help" for usage.`),process.exit(1)}function qe(e,t){let r=(i)=>i&&typeof i==="object";if(!r(e)||!r(t))return t;let n={...e};for(let i of Object.keys(t)){let s=n[i],a=t[i];if(Array.isArray(s)&&Array.isArray(a))n[i]=[...a];else if(r(s)&&r(a))n[i]=qe(s,a);else n[i]=a}return n}var un="__exit__";class Xe{command;env;prefix;options;constructor(e,t,r,n={}){this.command=e;this.env=t;this.prefix=r;this.options=n}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...r]=e;if(t&&this.command.hasSubcommands()){let n=this.command.getSubcommand(t);if(n){await this.handleSubcommandRoute(n,r);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((r)=>r.name);ar("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new Xe(e,this.env,this.commandPath).route(t,!1)}async executeCommand(e){if(this.isHelpRequest(e)){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}=pn(e,this.command.args),i=gn(n,this.command.positionals),s=Is(i,this.command.positionals);if(s)y.error(s),console.error(`
90
- Run "${this.commandPath} --help" for usage.`),process.exit(1);let a=this.command.prompts&&n.length===0,o=this.buildContext(i,r,a);await this.command.execute(o)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=pn([],this.command.args),t=gn([],this.command.positionals),r=this.buildContext(t,e,!0);await this.command.execute?.(r)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===un){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof me){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Xe(e,this.env,this.commandPath).route([],!0)}catch(t){if(t instanceof me)return;if(t instanceof g){if(y.warn(l.yellow(t.message)),t.hint)y.info(l.dim(t.hint));return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:un}:{hint:"Return to previous menu",label:"Back",value:un};return Ge({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((r)=>({hint:r.description,label:r.name,value:r.name})),t]})}buildContext(e,t,r){return{...this.env,args:t,interactive:r,positionals:e}}isHelpRequest(e){let t=e.indexOf("--"),r=t<0?e:e.slice(0,t);return r.includes("--help")||r.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var Yc={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"},Zc=4;class dn{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(e,t){this.configManager=e,this.metadata={...Yc,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new mn({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){try{let{command:t,flags:r,restArgs:n}=Es(e,this.globalArgs);if(r.version&&!t)return console.log(this.help.version());if(r.interactive&&!t)return this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(n[0]);await this.runDirect(t,n,!!r.help)}catch(t){this.handleError(t)}}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},r=new Xe(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await r.route([],!0)}catch(n){this.handleError(n)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){Qt(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,r){let n=this.commands.get(e);if(!n)return this.handleUnknownCommand(e);let i=t.length>0&&!t[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 Xe(n,s,this.bin).route(t,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";Xt(`${l.bgCyan(l.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());ar("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof me)process.exit(0);if(e instanceof g){if(y.warn(l.yellow(e.message)),e.hint)y.info(l.dim(e.hint));this.logErrorCauses(e),process.exit(e.exitCode)}if(e instanceof Error)y.error(l.red(e.message)),this.logErrorCauses(e),process.exit(1);console.error(l.red("Error:"),e),process.exit(1)}logErrorCauses(e,t=0){if(t>=Zc)return;let r=[...e instanceof AggregateError?e.errors:[],...e.cause!==void 0?[e.cause]:[]];for(let n of r){if(y.info(l.dim(`caused by: ${n instanceof Error?n.message:String(n)}`)),n instanceof g&&n.hint)y.info(l.dim(` ${n.hint}`));if(n instanceof Error)this.logErrorCauses(n,t+1)}}}class yt{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function B(e){return e}function pe(e){return e}import Qe from"fs";import As from"path";class fn{config;configPath;defaultConfig;constructor(e,t){this.configPath=As.resolve(e),this.defaultConfig=t,this.config=this.loadConfig()}get path(){return this.configPath}get(e){return this.config[e]}set(e,t){this.config[e]=t,this.save()}delete(e){delete this.config[e],this.save()}exists(){return Qe.existsSync(this.configPath)}getAll(){return qe({},this.config)}save(e){if(e)this.config={...e};this.ensureDirectoryExists();try{Qe.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(t){throw Error(`Failed to save config to ${this.configPath}`,{cause:t})}}ensureDirectoryExists(){let e=As.dirname(this.configPath);if(!Qe.existsSync(e))try{Qe.mkdirSync(e,{recursive:!0})}catch(t){throw Error(`Failed to create config directory at ${e}`,{cause:t})}}loadConfig(){if(!Qe.existsSync(this.configPath))return{...this.defaultConfig};try{let e=Qe.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return qe({...this.defaultConfig},t)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var xs="0.9.0";class j extends yt{}import{existsSync as hl}from"fs";import{mkdir as wl,writeFile as yl}from"fs/promises";import{dirname as bl}from"path";class Oe{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class or extends Oe{name="bitbucket";notImplemented(){throw new g("Bitbucket is not supported yet","Bitbucket support is coming soon")}async ensureAvailable(){this.notImplemented()}async getDefaultBranch(){this.notImplemented()}async findPr(e){this.notImplemented()}async createPr(e){this.notImplemented()}async updatePr(e,t){this.notImplemented()}async getPr(e){this.notImplemented()}async getPrFromCurrentBranch(){this.notImplemented()}async getPrCommits(e){this.notImplemented()}async getPrFiles(e){this.notImplemented()}async ensureLabelExists(e,t){this.notImplemented()}async getRelease(e){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var N="sis",hn="\uD83E\uDEA8",Me="other",et={build:23,chore:25,ci:24,docs:20,feat:10,"feat!":0,fix:11,"fix!":1,perf:12,refactor:13,style:21,test:22,["other"]:100},tt=50,De=".sisyphus",Os="stones",Ms="released",cr=7,Ds="unknown",bt="unknown",Fs="0.0.0",lr="latest",Ce="main",js=4,Ns=8,rt="config.json";var nt={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!0,filename:"CHANGELOG.md",generate:!0,packageHeader:"{emoji} {version} ({date})",root:!1,rootHeader:"{date} - {packages}",sections:{breaking:"Breaking changes",build:"Build",chore:"Chores",ci:"CI",dependencies:"Dependency updates",docs:"Documentation",feat:"Features",fix:"Bug fixes",other:"Other changes",perf:"Performance",refactor:"Refactoring",style:"Styling",test:"Tests"}},commit:{author:"r5n-bot",email:"r5n-bot@users.noreply.github.com",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},ignore:[],lastStone:{commit:"",date:""},plugins:[],pr:{labelMapping:{breaking:"major","breaking-change":"major",bug:"patch",chore:"patch",docs:"patch",enhancement:"minor",feature:"minor",fix:"patch"},skip:{authors:["r5n-bot[bot]"],labels:["sisyphus-release","skip-stone"],titlePatterns:["^chore\\(release\\):"]}},release:{createRelease:!1,npm:!1,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};var Qc=200,el=404,tl=10;function rl(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.tag_name==="string"&&typeof t.draft==="boolean"&&(typeof t.name==="string"||t.name===null)&&(typeof t.body==="string"||t.body===null)}class pr extends Oe{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new g("GitHub CLI (gh) is not installed","Install from https://cli.github.com and run: gh auth login")}try{await Bun.$`gh auth status`.quiet()}catch{throw new g("GitHub CLI (gh) is not authenticated","Run: gh auth login")}}async getDefaultBranch(){try{return(await Bun.$`gh repo view --json defaultBranchRef --jq .defaultBranchRef.name`.quiet()).stdout.toString().trim()||Ce}catch{return Ce}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let r=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),n=JSON.parse(r.stdout.toString());if(!n[0])return null;return this.mapPrResponse(n[0])}catch{return null}}async createPr(e){let t=await Bun.$`gh api ${this.apiPath}/pulls --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`,n=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let i=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await Bun.$`gh api ${this.apiPath}/issues/${n}/labels --method POST ${i}`}return this.getPr(n)}async updatePr(e,t){let r=[];if(t.title)r.push("--title",t.title);if(t.body)r.push("--body",t.body);await Bun.$`gh pr edit ${e} ${r}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),r=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(r)}catch{throw new g(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access")}}async getPrFromCurrentBranch(){try{let e=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),t=JSON.parse(e.stdout.toString());return this.mapPrResponse(t)}catch{throw new g("No PR found for current branch","Make sure you have an open PR or provide a URL with --url")}}async getPrCommits(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/commits --jq '.[].sha'`.quiet()).stdout.toString().trim().split(`
71
+ ${g}
72
+ `}}}}).prompt()};var _m=`${w("gray",x)} `;var no=(e)=>new _s({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??Q.withGuide,r=`${`${t?`${w("gray",x)}
73
+ `:""}${hr(this.state)} `}${e.message}
74
+ `,s=e.placeholder&&e.placeholder.length>0?w("inverse",e.placeholder[0])+w("dim",e.placeholder.slice(1)):w(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:s,i=this.value??"";switch(this.state){case"error":{let o=this.error?` ${w("yellow",this.error)}`:"",a=t?`${w("yellow",x)} `:"",c=t?w("yellow",Ne):"";return`${r.trim()}
75
+ ${a}${n}
76
+ ${c}${o}
77
+ `}case"submit":{let o=i?` ${w("dim",i)}`:"",a=t?w("gray",x):"";return`${r}${a}${o}`}case"cancel":{let o=i?` ${w(["strikethrough","dim"],i)}`:"",a=t?w("gray",x):"";return`${r}${a}${o}${i.trim()?`
78
+ ${a}`:""}`}default:{let o=t?`${w("cyan",x)} `:"",a=t?w("cyan",Ne):"";return`${r}${o}${n}
79
+ ${a}
80
+ `}}}}).prompt();var Fl=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),ao=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Ul=["bold","dim","italic","underline","reset"],co={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Vl={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"},Gl={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},io={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function br(e){return(t)=>Fl?`${e}${t}${co.reset}`:t}function Hl(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32&&r!==27)return!1}return!0}function oo({bright:e=!1,color:t}){let r=Bun.color(t,"ansi"),s=typeof r==="string"&&r.length>0&&Hl(r)?r:Vl[t];if(!s)return"";return e&&s in io?io[s]:s}var ql=ao.reduce((e,t)=>{let r=oo({color:t});if(r)e[t]=br(r);let s=oo({bright:!0,color:t});if(s)e[`${t}Bright`]=br(s);return e},{}),Wl=Ul.reduce((e,t)=>(e[t]=br(co[t]),e),{}),Jl=ao.reduce((e,t)=>{let r=Gl[t];if(r){let s=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[s]=br(r)}return e},{}),p={...ql,...Wl,...Jl};function vr(e){if(Tt(e))throw new fe;return e}function Kl(e){return e.map((t)=>t.key?`${p.bold(t.key)} ${p.dim(t.text)}`:p.dim(t.text)).join(p.dim(" \xB7 "))}function $r(e){v.info(Kl(e))}var Pr={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 j(e){return $r(Pr.confirm),vr(await to(e))}async function ce(e){return $r(Pr.text),vr(await no(e))}async function Ke(e){return $r(Pr.select),vr(await so({showInstructions:!1,...e}))}async function ke(e){return $r(Pr.multiselect),vr(await ro({showInstructions:!1,...e}))}var Yl=4;function ot(e,t=0){if(t>=Yl)return;let r=[...e instanceof AggregateError?e.errors:[],...e.cause!==void 0?[e.cause]:[]];for(let s of r){if(v.info(p.dim(`caused by: ${s instanceof Error?s.message:String(s)}`)),s instanceof u&&s.hint)v.info(p.dim(` ${s.hint}`));if(s instanceof Error)ot(s,t+1)}}function Ns(e){return e==null?[]:Array.isArray(e)?e:[e]}function Xl(e,t,r,s){var n,i=e[t],o=~s.string.indexOf(t)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~s.boolean.indexOf(t)?r==="false"?!1:r==="true"||(e._.push((n=+r,n*0===0)?n:r),!!r):(n=+r,n*0===0)?n:r;e[t]=i==null?o:Array.isArray(i)?i.concat(o):[i,o]}function _t(e,t){e=e||[],t=t||{};var r,s,n,i,o,a={_:[]},c=0,l=0,d=0,g=e.length;let h=t.alias!==void 0,f=t.unknown!==void 0,m=t.default!==void 0;if(t.alias=t.alias||{},t.string=Ns(t.string),t.boolean=Ns(t.boolean),h)for(r in t.alias){s=t.alias[r]=Ns(t.alias[r]);for(c=0;c<s.length;c++)(t.alias[s[c]]=s.concat(r)).splice(c,1)}for(c=t.boolean.length;c-- >0;){s=t.alias[t.boolean[c]]||[];for(l=s.length;l-- >0;)t.boolean.push(s[l])}for(c=t.string.length;c-- >0;){s=t.alias[t.string[c]]||[];for(l=s.length;l-- >0;)t.string.push(s[l])}if(m){for(r in t.default)if(i=typeof t.default[r],s=t.alias[r]=t.alias[r]||[],t[i]!==void 0){t[i].push(r);for(c=0;c<s.length;c++)t[i].push(s[c])}}let y=f?Object.keys(t.alias):[];for(c=0;c<g;c++){if(n=e[c],n==="--"){a._=a._.concat(e.slice(++c));break}for(l=0;l<n.length;l++)if(n.charCodeAt(l)!==45)break;if(l===0)a._.push(n);else if(n.substring(l,l+3)==="no-"){if(i=n.substring(l+3),f&&!~y.indexOf(i))return t.unknown(n);a[i]=!1}else{for(d=l+1;d<n.length;d++)if(n.charCodeAt(d)===61)break;i=n.substring(l,d),o=n.substring(++d)||(c+1===g||(""+e[c+1]).charCodeAt(0)===45||e[++c]),s=l===2?[i]:i;for(d=0;d<s.length;d++){if(i=s[d],f&&!~y.indexOf(i))return t.unknown("-".repeat(l)+i);Xl(a,i,d+1<s.length||o,t)}}}if(m){for(r in t.default)if(a[r]===void 0)a[r]=t.default[r]}if(h)for(r in a){s=t.alias[r]||[];while(s.length>0)a[s.shift()]=a[r]}return a}var Zl=1;function at(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Bs(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[r,s]of Object.entries(e)){if(s.type==="boolean")t.boolean.push(r);else t.string.push(r);if(s.alias)t.alias[s.alias]=r;let n=at(r);if(n!==r)t.alias[n]=r;if(s.default!==void 0)t.default[r]=s.default}return t}function js(e,t){if(e in t)return`--${at(e)}`;let r=Object.entries(t).find(([,s])=>s.alias===e)?.[0];if(r)return`--${at(r)}`;return e.length===Zl?`-${e}`:`--${at(e)}`}function Rr(e,t,r){let{alias:s}=Bs(t),n=Object.keys(e).find((i)=>!Object.hasOwn(t,i)&&!Object.hasOwn(s,i));if(n!==void 0)throw new u(`Unknown option: ${js(n,t)}`,r)}function lo(e,t){for(let[s,n]of Object.entries(e))if(Array.isArray(n))throw new u(`${js(s,t)} can only be provided once`);let r={...e};for(let[s,n]of Object.entries(t)){if(n.type!=="number")continue;let i=e[s];if(i===void 0)continue;let o=Number(i);if(typeof i==="boolean"||typeof i==="string"&&i.trim().length===0||!Number.isFinite(o)){let a=js(s,t);throw new u(`Invalid number for ${a}: "${i}"`,`Use ${a}=<number> with a finite numeric value`)}r[s]=o}return r}function uo(e,t){let r=Bs(t),s=_t(e,r),n=s._[0],i=n?e.indexOf(n):-1,o=_t(i>=0?e.slice(0,i):e,r),{_:a,...c}=o;Rr(c,t,"Place command options after the command name");let{_:l,...d}=s,g=Object.fromEntries(Object.entries(d).filter(([f])=>(f in t)||(f in r.alias))),h=lo(g,t);return{command:n,flags:h,restArgs:i>=0?e.slice(i+1):[]}}function Fs(e,t={}){let r=Bs(t),s=_t(Ql(e,r),r),{_:n,...i}=s;return{args:lo(i,t),rawPositionals:n}}function Ql(e,t){let r=!0;return e.map((s)=>{if(s==="--")r=!1;if(!r)return s;return s.replace(/^--(no-[^=]+)(=.*)?$/,(n,i,o)=>{let a=t.alias[i];return a&&t.boolean.includes(a)?`--${a}${o??""}`:n})})}function Us(e,t){let r={},s=Object.entries(t);for(let[n,[i,o]]of s.entries())r[i]=o.variadic?e.slice(n):e[n];return r}function po(e,t){for(let[r,s]of Object.entries(t)){if(!s.required)continue;let n=e[r];if(Array.isArray(n)?n.length===0:!n)return`Missing required argument: <${r}${s.variadic?"...":""}>`}return null}var eu=(e)=>e,k={arg:p.magenta,cmd:p.cyan,default:p.bold,desc:eu,flag:p.green,header:(e)=>p.bold(p.yellow(e)),hint:p.dim,name:(e)=>p.bold(p.cyan(e)),placeholder:p.magenta};class Vs{metadata;commands;globalArgs;constructor(e,t,r){this.metadata=e;this.commands=t;this.globalArgs=r}version(){return`${k.name(this.metadata.name)} ${k.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:r,version:s,description:n}=this.metadata;if(e.push(`${k.name(t)}${s?` ${k.hint(`v${s}`)}`:""}`),n)e.push(k.desc(n));e.push(""),e.push(k.header("Usage:")),e.push(` ${k.cmd(r)} ${k.placeholder("[command]")} ${k.placeholder("[options]")}`),e.push(""),e.push(k.header("Commands:"));let i=Array.from(this.commands.values()).map((o)=>[` ${k.cmd(o.name)}`,k.desc(o.description)]);return e.push(...this.formatColumns(i)),e.push(""),e.push(k.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(`${k.hint("Run")} ${k.cmd(`${r} <command> --help`)} ${k.hint("for command details.")}`),e.join(`
81
+ `).trimEnd()}command(e,t){let r=[],s=t??this.metadata.bin,n=`${s} ${e.name}`,i=`${k.cmd(s)} ${k.cmd(e.name)}`;r.push(k.name(n)),r.push(k.desc(e.description)),r.push(""),r.push(k.header("Usage:"));let o=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())r.push(` ${i} ${k.placeholder("<subcommand>")} ${k.placeholder("[options]")}`);else{let l=[i];if(o)l.push(o);l.push(k.placeholder("[options]")),r.push(` ${l.join(" ")}`)}if(e.prompts&&Object.keys(e.positionals).length>0)r.push(` ${k.hint("Omit positional arguments to run interactively.")}`);if(r.push(""),e.hasSubcommands()){r.push(k.header("Subcommands:"));let l=e.getSubcommands().map((d)=>[` ${k.cmd(d.name)}`,k.desc(d.description)]);r.push(...this.formatColumns(l)),r.push("")}if(Object.entries(e.positionals).length>0)r.push(k.header("Arguments:")),r.push(...this.formatPositionalDefs(e.positionals)),r.push("");if(Object.entries(e.args).length>0)r.push(k.header("Options:")),r.push(...this.formatArgDefs(e.args));return r.join(`
82
+ `).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,r])=>{let s=r.variadic?`${t}...`:t;return r.required?k.arg(`<${s}>`):k.arg(`[${s}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([r,s])=>{let n=s.variadic?`${r}...`:r,i=k.desc(s.description??""),o=s.required?"":k.hint(" (optional)");return[` ${k.arg(n)}`,`${i}${o}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[r,s]of Object.entries(e)){let n=s.alias?`${k.flag(`-${s.alias}`)}, `:" ",i=s.type==="boolean"?"":` ${k.placeholder(`<${s.type==="number"?"number":"value"}>`)}`,o=`${n}${k.flag(`--${at(r)}`)}${i}`,a=k.desc(s.description??""),c=this.formatDefault(s),l=c===void 0?"":` (default: ${k.default(c)})`;t.push([` ${o}`,`${a}${l}`])}return this.formatColumns(t)}formatDefault(e){if(typeof e.displayDefault==="string")return e.displayDefault;if(e.default===void 0)return;if(e.type==="boolean"&&e.default===!1)return;if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([s])=>this.stripAnsi(s).length)),r=2;return e.map(([s,n])=>{let i=t-this.stripAnsi(s).length+r;return`${s}${" ".repeat(i)}${n}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var xe=new Uint32Array(65536),tu=(e,t)=>{let r=e.length,s=t.length,n=1<<r-1,i=-1,o=0,a=r,c=r;while(c--)xe[e.charCodeAt(c)]|=1<<c;for(c=0;c<s;c++){let l=xe[t.charCodeAt(c)],d=l|o;if(l|=(l&i)+i^i,o|=~(l|i),i&=l,o&n)a++;if(i&n)a--;o=o<<1|1,i=i<<1|~(d|o),o&=d}c=r;while(c--)xe[e.charCodeAt(c)]=0;return a},ru=(e,t)=>{let r=t.length,s=e.length,n=[],i=[],o=Math.ceil(r/32),a=Math.ceil(s/32);for(let m=0;m<o;m++)i[m]=-1,n[m]=0;let c=0;for(;c<a-1;c++){let m=0,y=-1,R=c*32,S=Math.min(32,s)+R;for(let C=R;C<S;C++)xe[e.charCodeAt(C)]|=1<<C;for(let C=0;C<r;C++){let q=xe[t.charCodeAt(C)],L=i[C/32|0]>>>C&1,T=n[C/32|0]>>>C&1,K=q|m,V=((q|T)&y)+y^y|q|T,U=m|~(V|y),W=y&V;if(U>>>31^L)i[C/32|0]^=1<<C;if(W>>>31^T)n[C/32|0]^=1<<C;U=U<<1|L,W=W<<1|T,y=W|~(K|U),m=U&K}for(let C=R;C<S;C++)xe[e.charCodeAt(C)]=0}let l=0,d=-1,g=c*32,h=Math.min(32,s-g)+g;for(let m=g;m<h;m++)xe[e.charCodeAt(m)]|=1<<m;let f=s;for(let m=0;m<r;m++){let y=xe[t.charCodeAt(m)],R=i[m/32|0]>>>m&1,S=n[m/32|0]>>>m&1,C=y|l,q=((y|S)&d)+d^d|y|S,L=l|~(q|d),T=d&q;if(f+=L>>>s-1&1,f-=T>>>s-1&1,L>>>31^R)i[m/32|0]^=1<<m;if(T>>>31^S)n[m/32|0]^=1<<m;L=L<<1|R,T=T<<1|S,d=T|~(C|L),l=L&C}for(let m=g;m<h;m++)xe[e.charCodeAt(m)]=0;return f},su=(e,t)=>{if(e.length<t.length){let r=t;t=e,e=r}if(t.length===0)return e.length;if(e.length<=32)return tu(e,t);return ru(e,t)},go=(e,t)=>{let r=1/0,s=0;for(let n=0;n<t.length;n++){let i=su(e,t[n]);if(i<r)r=i,s=n}return t[s]};function Sr(e,t,r,s){let n=go(t,r);if(console.error(p.red(`Unknown ${e}: ${t}`)),n)console.error(p.yellow(`Did you mean "${n}"?`));console.error(`
83
+ Run "${s} --help" for usage.`),process.exit(1)}function ct(e,t){let r=(n)=>n&&typeof n==="object";if(!r(e)||!r(t))return t;let s={...e};for(let n of Object.keys(t)){let i=s[n],o=t[n];if(Array.isArray(i)&&Array.isArray(o))s[n]=[...o];else if(r(i)&&r(o))s[n]=ct(i,o);else s[n]=o}return s}var Gs="__exit__";class lt{command;env;prefix;options;constructor(e,t,r,s={}){this.command=e;this.env=t;this.prefix=r;this.options=s}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t&&process.stdout.isTTY!==!0)throw new u("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...r]=e;if(t&&this.command.hasSubcommands()){let s=this.command.getSubcommand(t);if(s){await this.handleSubcommandRoute(s,r);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((r)=>r.name);Sr("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new lt(e,this.env,this.commandPath).route(t,!1)}async executeCommand(e){if(this.isHelpRequest(e)){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:s}=Fs(e,this.command.args),n=Us(s,this.command.positionals),i=po(n,this.command.positionals);if(i)v.error(i),console.error(`
84
+ Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&s.length===0&&process.stdout.isTTY===!0,a=this.buildContext(n,r,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Fs([],this.command.args),t=Us([],this.command.positionals),r=this.buildContext(t,e,!0);await this.command.execute?.(r)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===Gs){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof fe){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new lt(e,this.env,this.commandPath).route([],!0)}catch(t){if(t instanceof fe)return;if(t instanceof u){if(v.warn(p.yellow(t.message)),t.hint)v.info(p.dim(t.hint));ot(t);return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Gs}:{hint:"Return to previous menu",label:"Back",value:Gs};return Ke({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((r)=>({hint:r.description,label:r.name,value:r.name})),t]})}buildContext(e,t,r){return{...this.env,args:t,interactive:r,positionals:e}}isHelpRequest(e){let t=e.indexOf("--"),r=t<0?e:e.slice(0,t);return r.includes("--help")||r.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var nu={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Hs{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(e,t){this.configManager=e,this.metadata={...nu,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Vs({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){try{let{command:t,flags:r,restArgs:s}=uo(e,this.globalArgs);if(r.version&&!t)return console.log(this.help.version());if(r.interactive&&!t)return await this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(s[0]);await this.runDirect(t,s,!!r.help)}catch(t){this.handleError(t)}}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},r=new lt(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await r.route([],!0)}catch(s){this.handleError(s)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){wr(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,r){let s=this.commands.get(e);if(!s)return this.handleUnknownCommand(e);let n=t.length>0&&!t[0]?.startsWith("-");if(r&&!n)return console.log(this.help.command(s));try{let i={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new lt(s,i,this.bin).route(t,!1)}catch(i){this.handleError(i)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";yr(`${p.bgCyan(p.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());Sr("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof fe)process.exit(0);if(e instanceof u){if(v.warn(p.yellow(e.message)),e.hint)v.info(p.dim(e.hint));ot(e),process.exit(e.exitCode)}if(e instanceof Error)v.error(p.red(e.message)),ot(e),process.exit(1);console.error(p.red("Error:"),e),process.exit(1)}}class Mt{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function B(e){return e}function pe(e){return e}import we from"fs";import yo from"path";var ut=(e)=>(e.map=(t)=>ut((r)=>t(e(r))),e.or=(t)=>ut((r)=>{try{return e(r)}catch(s){return t(r)}}),e),Ye=()=>"bad banditype"();var Cr=()=>ut((e)=>e),mo=(e)=>ut((t)=>e.includes(t)?t:Ye()),ho=(e)=>ut((t)=>typeof t===typeof e?t:Ye()),pt=()=>ho("");var qs=()=>ho();var Ws=(e)=>ut((t)=>t instanceof e?t:Ye()),kr=(e)=>Ws(Object).map((t)=>{let r={};for(let s in t){let n=e(t[s]);n!==void 0&&(r[s]=n)}return r});var Js=(e)=>Ws(Object).map((t)=>{let r={...t};for(let s in e){let n=e[s](t[s]);n!==void 0&&(r[s]=n)}return r}),fo=(e)=>Ws(Array).map((t)=>t.map(e));var iu=2,ou=kr(Cr());class zs{config;configPath;defaultConfig;loadError;constructor(e,t){this.configPath=yo.resolve(e),this.defaultConfig=t,this.config=this.loadConfig()}get path(){return this.configPath}get(e){return this.config[e]}set(e,t){this.config[e]=t,this.save()}delete(e){delete this.config[e],this.save()}exists(){return we.existsSync(this.configPath)}getAll(){return structuredClone(this.config)}save(e){if(this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(e)this.config={...e};this.ensureDirectoryExists();let t=this.exists()?we.realpathSync(this.configPath):this.configPath,r=`${t}.${crypto.randomUUID()}.tmp`;try{let s=this.exists()?we.statSync(this.configPath).mode:void 0;if(we.writeFileSync(r,JSON.stringify(this.config,null,iu),{flag:"wx",mode:s}),s!==void 0)we.chmodSync(r,s);we.renameSync(r,t)}catch(s){throw Error(`Failed to save config to ${this.configPath}`,{cause:s})}finally{we.rmSync(r,{force:!0})}}ensureDirectoryExists(){let e=yo.dirname(this.configPath);if(!we.existsSync(e))try{we.mkdirSync(e,{recursive:!0})}catch(t){throw Error(`Failed to create config directory at ${e}`,{cause:t})}}loadConfig(){if(!we.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let e=we.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);if(Array.isArray(t))throw Error("Config must be an object");let r=ou(t);return ct(structuredClone(this.defaultConfig),r)}catch(e){return this.loadError=e,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}}var wo="0.10.0";class D extends Mt{}import{existsSync as Pu}from"fs";import{mkdir as Ru,writeFile as Su}from"fs/promises";import{dirname as Cu}from"path";class je{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class xr extends je{name="bitbucket";notImplemented(){throw new u("Bitbucket is not supported yet","Bitbucket support is coming soon")}async ensureAvailable(){this.notImplemented()}async getDefaultBranch(){this.notImplemented()}async findPr(e){this.notImplemented()}async createPr(e){this.notImplemented()}async updatePr(e,t){this.notImplemented()}async getPr(e){this.notImplemented()}async getPrFromCurrentBranch(){this.notImplemented()}async getPrCommits(e){this.notImplemented()}async getPrFiles(e){this.notImplemented()}async ensureLabelExists(e,t){this.notImplemented()}async getRelease(e){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var N="sis",Ks="\uD83E\uDEA8",Be="other",dt={build:23,chore:25,ci:24,docs:20,feat:10,"feat!":0,fix:11,"fix!":1,perf:12,refactor:13,style:21,test:22,["other"]:100},gt=50,mt=".sisyphus",bo="stones",vo="released",Tr=7,$o="unknown",Lt="unknown",Po="0.0.0",de="latest",Ys=["bun","run","build"],Te="main",Ro=4,So=8,Er="config.json";var Fe={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!0,filename:"CHANGELOG.md",generate:!0,packageHeader:"{emoji} {version} ({date})",root:!1,rootHeader:"{date} - {packages}",sections:{breaking:"Breaking changes",build:"Build",chore:"Chores",ci:"CI",dependencies:"Dependency updates",docs:"Documentation",feat:"Features",fix:"Bug fixes",other:"Other changes",perf:"Performance",refactor:"Refactoring",style:"Styling",test:"Tests"}},commit:{author:"r5n-bot",email:"r5n-bot@users.noreply.github.com",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},dependents:{kinds:["dependencies","devDependencies","optionalDependencies","peerDependencies"],updateInternal:"always"},ignore:[],lastStone:{commit:"",date:""},plugins:[],pr:{labelMapping:{breaking:"major","breaking-change":"major",bug:"patch",chore:"patch",docs:"patch",enhancement:"minor",feature:"minor",fix:"patch"},skip:{authors:["r5n-bot[bot]"],labels:["sisyphus-release","skip-stone"],titlePatterns:["^chore\\(release\\):"]}},release:{build:{command:[...Ys],outputs:[],root:[]},createRelease:!1,npm:!1,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};var cu=200,lu=404,uu=10;function pu(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.tag_name==="string"&&typeof t.draft==="boolean"&&(typeof t.name==="string"||t.name===null)&&(typeof t.body==="string"||t.body===null)}class Ir extends je{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new u("GitHub CLI (gh) is not installed","Install from https://cli.github.com and run: gh auth login")}try{await Bun.$`gh auth status`.quiet()}catch{throw new u("GitHub CLI (gh) is not authenticated","Run: gh auth login")}}async getDefaultBranch(){try{return(await Bun.$`gh repo view --json defaultBranchRef --jq .defaultBranchRef.name`.quiet()).stdout.toString().trim()||Te}catch{return Te}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let r=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),s=JSON.parse(r.stdout.toString());if(!s[0])return null;return this.mapPrResponse(s[0])}catch{return null}}async createPr(e){let t=await Bun.$`gh api ${this.apiPath}/pulls --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`,s=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let n=e.labels.flatMap((i)=>["-f",`labels[]=${i}`]);await Bun.$`gh api ${this.apiPath}/issues/${s}/labels --method POST ${n}`}return this.getPr(s)}async updatePr(e,t){let r=[];if(t.title)r.push("--title",t.title);if(t.body)r.push("--body",t.body);await Bun.$`gh pr edit ${e} ${r}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),r=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(r)}catch{throw new u(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access")}}async getPrFromCurrentBranch(){try{let e=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),t=JSON.parse(e.stdout.toString());return this.mapPrResponse(t)}catch{throw new u("No PR found for current branch","Make sure you have an open PR or provide a URL with --url")}}async getPrCommits(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/commits --jq '.[].sha'`.quiet()).stdout.toString().trim().split(`
91
85
  `).filter(Boolean)}catch{return[]}}async getPrFiles(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/files --jq '.[].filename'`.quiet()).stdout.toString().trim().split(`
92
- `).filter(Boolean)}catch{return[]}}async ensureLabelExists(e,t){try{let r=t?.description??"",n=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --description ${r} ${n} --force`.quiet()}catch{}}async getRelease(e){let t=`${this.apiPath}/releases/tags/${encodeURIComponent(e)}`,r=await Bun.$`gh api ${t} --include`.quiet().nothrow(),n=r.stdout.toString().replaceAll(`\r
86
+ `).filter(Boolean)}catch{return[]}}async ensureLabelExists(e,t){try{let r=t?.description??"",s=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --description ${r} ${s} --force`.quiet()}catch{}}async getRelease(e){let t=`${this.apiPath}/releases/tags/${encodeURIComponent(e)}`,r=await Bun.$`gh api ${t} --include`.quiet().nothrow(),s=r.stdout.toString().replaceAll(`\r
93
87
  `,`
94
- `),[i="",...s]=n.split(`
88
+ `),[n="",...i]=s.split(`
95
89
 
96
- `),a=i.match(/^HTTP\/\S+\s+(\d{3})\b/m)?.[1],o=a?Number.parseInt(a,tl):null;if(r.exitCode!==0){if(o===el)return null;let p=o?`GitHub API returned HTTP ${o}`:`gh api failed with exit code ${r.exitCode}; check authentication and network connectivity`;throw this.releaseReadError(e,p)}if(o!==Qc)throw this.releaseReadError(e,o?`GitHub API returned HTTP ${o}`:"missing HTTP status");let c;try{c=JSON.parse(s.join(`
90
+ `),o=n.match(/^HTTP\/\S+\s+(\d{3})\b/m)?.[1],a=o?Number.parseInt(o,uu):null;if(r.exitCode!==0){if(a===lu)return null;let l=a?`GitHub API returned HTTP ${a}`:`gh api failed with exit code ${r.exitCode}; check authentication and network connectivity`;throw this.releaseReadError(e,l)}if(a!==cu)throw this.releaseReadError(e,a?`GitHub API returned HTTP ${a}`:"missing HTTP status");let c;try{c=JSON.parse(i.join(`
97
91
 
98
- `))}catch{throw this.releaseReadError(e,"response was not valid JSON")}if(!rl(c))throw this.releaseReadError(e,"response did not contain tag_name, name, and body");return{draft:c.draft,notes:c.body??"",tag:c.tag_name,title:c.name??""}}async createRelease(e){await Bun.$`gh release create ${e.tag} --repo ${`${this.owner}/${this.repo}`} --title ${e.title} --notes ${e.notes} --verify-tag`}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??bt,baseBranch:e.base?.ref??Ce,body:e.body??"",headBranch:e.head?.ref??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.merge_commit_sha,merged:e.merged,number:e.number,title:e.title,url:e.html_url}}mapPrResponse(e){return{author:e.author?.login??bt,baseBranch:e.baseRefName??Ce,body:e.body??"",headBranch:e.headRefName??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.mergeCommit?.oid??null,merged:e.state==="MERGED",number:e.number,title:e.title,url:e.url}}releaseReadError(e,t){return Error(`Failed to fetch GitHub release "${e}" from ${this.owner}/${this.repo}: ${t}`)}}var nl="https://gitlab.com/api/v4",il=404;class gr extends Oe{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=process.env.CI_API_V4_URL??nl,this.projectPath=encodeURIComponent(`${this.owner}/${this.repo}`)}async ensureAvailable(){this.authHeader=await this.resolveAuth()}async getDefaultBranch(){try{return(await this.api(`/projects/${this.projectPath}`)).default_branch||Ce}catch{return Ce}}async findPr(e){try{let t=new URLSearchParams({per_page:"1",state:"opened"});if(e.head)t.set("source_branch",e.head);if(e.label)t.set("labels",e.label);let r=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`);if(!r[0])return null;return this.mapMrResponse(r[0])}catch{return null}}async createPr(e){let t={description:e.body,source_branch:e.head,target_branch:e.base,title:e.title};if(e.labels?.length)t.labels=e.labels.join(",");let r=await this.api(`/projects/${this.projectPath}/merge_requests`,{body:JSON.stringify(t),method:"POST"});return this.mapMrResponse(r)}async updatePr(e,t){let r={};if(t.title)r.title=t.title;if(t.body)r.description=t.body;await this.api(`/projects/${this.projectPath}/merge_requests/${e}`,{body:JSON.stringify(r),method:"PUT"})}async getPr(e){try{let t=await this.api(`/projects/${this.projectPath}/merge_requests/${e}`);return this.mapMrResponse(t)}catch{throw new g(`Failed to fetch MR !${e}`,"Make sure the MR exists and you have access")}}async getPrFromCurrentBranch(){try{let t=(await Bun.$`git rev-parse --abbrev-ref HEAD`.quiet()).stdout.toString().trim(),r=new URLSearchParams({per_page:"1",source_branch:t,state:"opened"}),n=await this.api(`/projects/${this.projectPath}/merge_requests?${r}`);if(!n[0])throw Error("No MR found");return this.mapMrResponse(n[0])}catch{throw new g("No MR found for current branch","Make sure you have an open MR or provide a URL with --url")}}async getPrCommits(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/commits`)).map((r)=>r.id)}catch{return[]}}async getPrFiles(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/changes`)).changes?.map((r)=>r.new_path)??[]}catch{return[]}}async ensureLabelExists(e,t){try{let r={name:e};if(t?.description)r.description=t.description;if(t?.color)r.color=`#${t.color}`;await this.api(`/projects/${this.projectPath}/labels`,{body:JSON.stringify(r),method:"POST"})}catch{}}async getRelease(e){let t=await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,void 0,!0);if(t===void 0)return null;if(!sl(t))throw Error(`GitLab release response for ${e} did not contain tag_name, name, and description`);return{draft:!1,notes:t.description??"",tag:t.tag_name,title:t.name}}async createRelease(e){await this.api(`/projects/${this.projectPath}/releases`,{body:JSON.stringify({description:e.notes,name:e.title,tag_name:e.tag}),method:"POST"})}async deleteRelease(e){try{await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,{method:"DELETE"})}catch{}}async resolveAuth(){if(process.env.GITLAB_TOKEN)return{"PRIVATE-TOKEN":process.env.GITLAB_TOKEN};if(process.env.CI_JOB_TOKEN)return{"JOB-TOKEN":process.env.CI_JOB_TOKEN};try{let e=await Bun.$`glab auth status --show-token`.quiet(),r=(e.stdout.toString()+e.stderr.toString()).match(/Token found:\s*(\S+)/);if(r?.[1])return{Authorization:`Bearer ${r[1]}`}}catch{}throw new g("GitLab token not found","Set GITLAB_TOKEN environment variable or install glab CLI and run: glab auth login")}async api(e,t,r=!1){let n=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(r&&n.status===il)return;if(!n.ok){let i=await n.text().catch(()=>"");throw Error(`GitLab API error: ${n.status} ${n.statusText}${i?` \u2014 ${i}`:""}`)}return n.json()}mapMrResponse(e){return{author:e.author?.username??bt,baseBranch:e.target_branch??Ce,body:e.description??"",headBranch:e.source_branch??"",labels:e.labels??[],mergeCommitSha:e.merge_commit_sha,merged:e.state==="merged",number:e.iid,title:e.title,url:e.web_url}}}function sl(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.tag_name==="string"&&typeof t.name==="string"&&(typeof t.description==="string"||t.description===null)}var al=/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/,ol=/gitlab\.com\/([^/]+)\/([^/]+)\/-\/merge_requests\/(\d+)/,cl=/bitbucket\.org\/([^/]+)\/([^/]+)\/pull-requests\/(\d+)/;async function it(e){let t=e??await Ts();if(!t)throw new g("Could not detect git provider","Make sure you have a git remote configured (origin)");let r=ll(t);return await r.ensureAvailable(),r}function ll(e){switch(e.provider){case"github":return new pr(e);case"gitlab":return new gr(e);case"bitbucket":return new or(e);default:throw new g(`Unsupported provider: ${e.provider}`)}}async function Ts(){let e=await wn();if(!e)return null;return Pt(e)}async function Bs(){let e=await Ts();if(!e)throw new g("Could not detect git provider","Make sure you have a git remote configured (origin)");return e.provider}async function wn(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function Pt(e){let t=pl(e);if(!t)return null;let r=gl(t.hostname);if(!r)return null;let n=t.path.replace(/^\/+|\/+$/g,"").replace(/\.git$/,"").split("/").filter(Boolean),i=n.pop();if(!i||n.length===0)return null;if(r!=="gitlab"&&n.length!==1)return null;return{owner:n.join("/"),provider:r,repo:i}}function pl(e){try{let t=new URL(e);return{hostname:t.hostname.toLowerCase(),path:t.pathname}}catch{let t=e.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/),r=t?.[1],n=t?.[2];return r&&n?{hostname:r.toLowerCase(),path:n}:null}}function gl(e){if(e==="github.com")return"github";if(e==="gitlab.com")return"gitlab";if(e==="bitbucket.org")return"bitbucket";return null}function yn(e){let t=[[al,"github"],[ol,"gitlab"],[cl,"bitbucket"]];for(let[r,n]of t){let i=e.match(r);if(!i)continue;let[,s,a,o]=i;if(s&&a&&o)return{number:Number.parseInt(o,10),owner:s,provider:n,repo:a}}return null}import{existsSync as Us}from"fs";import{readFile as ml}from"fs/promises";import{dirname as ul,join as bn}from"path";import{fileURLToPath as dl}from"url";var mr={"create-stone":{description:"When a PR is merged, create stone and update release PR",name:"Handle PR merge (stone + release PR)"},release:{description:"When the release PR is merged, publish packages",name:"Publish release"}},fl=bn(ul(dl(import.meta.url)),"templates"),Gs={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class Pn{async generate(e){let t=[];for(let r of e){let n=await this.readTemplate(r),i=this.getOutputPath(r);t.push({content:n,path:i})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>Us(t))}async readTemplate(e){let t=bn(fl,this.provider,Gs[e]);return ml(t,"utf-8")}}class ur extends Pn{provider="github";outputDir=".github/workflows";getOutputPath(e){return bn(this.outputDir,Gs[e])}}var vt=".gitlab-ci-sisyphus.yml";class dr extends Pn{provider="gitlab";outputDir=".";async generate(e){let t=[];t.push(`stages:
92
+ `))}catch{throw this.releaseReadError(e,"response was not valid JSON")}if(!pu(c))throw this.releaseReadError(e,"response did not contain tag_name, name, and body");return{draft:c.draft,notes:c.body??"",tag:c.tag_name,title:c.name??""}}async createRelease(e){await Bun.$`gh release create ${e.tag} --repo ${`${this.owner}/${this.repo}`} --title ${e.title} --notes ${e.notes} --verify-tag`.quiet()}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??Lt,baseBranch:e.base?.ref??Te,body:e.body??"",headBranch:e.head?.ref??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.merge_commit_sha,merged:e.merged,number:e.number,title:e.title,url:e.html_url}}mapPrResponse(e){return{author:e.author?.login??Lt,baseBranch:e.baseRefName??Te,body:e.body??"",headBranch:e.headRefName??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.mergeCommit?.oid??null,merged:e.state==="MERGED",number:e.number,title:e.title,url:e.url}}releaseReadError(e,t){return Error(`Failed to fetch GitHub release "${e}" from ${this.owner}/${this.repo}: ${t}`)}}var du="https://gitlab.com/api/v4",gu=404;class Ar extends je{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=process.env.CI_API_V4_URL??du,this.projectPath=encodeURIComponent(`${this.owner}/${this.repo}`)}async ensureAvailable(){this.authHeader=await this.resolveAuth()}async getDefaultBranch(){try{return(await this.api(`/projects/${this.projectPath}`)).default_branch||Te}catch{return Te}}async findPr(e){try{let t=new URLSearchParams({per_page:"1",state:"opened"});if(e.head)t.set("source_branch",e.head);if(e.label)t.set("labels",e.label);let r=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`);if(!r[0])return null;return this.mapMrResponse(r[0])}catch{return null}}async createPr(e){let t={description:e.body,source_branch:e.head,target_branch:e.base,title:e.title};if(e.labels?.length)t.labels=e.labels.join(",");let r=await this.api(`/projects/${this.projectPath}/merge_requests`,{body:JSON.stringify(t),method:"POST"});return this.mapMrResponse(r)}async updatePr(e,t){let r={};if(t.title)r.title=t.title;if(t.body)r.description=t.body;await this.api(`/projects/${this.projectPath}/merge_requests/${e}`,{body:JSON.stringify(r),method:"PUT"})}async getPr(e){try{let t=await this.api(`/projects/${this.projectPath}/merge_requests/${e}`);return this.mapMrResponse(t)}catch{throw new u(`Failed to fetch MR !${e}`,"Make sure the MR exists and you have access")}}async getPrFromCurrentBranch(){try{let t=(await Bun.$`git rev-parse --abbrev-ref HEAD`.quiet()).stdout.toString().trim(),r=new URLSearchParams({per_page:"1",source_branch:t,state:"opened"}),s=await this.api(`/projects/${this.projectPath}/merge_requests?${r}`);if(!s[0])throw Error("No MR found");return this.mapMrResponse(s[0])}catch{throw new u("No MR found for current branch","Make sure you have an open MR or provide a URL with --url")}}async getPrCommits(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/commits`)).map((r)=>r.id)}catch{return[]}}async getPrFiles(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/changes`)).changes?.map((r)=>r.new_path)??[]}catch{return[]}}async ensureLabelExists(e,t){try{let r={name:e};if(t?.description)r.description=t.description;if(t?.color)r.color=`#${t.color}`;await this.api(`/projects/${this.projectPath}/labels`,{body:JSON.stringify(r),method:"POST"})}catch{}}async getRelease(e){let t=await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,void 0,!0);if(t===void 0)return null;if(!mu(t))throw Error(`GitLab release response for ${e} did not contain tag_name, name, and description`);return{draft:!1,notes:t.description??"",tag:t.tag_name,title:t.name}}async createRelease(e){await this.api(`/projects/${this.projectPath}/releases`,{body:JSON.stringify({description:e.notes,name:e.title,tag_name:e.tag}),method:"POST"})}async deleteRelease(e){try{await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,{method:"DELETE"})}catch{}}async resolveAuth(){if(process.env.GITLAB_TOKEN)return{"PRIVATE-TOKEN":process.env.GITLAB_TOKEN};if(process.env.CI_JOB_TOKEN)return{"JOB-TOKEN":process.env.CI_JOB_TOKEN};try{let e=await Bun.$`glab auth status --show-token`.quiet(),r=(e.stdout.toString()+e.stderr.toString()).match(/Token found:\s*(\S+)/);if(r?.[1])return{Authorization:`Bearer ${r[1]}`}}catch{}throw new u("GitLab token not found","Set GITLAB_TOKEN environment variable or install glab CLI and run: glab auth login")}async api(e,t,r=!1){let s=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(r&&s.status===gu)return;if(!s.ok){let n=await s.text().catch(()=>"");throw Error(`GitLab API error: ${s.status} ${s.statusText}${n?` \u2014 ${n}`:""}`)}return s.json()}mapMrResponse(e){return{author:e.author?.username??Lt,baseBranch:e.target_branch??Te,body:e.description??"",headBranch:e.source_branch??"",labels:e.labels??[],mergeCommitSha:e.merge_commit_sha,merged:e.state==="merged",number:e.iid,title:e.title,url:e.web_url}}}function mu(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.tag_name==="string"&&typeof t.name==="string"&&(typeof t.description==="string"||t.description===null)}var hu={github:/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/|$)/,gitlab:/^\/(.+)\/([^/]+)\/-\/merge_requests\/([1-9]\d*)(?:\/|$)/,bitbucket:/^\/([^/]+)\/([^/]+)\/pull-requests\/([1-9]\d*)(?:\/|$)/};async function ht(e){let t=e??await Co();if(!t)throw new u("Could not detect git provider","Make sure you have a git remote configured (origin)");let r=fu(t);return await r.ensureAvailable(),r}function fu(e){switch(e.provider){case"github":return new Ir(e);case"gitlab":return new Ar(e);case"bitbucket":return new xr(e);default:throw new u(`Unsupported provider: ${e.provider}`)}}async function Co(){let e=await Dt();if(!e)return null;return Xe(e)}async function ko(){let e=await Co();if(!e)throw new u("Could not detect git provider","Make sure you have a git remote configured (origin)");return e.provider}async function Dt(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function Xe(e){let t=yu(e);if(!t)return null;let r=xo(t.hostname);if(!r)return null;let s=t.path.replace(/^\/+|\/+$/g,"").replace(/\.git$/,"").split("/").filter(Boolean),n=s.pop();if(!n||s.length===0)return null;if(r!=="gitlab"&&s.length!==1)return null;return{owner:s.join("/"),provider:r,repo:n}}function yu(e){try{let t=new URL(e);return{hostname:t.hostname.toLowerCase(),path:t.pathname}}catch{let t=e.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/),r=t?.[1],s=t?.[2];return r&&s?{hostname:r.toLowerCase(),path:s}:null}}function xo(e){if(e==="github.com")return"github";if(e==="gitlab.com")return"gitlab";if(e==="bitbucket.org")return"bitbucket";return null}function To(e){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return null;let r=xo(t.hostname.toLowerCase());if(!r)return null;let s=t.pathname.match(hu[r]),[,n,i,o]=s??[],a=Number(o);if(!n||!i||!Number.isSafeInteger(a))return null;return{number:a,owner:n,provider:r,repo:i}}catch{return null}}import{existsSync as Eo}from"fs";import{readFile as wu}from"fs/promises";import{dirname as bu,join as Xs}from"path";import{fileURLToPath as vu}from"url";var Or={"create-stone":{description:"When a PR is merged, create stone and update release PR",name:"Handle PR merge (stone + release PR)"},release:{description:"When the release PR is merged, publish packages",name:"Publish release"}},$u=Xs(bu(vu(import.meta.url)),"templates"),Io={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class Zs{async generate(e){let t=[];for(let r of e){let s=await this.readTemplate(r),n=this.getOutputPath(r);t.push({content:s,path:n})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>Eo(t))}async readTemplate(e){let t=Xs($u,this.provider,Io[e]);return wu(t,"utf-8")}}class _r extends Zs{provider="github";outputDir=".github/workflows";getOutputPath(e){return Xs(this.outputDir,Io[e])}}var Nt=".gitlab-ci-sisyphus.yml";class Mr extends Zs{provider="gitlab";outputDir=".";async generate(e){let t=[];t.push(`stages:
99
93
  - sisyphus
100
- `);for(let r of e){let n=await this.readTemplate(r);t.push(n)}return[{content:t.join(`
101
- `),path:vt}]}getExistingFiles(e){return Us(vt)?[vt]:[]}getIncludeInstruction(){return`include:
102
- - local: '${vt}'`}getOutputPath(e){return vt}}function qs(e){switch(e){case"github":return new ur;case"gitlab":return new dr;default:throw Error(`CI generation is not supported for ${e}`)}}var Pl={bitbucket:"Bitbucket Pipelines",github:"GitHub Actions",gitlab:"GitLab CI"},vl=B({all:{alias:"a",default:!1,description:"Install all workflows",type:"boolean"},createStone:{default:!1,description:"Install create-stone workflow",type:"boolean"},dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},release:{default:!1,description:"Install release workflow",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class vn extends j{name="init";description="Set up CI workflows for automated releases";args=vl;prompts=!0;async execute(e){let t=await Bs(),r=qs(t);y.info(`Detected ${l.bold(Pl[t])} repository
103
- `);let n=await this.selectWorkflows(e);if(n.length===0){y.info(l.dim("No workflows selected"));return}let i=r.getExistingFiles(n);if(i.length>0&&!e.args.yes){if(!e.interactive)throw new g(`Workflows already exist: ${i.join(", ")}`,"Use --yes to overwrite existing workflows");if(y.warn(`The following files already exist:
104
- ${i.map((o)=>` ${o}`).join(`
105
- `)}`),!await T({initialValue:!1,message:"Overwrite existing files?"}))return}let s=await r.generate(n);if(e.args.dryRun){for(let a of s)y.info(`
106
- ${l.bold(a.path)}:`),y.info(l.dim(a.content));return}for(let a of s){let o=bl(a.path);if(o!=="."&&!hl(o))await wl(o,{recursive:!0});await yl(a.path,a.content,"utf-8")}if(q(s.map((a)=>` ${l.green("+")} ${a.path}`).join(`
107
- `),l.green("CI workflows created")),r instanceof dr)y.info(`
108
- Add this to your ${l.bold(".gitlab-ci.yml")}:
109
- `),y.info(l.cyan(r.getIncludeInstruction())),y.info(""),y.info(`${l.yellow("Note:")} Add a ${l.bold("GITLAB_TOKEN")} CI/CD variable (Personal Access Token with ${l.bold("api")} + ${l.bold("write_repository")} scopes)`),y.info(l.dim("Required for creating release PRs. Settings \u2192 CI/CD \u2192 Variables")),y.info("");if(r instanceof ur)y.info(`
110
- ${l.yellow("Note:")} Enable ${l.bold('"Allow GitHub Actions to create and approve pull requests"')}`),y.info(l.dim("Settings \u2192 Actions \u2192 General \u2192 Workflow permissions")),y.info("");y.info(l.dim("Commit and push these files to enable the workflows."))}async selectWorkflows(e){let t=this.getWorkflowsFromFlags(e);if(t.length>0)return t;if(!e.interactive)throw new g("No workflows specified","Use --all or specify workflows with --createStone, --release");return ke({initialValues:Object.keys(mr),message:"Select workflows to create",options:Object.entries(mr).map(([r,n])=>({hint:n.description,label:n.name,value:r})),required:!1})}getWorkflowsFromFlags(e){if(e.args.all)return Object.keys(mr);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}}var we;((s)=>{s.Major="major";s.Minor="minor";s.Patch="patch";s.Dependency="dependency";s.Snapshot="snapshot"})(we||={});var Hs={["major"]:5,["minor"]:4,["patch"]:3,["dependency"]:2,["snapshot"]:1},st={["major"]:"\uD83D\uDEA8",["minor"]:"\u2728",["patch"]:"\uD83D\uDC1B",["dependency"]:"\uD83D\uDCE6",["snapshot"]:"\uD83D\uDCF8"},at={["major"]:l.red,["minor"]:l.yellow,["patch"]:l.green,["dependency"]:l.blue,["snapshot"]:l.magenta},He=["major","minor","patch","dependency","snapshot"];function Rl(e,t){return Hs[e]-Hs[t]}function _s(e,t){return Rl(e,t)>=0?e:t}function Vs(e){return Object.values(we).includes(e)}var kl=/^(\w+)(?:\(([^)]+)\))?(!)?: (.+)$/,Rn="\x1F",$l=new Set(["build","chore","ci","docs","feat","fix","perf","refactor","style","test"]);class J{hash;subject;author;body;type;scope;breaking;message;files;constructor(e){this.hash=e.hash,this.subject=e.subject,this.author=e.author,this.body=e.body,this.type=e.type,this.scope=e.scope,this.breaking=e.breaking,this.message=e.message,this.files=e.files}static async since(e){if(e){let t=await J.tryFetchFromRange(`${e}..HEAD`);if(t)return t}return J.fetchFromRange("HEAD")}static async inRange(e,t){let r=[`origin/${e}..origin/${t}`,`${e}..${t}`];for(let n of r){let i=await J.tryFetchFromRange(n);if(i)return i}return[]}static async fromHash(e){try{let r=(await Bun.$`git log -1 --pretty=format:"%H%x1f%s%x1f%an" ${e}`.quiet()).stdout.toString().trim();if(!r)return null;let n=r.split(Rn);if(n.length<3)return null;let[i,s,a]=n;if(!i||!s||!a)return null;return J.hydrate(i,s,a)}catch{return null}}static async fromMerge(e){try{let r=(await Bun.$`git rev-parse ${e}^2`.quiet()).stdout.toString().trim();if(!r)return[];return J.fetchFromRange(`${e}^1..${r}`)}catch{return[]}}static async tryFetchFromRange(e){try{return await J.fetchFromRange(e)}catch{return null}}static async fetchFromRange(e){let n=(await Bun.$`git log ${e} --pretty=format:${"%x00%H%x1f%s%x1f%an%x1f%b%x00"} --name-only --no-merges`.quiet()).stdout.toString().trim();if(!n)return[];let i=n.split("\x00").filter(Boolean),s=[];for(let a=0;a<i.length;a+=2){let o=i[a];if(!o)continue;let c=o.split(Rn);if(c.length<3)continue;let[p,m,u]=c;if(!p||!m||!u)continue;let f=c.slice(3).join(Rn).trim()||void 0,b=(i[a+1]??"").split(`
111
- `).filter(Boolean);s.push(J.parse(p,m,u).withFiles(b).withBody(f))}return s}static async hydrate(e,t,r){let n=await J.getFiles(e),i=await J.getBody(e);return J.parse(e,t,r).withFiles(n).withBody(i)}static async getFiles(e){return(await Bun.$`git diff-tree --no-commit-id --name-only -r ${e}`.quiet()).stdout.toString().trim().split(`
112
- `).filter(Boolean)}static async getBody(e){return(await Bun.$`git log -1 --pretty=format:"%b" ${e}`.quiet()).stdout.toString().trim()||void 0}static parse(e,t,r){let n=t.match(kl);if(n){let[,i="",s,a,o=""]=n;if(i&&$l.has(i))return new J({author:r,breaking:!!a,files:[],hash:e,message:o,scope:s,subject:t,type:i})}return new J({author:r,breaking:!1,files:[],hash:e,message:t,subject:t,type:Me})}get shortHash(){return this.hash.slice(0,cr)}get isConventional(){return this.type!==Me}withFiles(e){return new J({...this.toOptions(),files:e})}withBody(e){return new J({...this.toOptions(),body:e})}toInfo(e){return{body:this.body,hash:this.shortHash,message:this.message,packages:e,scope:this.scope,subject:this.subject,type:this.type}}toOptions(){return{author:this.author,body:this.body,breaking:this.breaking,files:this.files,hash:this.hash,message:this.message,scope:this.scope,subject:this.subject,type:this.type}}}var z=(e)=>e.length>0?e:void 0;var fr=1,Cl=1,hr=10,Sl=/[.ZT:-]/g,El=14,Il="nightly";class se{static bump(e,t,r){let[n="0.0.0",i=""]=e.split("-"),[s="",a="0"]=i.split(".");if(t==="snapshot")return se.formatSnapshot(r);if(r&&t!=="dependency")return se.formatTagged(n,r,s,a);if(t==="dependency"&&s)return se.formatTagged(n,s,s,a);return se.bumpBase(n,t)}static formatLabel(e,t,r,n){let i=se.bump(t,r,n),s=st[r];return`${e}@${t} => ${i} ${s}`}static formatSnapshot(e){let t=new Date().toISOString().replace(Sl,"").slice(0,El);return`0.0.0-${e||Il}-${t}`}static formatTagged(e,t,r,n){let i=t===r?Number.parseInt(n,hr)+fr:Cl;return`${e}-${t}.${i}`}static bumpBase(e,t){let[r="0",n="0",i="0"]=e.split("."),s=Number.parseInt(r,hr),a=Number.parseInt(n,hr),o=Number.parseInt(i,hr);switch(t){case"major":return`${s+fr}.0.0`;case"minor":return`${s}.${a+fr}.0`;case"dependency":case"patch":return`${s}.${a}.${o+fr}`;default:return`${s}.${a}.${o}`}}}class Q{name;version;file;dependencyOf;bump;tag;isPrivate;_newVersion;constructor(e){this.name=e.name,this.version=e.version,this.file=e.file,this.dependencyOf=e.dependencyOf??[],this.bump=e.bump,this.tag=e.tag,this.isPrivate=e.isPrivate??!1,this._newVersion=e.newVersion}static fromJson(e,t){return new Q({file:t,isPrivate:e.private??!1,name:e.name,version:e.version||Fs})}static applyStone(e,t){let r=[];for(let n of He)for(let i of e.getPackages(n)){let s=t.get(i);if(s)r.push(s.withBump(n,e.tag))}return r}get newVersion(){if(this._newVersion)return this._newVersion;if(!this.bump)return;return se.bump(this.version,this.bump,this.tag)}get label(){if(!this.bump)return`${this.name}@${this.version}`;return se.formatLabel(this.name,this.version,this.bump,this.tag)}withDependencyOf(e){return new Q({...this.toOptions(),dependencyOf:e})}withBump(e,t){return new Q({...this.toOptions(),bump:e,newVersion:se.bump(this.version,e,t),tag:t})}withVersions(e,t){return new Q({...this.toOptions(),newVersion:t,version:e})}toOptions(){return{bump:this.bump,dependencyOf:this.dependencyOf,file:this.file,isPrivate:this.isPrivate,name:this.name,newVersion:this._newVersion,tag:this.tag,version:this.version}}}import{randomUUID as Ll}from"crypto";class A{id;message;tag;description;commits;_packages;constructor(e){this.id=e.id,this.message=e.message,this.tag=e.tag,this.description=e.description,this.commits=e.commits,this._packages=e.packages}static create(e,t=0){let r=A.generateId(t);return A.fromData(r,e)}static fromJson(e){return A.fromData(e.id,e)}static mergeAll(e){let[t,...r]=e;if(!t)throw Error("No stones to merge");if(r.length===0)return t;let n=e.map((i)=>i.message).join("; ");return A.merge(e,n).stone}static merge(e,t){let r=new Map,n=[];for(let m of e)A.collectBumps(m,"major",r,n),A.collectBumps(m,"minor",r,n),A.collectBumps(m,"patch",r,n),A.collectBumps(m,"dependency",r,n);let i=A.categorizeBumps(r),s=e.map((m)=>m.description).filter(Boolean).join(`
113
-
114
- `),a=e.flatMap((m)=>m.commits??[]),o=[...new Set(e.map((m)=>m.tag).filter(Boolean))],c=`merged-${Date.now()}`,p=new A({commits:a.length>0?a:void 0,description:s||void 0,id:c,message:t,packages:i,tag:o[0]});return{conflicts:[...new Set(n)],stone:p}}static collectBumps(e,t,r,n){for(let i of e.getPackages(t)){let s=r.get(i);if(!s){r.set(i,t);continue}if(s===t)continue;n.push(i);let a=_s(t,s);if(a!==s)r.set(i,a)}}static categorizeBumps(e){let t=new Map;for(let r of He)t.set(r,[]);for(let[r,n]of e)t.get(n)?.push(r);return t}static fromData(e,t){let r=new Map;return r.set("major",t.major??[]),r.set("minor",t.minor??[]),r.set("patch",t.patch??[]),r.set("dependency",t.dependency??[]),r.set("snapshot",t.snapshot??[]),new A({commits:t.commits,description:t.description,id:e,message:t.message,packages:r,tag:t.tag})}static generateId(e){let t=String(e+1).padStart(js,"0"),r=Ll().slice(0,Ns);return`${t}-${r}`}get major(){return this._packages.get("major")??[]}get minor(){return this._packages.get("minor")??[]}get patch(){return this._packages.get("patch")??[]}get dependency(){return this._packages.get("dependency")??[]}get snapshot(){return this._packages.get("snapshot")??[]}get allPackages(){let e=[];for(let t of this._packages.values())e.push(...t);return e}get isEmpty(){return this.allPackages.length===0}affectsPackage(e){return this.allPackages.includes(e)}getPackages(e){return this._packages.get(e)??[]}withMessage(e){return new A({...this.toOptions(),message:e})}withTag(e){return new A({...this.toOptions(),tag:e})}withDescription(e){return new A({...this.toOptions(),description:e})}withCommits(e){return new A({...this.toOptions(),commits:e})}withPackages(e,t){let r=new Map(this._packages);return r.set(e,t),new A({...this.toOptions(),packages:r})}toOptions(){return{commits:this.commits,description:this.description,id:this.id,message:this.message,packages:new Map(this._packages),tag:this.tag}}toJson(){return{commits:this.commits&&this.commits.length>0?this.commits:void 0,dependency:z(this.dependency),description:this.description,id:this.id,major:z(this.major),message:this.message,minor:z(this.minor),patch:z(this.patch),snapshot:z(this.snapshot),tag:this.tag}}}import{readFile as Ol,rm as Ml,writeFile as Ws}from"fs/promises";import{dirname as Dl,join as Fl}from"path";var Al={bitbucket:"commits",github:"commit",gitlab:"-/commit"},xl={bitbucket:"bitbucket.org",github:"github.com",gitlab:"gitlab.com"};function kn(e){let t=xl[e.provider],r=Al[e.provider],n=`https://${t}/${e.owner}/${e.repo}`;return(i)=>`${n}/${r}/${i}`}class Rt{cached=void 0;async getRemoteInfo(){if(this.cached!==void 0)return this.cached;let e=await wn();if(!e)return this.cached=null,null;let t=Pt(e);if(!t)return this.cached=null,null;return this.cached={...t,commitUrl:kn(t)},this.cached}}class _e{config;originals=new Map;remoteParser=new Rt;commitUrlFn=null;constructor(e){this.config=e}async generate(e,t){await this.initCommitLinks();let r=new Map(t.map((n)=>[n.name,n]));for(let n of t){let i=this.filterStonesForPackage(e,n.name),s=this.getBumpedDependencies(e,n.name,r);await this.generateForPackage(i,n,s)}if(this.config.root)await this.generateRoot(e,t)}async initCommitLinks(){let e=await this.remoteParser.getRemoteInfo();this.commitUrlFn=e?.commitUrl??null}getBumpedDependencies(e,t,r){let n=new Set;for(let i of e){if(!i.dependency.includes(t))continue;for(let s of[...i.major,...i.minor,...i.patch])n.add(s)}return[...n].map((i)=>r.get(i)).filter((i)=>i!==void 0)}filterStonesForPackage(e,t){return e.filter((r)=>this.hasDirectChanges(r,t))}hasDirectChanges(e,t){return e.major.includes(t)||e.minor.includes(t)||e.patch.includes(t)}async rollback(){for(let[e,t]of this.originals)if(t===null)await Ml(e,{force:!0});else await Ws(e,t,"utf-8");this.originals.clear()}async generateForPackage(e,t,r){let n=Fl(Dl(t.file),this.config.filename),i=this.formatEntry(e,t,r);await this.prependToChangelog(n,i,t.name)}async generateRoot(e,t){let r=this.config.filename,n=this.formatRootEntry(e,t);await this.prependToChangelog(r,n,"Changelog")}async prependToChangelog(e,t,r){let n=await this.readExisting(e);if(!this.originals.has(e))this.originals.set(e,n);let i=n?this.extractTitle(n):`# ${r}`,s=n?this.extractRest(n):"",a=`${i}
115
-
116
- ${t}${s?`
117
-
118
- ${s}`:""}
119
- `;await Ws(e,a,"utf-8")}async readExisting(e){try{return await Ol(e,"utf-8")}catch{return null}}extractTitle(e){let t=e.split(`
94
+ `);for(let r of e){let s=await this.readTemplate(r);t.push(s)}return[{content:t.join(`
95
+ `),path:Nt}]}getExistingFiles(e){return Eo(Nt)?[Nt]:[]}getIncludeInstruction(){return`include:
96
+ - local: '${Nt}'`}getOutputPath(e){return Nt}}function Ao(e){switch(e){case"github":return new _r;case"gitlab":return new Mr;default:throw Error(`CI generation is not supported for ${e}`)}}var ku={bitbucket:"Bitbucket Pipelines",github:"GitHub Actions",gitlab:"GitLab CI"},xu=B({all:{alias:"a",default:!1,description:"Install all workflows",type:"boolean"},createStone:{default:!1,description:"Install create-stone workflow",type:"boolean"},dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},release:{default:!1,description:"Install release workflow",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class Qs extends D{name="init";description="Set up CI workflows for automated releases";args=xu;prompts=!0;async execute(e){let t=await ko(),r=Ao(t);v.info(`Detected ${p.bold(ku[t])} repository
97
+ `);let s=await this.selectWorkflows(e);if(s.length===0){v.info(p.dim("No workflows selected"));return}let n=r.getExistingFiles(s);if(n.length>0&&!e.args.yes){if(!e.interactive)throw new u(`Workflows already exist: ${n.join(", ")}`,"Use --yes to overwrite existing workflows");if(v.warn(`The following files already exist:
98
+ ${n.map((a)=>` ${a}`).join(`
99
+ `)}`),!await j({initialValue:!1,message:"Overwrite existing files?"}))return}let i=await r.generate(s);if(e.args.dryRun){for(let o of i)v.info(`
100
+ ${p.bold(o.path)}:`),v.info(p.dim(o.content));return}for(let o of i){let a=Cu(o.path);if(a!=="."&&!Pu(a))await Ru(a,{recursive:!0});await Su(o.path,o.content,"utf-8")}if(G(i.map((o)=>` ${p.green("+")} ${o.path}`).join(`
101
+ `),p.green("CI workflows created")),r instanceof Mr)v.info(`
102
+ Add this to your ${p.bold(".gitlab-ci.yml")}:
103
+ `),v.info(p.cyan(r.getIncludeInstruction())),v.info(""),v.info(`${p.yellow("Note:")} Add a ${p.bold("GITLAB_TOKEN")} CI/CD variable (Personal Access Token with ${p.bold("api")} + ${p.bold("write_repository")} scopes)`),v.info(p.dim("Required for creating release PRs. Settings \u2192 CI/CD \u2192 Variables")),v.info("");if(r instanceof _r)v.info(`
104
+ ${p.yellow("Note:")} Enable ${p.bold('"Allow GitHub Actions to create and approve pull requests"')}`),v.info(p.dim("Settings \u2192 Actions \u2192 General \u2192 Workflow permissions")),v.info("");v.info(p.dim("Commit and push these files to enable the workflows."))}async selectWorkflows(e){let t=this.getWorkflowsFromFlags(e);if(t.length>0)return t;if(!e.interactive)throw new u("No workflows specified","Use --all or specify workflows with --createStone, --release");return ke({initialValues:Object.keys(Or),message:"Select workflows to create",options:Object.entries(Or).map(([r,s])=>({hint:s.description,label:s.name,value:r})),required:!1})}getWorkflowsFromFlags(e){if(e.args.all)return Object.keys(Or);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}}var ge;((i)=>{i.Major="major";i.Minor="minor";i.Patch="patch";i.Dependency="dependency";i.Snapshot="snapshot"})(ge||={});var Oo={["major"]:5,["minor"]:4,["patch"]:3,["dependency"]:2,["snapshot"]:1},ft={["major"]:"\uD83D\uDEA8",["minor"]:"\u2728",["patch"]:"\uD83D\uDC1B",["dependency"]:"\uD83D\uDCE6",["snapshot"]:"\uD83D\uDCF8"},yt={["major"]:p.red,["minor"]:p.yellow,["patch"]:p.green,["dependency"]:p.blue,["snapshot"]:p.magenta},Ee=["major","minor","patch","dependency","snapshot"];function Tu(e,t){return Oo[e]-Oo[t]}function Lr(e,t){return Tu(e,t)>=0?e:t}function _o(e){return Object.values(ge).includes(e)}var Eu=/^(\w+)(?:\(([^)]+)\))?(!)?: (.+)$/,en="\x1F",Iu=new Set(["build","chore","ci","docs","feat","fix","perf","refactor","style","test"]);class J{hash;subject;author;body;type;scope;breaking;message;files;constructor(e){this.hash=e.hash,this.subject=e.subject,this.author=e.author,this.body=e.body,this.type=e.type,this.scope=e.scope,this.breaking=e.breaking,this.message=e.message,this.files=e.files}static async since(e){if(e!==void 0)try{let r=(await Bun.$`git rev-parse --verify --end-of-options ${`${e}^{commit}`}`.quiet()).stdout.toString().trim();return await J.fetchFromRange(`${r}..HEAD`)}catch(t){let r=new u(`Failed to read commits since ${e}`,"Fetch the missing commit or correct the configured baseline before creating stones");throw r.cause=t,r}return J.fetchFromRange("HEAD")}static async inRange(e,t){let r=[`origin/${e}..origin/${t}`,`${e}..${t}`];for(let s of r){let n=await J.tryFetchFromRange(s);if(n)return n}return[]}static async fromHash(e){try{let r=(await Bun.$`git log -1 --pretty=format:"%H%x1f%s%x1f%an" ${e}`.quiet()).stdout.toString().trim();if(!r)return null;let s=r.split(en);if(s.length<3)return null;let[n,i,o]=s;if(!n||!i||!o)return null;return J.hydrate(n,i,o)}catch{return null}}static async fromMerge(e){try{let r=(await Bun.$`git rev-parse ${e}^2`.quiet()).stdout.toString().trim();if(!r)return[];return J.fetchFromRange(`${e}^1..${r}`)}catch{return[]}}static async tryFetchFromRange(e){try{return await J.fetchFromRange(e)}catch{return null}}static async fetchFromRange(e){let s=(await Bun.$`git log ${e} --pretty=format:${"%x00%H%x1f%s%x1f%an%x1f%b%x00"} --name-only --no-merges`.quiet()).stdout.toString().trim();if(!s)return[];let n=s.split("\x00").filter(Boolean),i=[];for(let o=0;o<n.length;o+=2){let a=n[o];if(!a)continue;let c=a.split(en);if(c.length<3)continue;let[l,d,g]=c;if(!l||!d||!g)continue;let h=c.slice(3).join(en).trim()||void 0,f=(n[o+1]??"").split(`
105
+ `).filter(Boolean);i.push(J.parse(l,d,g).withFiles(f).withBody(h))}return i}static async hydrate(e,t,r){let s=await J.getFiles(e),n=await J.getBody(e);return J.parse(e,t,r).withFiles(s).withBody(n)}static async getFiles(e){return(await Bun.$`git diff-tree --no-commit-id --name-only -r ${e}`.quiet()).stdout.toString().trim().split(`
106
+ `).filter(Boolean)}static async getBody(e){return(await Bun.$`git log -1 --pretty=format:"%b" ${e}`.quiet()).stdout.toString().trim()||void 0}static parse(e,t,r){let s=t.match(Eu);if(s){let[,n="",i,o,a=""]=s;if(n&&Iu.has(n))return new J({author:r,breaking:!!o,files:[],hash:e,message:a,scope:i,subject:t,type:n})}return new J({author:r,breaking:!1,files:[],hash:e,message:t,subject:t,type:Be})}get shortHash(){return this.hash.slice(0,Tr)}get isConventional(){return this.type!==Be}withFiles(e){return new J({...this.toOptions(),files:e})}withBody(e){return new J({...this.toOptions(),body:e})}toInfo(e){return{body:this.body,hash:this.shortHash,message:this.message,packages:e,scope:this.scope,subject:this.subject,type:this.type}}toOptions(){return{author:this.author,body:this.body,breaking:this.breaking,files:this.files,hash:this.hash,message:this.message,scope:this.scope,subject:this.subject,type:this.type}}}var Y=(e)=>e.length>0?e:void 0;var Au=/^[A-Za-z][0-9A-Za-z]*$/,Ou=pt().map((e)=>Au.test(e)?e:Ye());function Ze(e,t="Invalid prerelease tag"){try{return Ou(e)}catch{throw new u(t,"Start with a letter and use only letters or numbers")}}var _u=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,Mu=/^(0|[1-9]\d*)$/,Mo=10,tn=1,Lu=2;function Ie(e){let t=_u.exec(e);if(!t)return null;let[,r="0",s="0",n="0",i,o]=t,a=[r,s,n].map((l)=>Number.parseInt(l,Mo)),c=i?i.split(".").map(Du):[];if(a.some((l)=>!Number.isSafeInteger(l)))return null;if(c.some((l)=>typeof l==="number"&&!Number.isSafeInteger(l)))return null;return{build:o?o.split("."):[],major:a[0],minor:a[1],patch:a[2],prerelease:c}}function Dr(e,t){let r=Ie(e);if(r)return r;throw new u(`Cannot ${t}: "${e}" is not a valid version`,'Set the package version to MAJOR.MINOR.PATCH (no leading "v") before releasing')}function Nr(e){let t=e.prerelease.length>0?`-${e.prerelease.join(".")}`:"",r=e.build.length>0?`+${e.build.join(".")}`:"";return`${e.major}.${e.minor}.${e.patch}${t}${r}`}function Ae(e){return e.prerelease.length>0}function Lo(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}function Do(e,t){let r=e.major-t.major||e.minor-t.minor||e.patch-t.patch;if(r!==0)return r<0?-1:1;return Nu(e.prerelease,t.prerelease)}function No(e,t){let r=Ae(e);if(t==="major"){let s=r&&e.minor===0&&e.patch===0;return rn(s?e.major:e.major+tn,0,0)}if(t==="minor"){let s=r&&e.patch===0;return rn(e.major,s?e.minor:e.minor+tn,0)}return rn(e.major,e.minor,r?e.patch:e.patch+tn)}function jr(e,t,r){return{...e,build:[],prerelease:[t,r]}}function jt(e){return Bo(e)?.tag}function jo(e){return Bo(e)?.counter}function Bo(e){if(e.prerelease.length!==Lu)return;let[t,r]=e.prerelease;if(typeof t!=="string"||typeof r!=="number")return;return{counter:r,tag:t}}function rn(e,t,r){return{build:[],major:e,minor:t,patch:r,prerelease:[]}}function Du(e){return Mu.test(e)?Number.parseInt(e,Mo):e}function Nu(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let r=Math.max(e.length,t.length);for(let s=0;s<r;s+=1){let n=e[s],i=t[s];if(n===void 0)return-1;if(i===void 0)return 1;if(n===i)continue;let o=typeof n==="number",a=typeof i==="number";if(o&&a)return n<i?-1:1;if(o)return-1;if(a)return 1;return n<i?-1:1}return 0}var ju=1,Fo=0,Bu=/[.ZT:-]/g,Fu=14,Uu="0.0.0",Vu=/^0\.0\.0-[0-9A-Za-z.-]+-\d{14,}$/,Gu="nightly",Hu={dependency:"patch",major:"major",minor:"minor",patch:"patch"};class me{static bump(e,t,r,s=!1){if(r!==void 0)Ze(r);if(t==="snapshot")return me.formatSnapshot(r);let n=`apply a ${t} bump`,i=Hu[t];if(!i)throw new u(`Unknown bump type "${t}"`,"Use major, minor, patch, dependency, or snapshot");if(me.isSnapshotVersion(e))throw new u(`Cannot ${n} to snapshot version ${e}`,"Restore the package version from its last real release before releasing it again");let o=Dr(e,n),a=me.resolveTag(o,t,r,s),c=No(o,i),l=a===void 0?c:me.applyPrerelease(c,o,a,e);if(Do(l,o)<=0)throw new u(`A ${t} bump would move ${e} to ${Nr(l)}, which is not a later version`,"Prerelease tags must increase in semver precedence (alpha < beta < rc)");return Nr(l)}static formatLabel(e,t,r,s,n){let i=n??me.bump(t,r,s),o=ft[r];return`${e}@${t} => ${i} ${o}`}static isSnapshotVersion(e){return Vu.test(e)}static resolveTag(e,t,r,s){if(r!==void 0)return r;if(s||t!=="dependency")return;let n=jt(e);if(n===void 0&&Ae(e))throw new u(`Cannot continue the prerelease of ${Nr(e)}`,"Set the package version to a <tag>.<number> prerelease, or roll a graduating release to leave the channel");return n}static applyPrerelease(e,t,r,s){if(Ze(r),!Lo(e,t))return jr(e,r,Fo);let n=jo(t);if(jt(t)===r&&n!==void 0)return jr(e,r,n+ju);if(t.prerelease[0]===r){let i=`${e.major}.${e.minor}.${e.patch}`;throw new u(`Cannot continue the "${r}" prerelease from ${s}`,`Set the package version to ${i}-${r}.<number> first`)}return jr(e,r,Fo)}static formatSnapshot(e){let t=new Date().toISOString().replace(Bu,"").slice(0,Fu);return`${Uu}-${e||Gu}-${t}`}}var qu={build:[],major:0,minor:0,patch:0,prerelease:[]},Br="workspace:",Uo=["dependencies","devDependencies","optionalDependencies","peerDependencies"];function Wu(e){let t=[];for(let r of Uo)for(let[s,n]of Object.entries(e[r]??{})){if(!n?.startsWith(Br))continue;t.push({kind:r,name:s,specifier:n})}return t}class z{name;version;file;workspaceDependencies;bump;tag;isPrivate;_newVersion;constructor(e){this.name=e.name,this.version=e.version,this.file=e.file,this.workspaceDependencies=e.workspaceDependencies??[],this.bump=e.bump,this.tag=e.tag,this.isPrivate=e.isPrivate??!1,this._newVersion=e.newVersion}static fromJson(e,t){return new z({file:t,isPrivate:e.private??!1,name:e.name,version:e.version||Po,workspaceDependencies:Wu(e)})}static applyStone(e,t,r=Uo){let s=[],n=new Set,i=z.graduatingPackages(e,t,new Set(r));for(let o of Ee)for(let a of e.getPackages(o)){let c=t.get(a);if(!c||n.has(a))continue;n.add(a),s.push(c.withBump(o,e.tag,i.has(a)))}return s}static graduatingPackages(e,t,r){let s=new Set;if(e.tag!==void 0)return s;let n=Ee.filter((a)=>a!=="dependency"&&a!=="snapshot");for(let a of n)for(let c of e.getPackages(a))if(z.isPrereleaseVersion(t.get(c)?.version))s.add(c);let i=e.getPackages("dependency").map((a)=>t.get(a)).filter((a)=>a!==void 0&&z.isPrereleaseVersion(a.version)),o=!0;while(o){o=!1;for(let a of i){if(s.has(a.name))continue;if(!a.workspaceDependencies.some((c)=>r.has(c.kind)&&s.has(c.name)))continue;s.add(a.name),o=!0}}return s}static isPrereleaseVersion(e){return e!==void 0&&Ae(Ie(e)??qu)}get newVersion(){if(this._newVersion)return this._newVersion;if(!this.bump)return;return me.bump(this.version,this.bump,this.tag)}get label(){if(!this.bump)return`${this.name}@${this.version}`;return me.formatLabel(this.name,this.version,this.bump,this.tag,this._newVersion)}withBump(e,t,r=!1){return new z({...this.toOptions(),bump:e,newVersion:me.bump(this.version,e,t,r),tag:t})}withVersions(e,t){return new z({...this.toOptions(),newVersion:t,version:e})}toOptions(){return{bump:this.bump,file:this.file,isPrivate:this.isPrivate,name:this.name,newVersion:this._newVersion,tag:this.tag,version:this.version,workspaceDependencies:this.workspaceDependencies}}}import{randomUUID as Ju}from"crypto";var zu=fo(pt());class A{id;message;tag;description;commits;_packages;constructor(e){this.id=e.id,this.message=e.message,this.tag=e.tag===void 0?void 0:Ze(e.tag),this.description=e.description,this.commits=e.commits,this._packages=e.packages}static create(e,t=0){let r=A.generateId(t);return A.fromData(r,e)}static fromJson(e){return A.fromData(e.id,e)}static mergeAll(e){if(e.length===0)throw Error("No stones to merge");let t=e.map((n)=>n.message).join("; "),{stone:r,errors:s}=A.merge(e,t);if(s.length>0)throw new u("Pending stones conflict and cannot be released together",s.join(`
107
+ `));return r}static merge(e,t){let r=new Map,s=[],n=[];for(let g of e)for(let h of Ee)A.collectBumps(g,h,r,s,n);let i=A.categorizeBumps(r),o=e.map((g)=>g.description).filter(Boolean).join(`
108
+
109
+ `),a=A.mergeCommits(e),c=A.resolveTag(e,n),l=`merged-${Date.now()}`,d=new A({commits:a.length>0?a:void 0,description:o||void 0,id:l,message:t,packages:i,tag:c});return{conflicts:[...new Set(s)],errors:[...new Set(n)],stone:d}}static resolveTag(e,t){let r=e.filter((i)=>!i.isEmpty),s=new Map;for(let i of r){if(!i.tag)continue;s.set(i.tag,[...s.get(i.tag)??[],i.id])}if(s.size===0)return;let n=r.filter((i)=>!i.tag).map((i)=>i.id);if(s.size>1||n.length>0){let i=[...s.entries()].map(([o,a])=>`${o}: ${a.join(", ")}`);if(n.length>0)i.push(`no tag: ${n.join(", ")}`);t.push(`Stones disagree on the prerelease tag (${i.join("; ")})`)}return[...s.keys()][0]}static mergeCommits(e){let t=new Map;for(let r of e.flatMap((s)=>s.commits??[])){let s=t.get(r.hash);if(!s){t.set(r.hash,{...r,packages:[...r.packages??[]]});continue}let n=new Set([...s.packages,...r.packages??[]]);t.set(r.hash,{...s,packages:[...n]})}return[...t.values()]}static collectBumps(e,t,r,s,n){for(let i of e.getPackages(t)){let o=r.get(i);if(!o){r.set(i,t);continue}if(o===t)continue;if(o==="snapshot"||t==="snapshot"){n.push(`Package ${i} is requested as both a snapshot and a ${o==="snapshot"?t:o} release`);continue}s.push(i);let a=Lr(t,o);if(a!==o)r.set(i,a)}}static categorizeBumps(e){let t=new Map;for(let r of Ee)t.set(r,[]);for(let[r,s]of e)t.get(s)?.push(r);return t}static fromData(e,t){let r=new Map;for(let s of Ee){let n=t[s];try{r.set(s,n===void 0?[]:zu(n))}catch{throw new u(`Invalid ${s} packages in stone ${e}`,"Each bump field must contain an array of package names")}}return new A({commits:t.commits,description:t.description,id:e,message:t.message,packages:r,tag:t.tag})}static generateId(e){let t=String(e+1).padStart(Ro,"0"),r=Ju().slice(0,So);return`${t}-${r}`}get major(){return this._packages.get("major")??[]}get minor(){return this._packages.get("minor")??[]}get patch(){return this._packages.get("patch")??[]}get dependency(){return this._packages.get("dependency")??[]}get snapshot(){return this._packages.get("snapshot")??[]}get allPackages(){let e=[];for(let t of this._packages.values())e.push(...t);return e}get isEmpty(){return this.allPackages.length===0}affectsPackage(e){return this.allPackages.includes(e)}getPackages(e){return this._packages.get(e)??[]}withMessage(e){return new A({...this.toOptions(),message:e})}withTag(e){return new A({...this.toOptions(),tag:e})}withDescription(e){return new A({...this.toOptions(),description:e})}withCommits(e){return new A({...this.toOptions(),commits:e})}withPackages(e,t){let r=new Map(this._packages);return r.set(e,t),new A({...this.toOptions(),packages:r})}toOptions(){return{commits:this.commits,description:this.description,id:this.id,message:this.message,packages:new Map(this._packages),tag:this.tag}}toJson(){return{commits:this.commits&&this.commits.length>0?this.commits:void 0,dependency:Y(this.dependency),description:this.description,id:this.id,major:Y(this.major),message:this.message,minor:Y(this.minor),patch:Y(this.patch),snapshot:Y(this.snapshot),tag:this.tag}}}import{readFile as Xu,rm as Zu,writeFile as Vo}from"fs/promises";import{dirname as Qu,join as ep}from"path";var Ku={bitbucket:"commits",github:"commit",gitlab:"-/commit"},Yu={bitbucket:"bitbucket.org",github:"github.com",gitlab:"gitlab.com"};function sn(e){let t=Yu[e.provider],r=Ku[e.provider],s=`https://${t}/${e.owner}/${e.repo}`;return(n)=>`${s}/${r}/${n}`}class Bt{cached=void 0;async getRemoteInfo(){if(this.cached!==void 0)return this.cached;let e=await Dt();if(!e)return this.cached=null,null;let t=Xe(e);if(!t)return this.cached=null,null;return this.cached={...t,commitUrl:sn(t)},this.cached}}class Qe{config;originals=new Map;remoteParser=new Bt;commitUrlFn=null;constructor(e){this.config=e}async generate(e,t){await this.initCommitLinks();let r=new Map(t.map((s)=>[s.name,s]));for(let s of t){let n=this.filterStonesForPackage(e,s.name),i=this.getBumpedDependencies(e,s.name,r);await this.generateForPackage(n,s,i)}if(this.config.root)await this.generateRoot(e,t)}async initCommitLinks(){let e=await this.remoteParser.getRemoteInfo();this.commitUrlFn=e?.commitUrl??null}getBumpedDependencies(e,t,r){let s=new Set;for(let n of e){if(!n.dependency.includes(t))continue;for(let i of[...n.major,...n.minor,...n.patch])s.add(i)}return[...s].map((n)=>r.get(n)).filter((n)=>n!==void 0)}filterStonesForPackage(e,t){return e.filter((r)=>this.hasDirectChanges(r,t))}hasDirectChanges(e,t){return e.major.includes(t)||e.minor.includes(t)||e.patch.includes(t)}async rollback(){for(let[e,t]of this.originals)if(t===null)await Zu(e,{force:!0});else await Vo(e,t,"utf-8");this.originals.clear()}async generateForPackage(e,t,r){let s=ep(Qu(t.file),this.config.filename),n=this.formatEntry(e,t,r);await this.prependToChangelog(s,n,t.name)}async generateRoot(e,t){let r=this.config.filename,s=this.formatRootEntry(e,t);await this.prependToChangelog(r,s,"Changelog")}async prependToChangelog(e,t,r){let s=await this.readExisting(e);if(!this.originals.has(e))this.originals.set(e,s);let n=s?this.extractTitle(s):`# ${r}`,i=s?this.extractRest(s):"",o=`${n}
110
+
111
+ ${t}${i?`
112
+
113
+ ${i}`:""}
114
+ `;await Vo(e,o,"utf-8")}async readExisting(e){try{return await Xu(e,"utf-8")}catch{return null}}extractTitle(e){let t=e.split(`
120
115
  `)[0]??"";return t.startsWith("#")?t:"# Changelog"}extractRest(e){let t=e.split(`
121
- `);if(!(t[0]??"").startsWith("#"))return e;let n=1;while(n<t.length&&t[n]?.trim()==="")n++;return t.slice(n).join(`
122
- `).trim()}formatEntry(e,t,r){let n=this.formatPackageHeader(t),i=r.length>0,s=[`## ${n}`];for(let a of e)s.push("",`### ${hn} ${a.message}`),s.push("",this.formatStoneContent(a,t.name));if(i){s.push("",`### ${this.config.sections.dependencies}`);for(let a of r)s.push(`- \`${a.name}\` ${a.version} \u2192 ${a.newVersion}`)}return s.join(`
123
- `)}formatRootEntry(e,t){let n=[`## ${this.formatRootHeader(t)}`];n.push("","**Packages**");for(let i of t){let s=this.getEmoji(i),a=i.newVersion?`${i.version} \u2192 ${i.newVersion}`:i.version;n.push(`- ${s} \`${i.name}\` ${a}`)}for(let i of e)n.push("",`### ${hn} ${i.message}`),n.push(this.formatStonePackages(i)),n.push("",this.formatRootStoneContent(i));return n.join(`
124
- `)}formatPackageHeader(e){let t=e.newVersion??e.version,r=this.getDate(),n=this.getEmoji(e);return this.config.packageHeader.replace("{emoji}",()=>n).replace("{version}",()=>t).replace("{date}",()=>r)}formatRootHeader(e){let t=this.getDate(),r=e.map((n)=>`${n.name}@${n.newVersion??n.version}`).join(", ");return this.config.rootHeader.replace("{date}",()=>t).replace("{packages}",()=>r)}formatRootStoneContent(e){let t=[];if(e.description)t.push(this.formatDescription(e.description));if(e.commits?.length){let r=!this.isSectionName(e.message);t.push(this.formatRootCommits(e.commits,r))}return t.join(`
116
+ `);if(!(t[0]??"").startsWith("#"))return e;let s=1;while(s<t.length&&t[s]?.trim()==="")s++;return t.slice(s).join(`
117
+ `).trim()}formatEntry(e,t,r){let s=this.formatPackageHeader(t),n=r.length>0,i=[`## ${s}`];for(let o of e)i.push("",`### ${Ks} ${o.message}`),i.push("",this.formatStoneContent(o,t.name));if(n){i.push("",`### ${this.config.sections.dependencies}`);for(let o of r)i.push(`- \`${o.name}\` ${o.version} \u2192 ${o.newVersion}`)}return i.join(`
118
+ `)}formatRootEntry(e,t){let s=[`## ${this.formatRootHeader(t)}`];s.push("","**Packages**");for(let n of t){let i=this.getEmoji(n),o=n.newVersion?`${n.version} \u2192 ${n.newVersion}`:n.version;s.push(`- ${i} \`${n.name}\` ${o}`)}for(let n of e)s.push("",`### ${Ks} ${n.message}`),s.push(this.formatStonePackages(n)),s.push("",this.formatRootStoneContent(n));return s.join(`
119
+ `)}formatPackageHeader(e){let t=e.newVersion??e.version,r=this.getDate(),s=this.getEmoji(e);return this.config.packageHeader.replace("{emoji}",()=>s).replace("{version}",()=>t).replace("{date}",()=>r)}formatRootHeader(e){let t=this.getDate(),r=e.map((s)=>`${s.name}@${s.newVersion??s.version}`).join(", ");return this.config.rootHeader.replace("{date}",()=>t).replace("{packages}",()=>r)}formatRootStoneContent(e){let t=[];if(e.description)t.push(this.formatDescription(e.description));if(e.commits?.length){let r=!this.isSectionName(e.message);t.push(this.formatRootCommits(e.commits,r))}return t.join(`
125
120
 
126
121
  `)}formatRootCommits(e,t){let r=this.formatCommits(e,t);return`<details>
127
122
  <summary>Commits (${e.length})</summary>
128
123
 
129
124
  ${r}
130
125
 
131
- </details>`}formatStonePackages(e){let t=[...e.major,...e.minor,...e.patch];if(t.length===0)return"";return`**Packages:** ${t.map((n)=>`\`${n}\``).join(" \xB7 ")}`}formatStoneContent(e,t){let r=[];if(e.description)r.push(this.formatDescription(e.description));let n=t&&e.commits?this.filterCommitsForPackage(e.commits,t):e.commits??[];if(n.length>0){let i=!this.isSectionName(e.message);r.push(this.formatCommits(n,i))}return r.join(`
126
+ </details>`}formatStonePackages(e){let t=[...e.major,...e.minor,...e.patch];if(t.length===0)return"";return`**Packages:** ${t.map((s)=>`\`${s}\``).join(" \xB7 ")}`}formatStoneContent(e,t){let r=[];if(e.description)r.push(this.formatDescription(e.description));let s=t&&e.commits?this.filterCommitsForPackage(e.commits,t):e.commits??[];if(s.length>0){let n=!this.isSectionName(e.message);r.push(this.formatCommits(s,n))}return r.join(`
132
127
 
133
128
  `)}isSectionName(e){return Object.values(this.config.sections).includes(e)}formatDescription(e){return`<details>
134
129
  <summary>Description</summary>
135
130
 
136
131
  ${this.convertHeadersToBold(e).split(`
137
- `).map((n)=>` ${n}`).join(`
132
+ `).map((s)=>` ${s}`).join(`
138
133
  `)}
139
- </details>`}convertHeadersToBold(e){return e.replace(/^#{1,6}\s+(.+)$/gm,"**$1**")}getDate(){return new Date().toISOString().split("T")[0]??""}getEmoji(e){return e.bump?st[e.bump]:"\uD83D\uDCE6"}filterCommitsForPackage(e,t){return e.filter((r)=>r.packages.includes(t))}formatCommits(e,t){if(!t)return e.map((i)=>this.formatCommitLine(i)).join(`
140
- `);let r=this.groupCommitsByType(e),n=[];for(let[i,s]of r){let a=this.config.sections[i]??`${i} changes`;n.push(`#### ${a}`),n.push(s.map((o)=>this.formatCommitLine(o)).join(`
141
- `))}return n.join(`
134
+ </details>`}convertHeadersToBold(e){return e.replace(/^#{1,6}\s+(.+)$/gm,"**$1**")}getDate(){return new Date().toISOString().split("T")[0]??""}getEmoji(e){return e.bump?ft[e.bump]:"\uD83D\uDCE6"}filterCommitsForPackage(e,t){return e.filter((r)=>r.packages.includes(t))}formatCommits(e,t){if(!t)return e.map((n)=>this.formatCommitLine(n)).join(`
135
+ `);let r=this.groupCommitsByType(e),s=[];for(let[n,i]of r){let o=this.config.sections[n]??`${n} changes`;s.push(`#### ${o}`),s.push(i.map((a)=>this.formatCommitLine(a)).join(`
136
+ `))}return s.join(`
142
137
 
143
- `)}groupCommitsByType(e){let t=new Map;for(let r of e){let n=t.get(r.type)??[];n.push(r),t.set(r.type,n)}return Array.from(t.entries()).sort(([r],[n])=>(et[r]??tt)-(et[n]??tt))}formatCommitLine(e){let r=`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`;if(e.body){let n=e.body.split(`
144
- `).map((i)=>` ${i}`).join(`
138
+ `)}groupCommitsByType(e){let t=new Map;for(let r of e){let s=t.get(r.type)??[];s.push(r),t.set(r.type,s)}return Array.from(t.entries()).sort(([r],[s])=>(dt[r]??gt)-(dt[s]??gt))}formatCommitLine(e){let r=`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`;if(e.body){let s=e.body.split(`
139
+ `).map((n)=>` ${n}`).join(`
145
140
  `);return`${r}
146
141
  <details>
147
142
  <summary>Details</summary>
148
143
 
149
- ${n}
150
- </details>`}return r}}import{readdir as Js,readFile as zs}from"fs/promises";import{join as $n}from"path";var jl=".changeset",Nl="config.json";class Cn{root;constructor(e=process.cwd()){this.root=e}get changesetDir(){return $n(this.root,jl)}async exists(){try{return await Js(this.changesetDir),!0}catch{return!1}}async parse(){let e=[],t=[],r=await this.findChangesetFiles();for(let i of r){let s=await this.parseFile(i);if(s)t.push(s);else e.push(`Failed to parse: ${i}`)}let n=await this.parseConfig();return{changesets:t,config:n,errors:e}}async findChangesetFiles(){try{return(await Js(this.changesetDir)).filter((t)=>t.endsWith(".md")&&t!=="README.md").map((t)=>$n(this.changesetDir,t))}catch{return[]}}async parseFile(e){try{let r=(await zs(e,"utf-8")).split(`
151
- `),n=!1,i=[],s=[];for(let c of r)if(c.trim()==="---")n=!n;else if(n)i.push(c);else if(i.length>0)s.push(c);let a={};for(let c of i){let p=c.match(/^"(.+)":\s*(major|minor|patch)$/);if(p?.[1]&&p[2])a[p[1]]=p[2]}if(Object.keys(a).length===0)return null;return{filename:e.split("/").pop()??"",packages:a,summary:s.join(`
152
- `).trim()}}catch{return null}}async parseConfig(){try{let e=$n(this.changesetDir,Nl),t=await zs(e,"utf-8");return JSON.parse(t)}catch{return null}}toStoneData(e){let t=[],r=[],n=[];for(let[o,c]of Object.entries(e.packages))switch(c){case"major":t.push(o);break;case"minor":r.push(o);break;case"patch":n.push(o);break}let i=e.summary.split(`
153
- `),s=i[0]?.trim()||"Migrated from changeset";return{description:i.slice(1).join(`
154
- `).trim()||void 0,major:z(t),message:s,minor:z(r),patch:z(n)}}}function wr(e){let t=new Map;for(let[r,n]of e){let i=n.file.replace(/\\/g,"/"),s=i.substring(0,i.lastIndexOf("/"))||".";t.set(s,r)}return t}function ot(e,t){let r=new Set;for(let n of e){let i=t.get(n);if(i?.dependencyOf){for(let s of i.dependencyOf)if(!e.includes(s))r.add(s)}}return Array.from(r)}function kt(e,t,r=!0){let n=new Set;for(let i of e)for(let[s,a]of t){let o=s===".",c=i.startsWith(`${s}/`);if(o?r:c)n.add(a)}return n}import{existsSync as ct}from"fs";import{mkdir as Ks,readdir as Sn,readFile as Ys,rename as Tl,unlink as Bl,writeFile as Ul}from"fs/promises";import{dirname as Gl,join as $t,resolve as Zs}from"path";var Xs=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,Qs=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;class I{config;constructor(e){this.config=e}get sisyphusDir(){return this.config.get("sisyphusDir")||De}get stonesPath(){return this.config.get("stonesPath")||$t(this.sisyphusDir,Os)}get releasedPath(){return $t(this.sisyphusDir,Ms)}async list(){let e=await this.listIds(),t=[];for(let r of e){let n=await this.get(r);if(n)t.push(n)}return t}async listIds(){return await this.ensureStorageExists(),(await Sn(this.stonesPath)).filter((t)=>t.endsWith(".json")).map((t)=>this.toStoneId(t)).sort()}async get(e){let t=this.getFilePath(e);if(!ct(t))return null;let r=await Ys(t,"utf-8"),n=JSON.parse(r);if(n.id!==e)throw Error(`Stone file ID mismatch: expected "${e}", found "${String(n.id)}"`);return A.fromJson(n)}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),r=JSON.stringify(e.toJson(),null,2);await Ul(t,r,"utf-8"),this.addToConfigStones(e.id)}async delete(e){let t=this.getFilePath(e);if(!ct(t))return!1;return await Bl(t),this.removeFromConfigStones(e),!0}async deleteMany(e){let t=0;for(let r of e)if(await this.delete(r))t++;return t}async create(e){let t=await this.listIds(),r=A.create(e,t.length);return await this.save(r),r}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),r=$t(this.releasedPath,t);await Ks(r,{recursive:!0});for(let n of e){let i=this.getFilePath(n.id),s=$t(r,`${n.id}.json`);if(ct(i))await Tl(i,s),this.removeFromConfigStones(n.id)}return t}async getReleasedStones(e,t){let r=this.getArchivePath(e);if(!ct(r))return[];let i=(await Sn(r)).filter((o)=>o.endsWith(".json")).sort(),s=t?.map((o)=>`${this.validateId(o)}.json`).sort();if(s&&JSON.stringify(i)!==JSON.stringify(s))throw Error(`Released stone archive ${e} does not match currentRelease: expected ${s.join(", ")||"no stones"}, found ${i.join(", ")||"no stones"}`);let a=[];for(let o of i)try{let c=this.validateId(o.slice(0,-5)),p=await Ys($t(r,o),"utf-8"),m=JSON.parse(p);if(m.id!==c)throw Error(`Stone file ID mismatch: expected "${c}", found "${String(m.id)}"`);a.push(A.fromJson(m))}catch(c){if(t)throw c;y.warn(l.dim(`Failed to parse stone "${o}": ${c}`))}return a}async listReleasedTimestamps(){if(!ct(this.releasedPath))return[];return(await Sn(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()&&Qs.test(t.name)).map((t)=>t.name)}async getTrackedCommitPackages(){let e=await this.list(),t=new Map;for(let r of e.flatMap((n)=>n.commits??[])){let n=t.get(r.hash)??new Set;for(let i of r.packages)n.add(i);t.set(r.hash,n)}return t}getFilePath(e){let t=this.validateId(e);return this.resolveChildPath(this.stonesPath,`${t}.json`,`Stone path must be a direct child of the stones directory: ${e}`)}getFilePaths(e){return e.map((t)=>this.getFilePath(t.id))}createTimestamp(){return new Date().toISOString().replace(/[:.]/g,"-")}getArchivePath(e){if(!Qs.test(e))throw Error(`Invalid released stone timestamp "${e}"`);return this.resolveChildPath(this.releasedPath,e,`Released stone archive must be a direct child of the released directory: ${e}`)}resolveChildPath(e,t,r){let n=Zs(e),i=Zs(n,t);if(Gl(i)!==n)throw Error(r);return i}validateId(e){if(!Xs.test(e))throw Error(`Invalid stone ID "${e}"`);return e}toStoneId(e){let t=e.slice(0,-5);if(Xs.test(t))return t;throw new g(`Invalid stone ID "${t}" from stone file ${e} in ${this.stonesPath}`,"Remove or rename the file; stone files must match <seq>-<hash>.json")}async ensureStorageExists(){if(!ct(this.stonesPath))await Ks(this.stonesPath,{recursive:!0})}addToConfigStones(e){let t=this.config.getAll();if(!t.stones.includes(e))this.config.set("stones",[...t.stones,e])}removeFromConfigStones(e){let t=this.config.getAll(),r=t.stones.filter((n)=>n!==e);if(r.length!==t.stones.length)this.config.set("stones",r)}}class O{static async scan(e={}){let{filter:t,single:r}=e;if(r)return O.scanRootPackage(t);let n=await O.getWorkspaces();O.validateWorkspaces(n);let i=await O.scanWorkspaces(n);return{packageNames:O.filterNames(Array.from(i.keys()),t),packages:i}}static async getWorkspaces(){try{let t=(await Bun.file("package.json").json())?.workspaces;if(Array.isArray(t))return t;return t?.packages||[]}catch{throw new g("Could not read package.json","Ensure you're in a project root directory.")}}static validateWorkspaces(e){if(e.length===0)throw new g("No workspaces found in package.json.","Use --single flag or set `single: true` in config for single-package mode.")}static filterNames(e,t){if(!t)return e;return e.filter((r)=>r.includes(t))}static async scanRootPackage(e){let t=await Bun.file("package.json").json(),r=Q.fromJson(t,"package.json"),n=new Map;return n.set(r.name,r),{packageNames:O.filterNames([r.name],e),packages:n}}static async scanWorkspaces(e){let t=new Map,r=new Map;for(let n of e){let i=new Bun.Glob(`${n}/package.json`).scanSync({cwd:process.cwd()});for(let s of i){let a=await O.processPackageFile(s,r);if(a)t.set(a.name,a)}}return O.linkDependencies(t,r),t}static async processPackageFile(e,t){let r=await Bun.file(e).json(),n=Q.fromJson(r,e);return O.trackDependencies(n.name,r,t),n}static trackDependencies(e,t,r){let n={...t.dependencies,...t.devDependencies};for(let[i,s]of Object.entries(n)){if(!s?.startsWith("workspace"))continue;let a=r.get(i)||[];if(!a.includes(e))r.set(i,[...a,e])}}static linkDependencies(e,t){for(let[r,n]of t){let i=e.get(r);if(i)e.set(r,i.withDependencyOf(n))}}}var ql={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[Me]:"patch"};class Ve{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new I(e)}async analyze(e={}){let t=await this.getCommitsSinceLastRelease();if(t.length===0)return[];let r=this.config.get("commits")?.skip??nt.commits.skip;if(t=t.filter((i)=>!this.shouldSkipCommit(i,r)),t.length===0)return[];let n=await this.stoneManager.getTrackedCommitPackages();return this.groupByPackage(t,e,n)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;for(let r of t.messagePatterns)try{if(new RegExp(r,"i").test(e.subject))return!0}catch{y.warn(l.yellow(`Invalid regex pattern in commits.skip.messagePatterns: "${r}"`))}return!1}async getCommitsSinceLastRelease(){let t=this.config.get("lastStone")?.commit||void 0;if(!t)return[];return J.since(t)}async groupByPackage(e,t,r){let{packages:n,packageNames:i}=await O.scan({filter:t.filter,single:t.single}),s=new Set(i),a=new Map([...n].filter(([p])=>s.has(p))),o=wr(a),c=new Map;for(let p of e){let m=kt(p.files,o);for(let d of r.get(p.shortHash)??[])m.delete(d);if(m.size===0)continue;let u=p.breaking?"major":ql[p.type]||"patch",f=`${p.type}${p.breaking?"!":""}`,b=c.get(f);if(!b){let d=this.getGroupMessage(p);b={bump:u,commits:[],message:d,packages:new Set},c.set(f,b)}b.commits.push(p.toInfo([...m]));for(let d of m)b.packages.add(d)}return Array.from(c.entries()).sort(([p],[m])=>(et[p]??tt)-(et[m]??tt)).map(([,p])=>p)}getGroupMessage(e){let t=this.config.get("changelog").sections;if(e.breaking)return t.breaking;return t[e.type]??`${e.type} updates`}static buildStoneData(e,t,r){let n=Array.from(e.packages);return{[e.bump]:n,commits:z(e.commits),dependency:z(ot(n,t)),message:e.message,tag:r}}}import{readFile as Hl,writeFile as ea}from"fs/promises";var _l=2,Vl=1,Wl='"version"';class Ct{originals=new Map;async updateAll(e){this.originals.clear();for(let t of e)await this.updatePackage(t)}async rollback(){for(let[e,t]of this.originals)await ea(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;let r=await Hl(e.file,"utf-8");this.originals.set(e.file,r),await ea(e.file,Jl(r,t),"utf-8")}}function Jl(e,t){let r=zl(e);if(!r)return Zl(e,t);return`${e.slice(0,r.start)}${JSON.stringify(t)}${e.slice(r.end)}`}function zl(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'){let i=En(e,r);if(t===Vl&&e.slice(r,i)===Wl&&!Yl(e,r)){let a=Kl(e,i);if(a!==null&&e[a]==='"')return{end:En(e,a),start:a};return null}r=i;continue}if(n==="{"||n==="[")t+=1;if(n==="}"||n==="]")t-=1;r+=1}return null}function En(e,t){let r=t+1;while(r<e.length){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r+1;r+=1}return r}function Kl(e,t){let r=t;while(r<e.length&&/\s/.test(e[r]??""))r+=1;if(e[r]!==":")return null;r+=1;while(r<e.length&&/\s/.test(e[r]??""))r+=1;return r}function Yl(e,t){let r=[],n=0;while(n<t){let i=e[n];if(i==='"'){n=En(e,n);continue}if(i==="{"||i==="[")r.push(i);if(i==="}"||i==="]")r.pop();n+=1}return r[r.length-1]==="["}function Zl(e,t){let r=JSON.parse(e);return r.version=t,`${JSON.stringify(r,null,Xl(e))}
155
- `}function Xl(e){let t=e.match(/^[\t ]+/m);return t?t[0]:_l}var ta="catalog:",ra="workspace:",na="default",Ql=2,ep=new Set(["*","^","~"]);function ia(e){let t=Array.isArray(e.workspaces)?void 0:e.workspaces,r={[na]:{...e.catalog,...t?.catalog}};return Object.assign(r,e.catalogs,t?.catalogs),r}function sa(e){let t={};for(let r of e)t[r.name]={isPrivate:r.isPrivate,version:r.version||null};return t}function tp(e,t,r,n){let i=t.slice(ta.length)||na,s=r[i]?.[e];if(!s)throw new g(`Catalog "${i}" has no entry for "${e}" (required by ${n})`,"Add the entry to the root package.json catalog before publishing");return s}function rp(e,t,r,n){let i=t.slice(ra.length),s=r[e];if(!s)throw new g(`Workspace package "${e}" (required by ${n}) was not found in the workspace`,"Check the dependency name against your workspaces globs");if(s.isPrivate)throw new g(`"${n}" depends on private workspace package "${e}", which is not published to the registry`,`Move "${e}" to devDependencies (bundled CLIs do not need it at runtime) or publish it first`);if(!ep.has(i)){if(!i)throw new g(`Invalid workspace specifier "${t}" for "${e}" (required by ${n})`,"Use workspace:*, workspace:^, workspace:~, or workspace:<range>");return i}let a=s.version;if(!a)throw new g(`Workspace package "${e}" (required by ${n}) has no version in its package.json`,"Add a version field before publishing");return i==="*"?a:`${i}${a}`}function In(e,t,r,n){if(!e)return e;let i={};for(let[s,a]of Object.entries(e))if(a.startsWith(ta))i[s]=tp(s,a,t,n);else if(a.startsWith(ra))i[s]=rp(s,a,r,n);else i[s]=a;return i}function np(e,t,r){let{devDependencies:n,...i}=e;return{...i,dependencies:In(e.dependencies,t,r,e.name),optionalDependencies:In(e.optionalDependencies,t,r,e.name),peerDependencies:In(e.peerDependencies,t,r,e.name)}}function aa(e,t,r){let n=JSON.parse(e),i=np(n,t,r),s=ip(e);return`${JSON.stringify(i,null,s)}
156
- `}function ip(e){let t=e.match(/^[\t ]+/m);return t?t[0]:Ql}class Ln{config;provider=null;constructor(e){this.config=e}async analyze(e){let t=await this.getProvider(),r=e?await this.fetchFromUrl(t,e):await this.fetchFromCurrentBranch(t),n=this.config.get("single"),{packages:i}=await O.scan({single:n}),s=wr(i),a={isSinglePackage:n,packagePaths:s,provider:t,url:e},{commits:o,affectedPackages:c}=r.merged?await this.analyzeAfterMerge(r,a):await this.analyzeBeforeMerge(r,a),p=this.inferBumpFromLabels(r.labels)??this.inferBumpFromTitle(r.title);return{commits:o,packages:c,pr:r,suggestedBump:p}}async analyzeBeforeMerge(e,t){let r=await J.inRange(e.baseBranch,e.branch);return this.processCommits(r,t)}async analyzeAfterMerge(e,t){if(await this.detectMergeMethod(e.mergeCommitSha)==="squash")return this.analyzeSquashMerge(e,t);return this.analyzeMergeCommit(e,t)}async analyzeSquashMerge(e,t){let r=t.url?await this.fetchFilesFromApi(t.provider,t.url):await this.getFilesFromCommit(e.mergeCommitSha),n=kt(r,t.packagePaths,t.isSinglePackage),i={body:e.body||void 0,hash:e.mergeCommitSha?.slice(0,cr)??Ds,message:e.title,packages:[...n],subject:e.title,type:this.inferCommitType(e.title)};return{affectedPackages:n,commits:[i]}}async analyzeMergeCommit(e,t){if(!e.mergeCommitSha)return{affectedPackages:new Set,commits:[]};let r=await J.fromMerge(e.mergeCommitSha);return this.processCommits(r,t)}processCommits(e,t){let r=[],n=new Set;for(let i of e){let s=kt(i.files,t.packagePaths,t.isSinglePackage);if(s.size===0)continue;r.push(i.toInfo([...s]));for(let a of s)n.add(a)}return{affectedPackages:n,commits:r}}async detectMergeMethod(e){if(!e)return"squash";if(await this.getCommitParentCount(e)===2)return"merge";return"squash"}async getCommitParentCount(e){try{let t=await Bun.$`git rev-parse ${e}^@`.quiet().nothrow();if(t.exitCode!==0)return 1;return t.stdout.toString().trim().split(`
157
- `).filter(Boolean).length}catch{return 1}}inferCommitType(e){return e.match(/^(\w+)(?:\(.*?\))?!?:/)?.[1]??Me}async getProvider(){if(!this.provider)this.provider=await it();return this.provider}async fetchFilesFromApi(e,t){let r=yn(t);if(!r)return[];return e.getPrFiles(r.number)}async fetchFromCurrentBranch(e){let t=await e.getPrFromCurrentBranch();return this.mapPullRequest(t)}async fetchFromUrl(e,t){let r=yn(t);if(!r)throw new g("Invalid PR URL","Expected a PR/MR URL from GitHub, GitLab, or Bitbucket");if(r.provider!==e.name)throw new g(`PR URL is from ${r.provider}, but repository is on ${e.name}`,"Make sure the PR URL matches the repository provider");let n=await e.getPr(r.number);return this.mapPullRequest(n)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping;for(let r of e){let n=r.toLowerCase();for(let[i,s]of Object.entries(t))if(n===i.toLowerCase())return s}return null}inferBumpFromTitle(e){let t=e.toLowerCase();if(t.includes("breaking")||e.includes("!:"))return"major";if(t.includes("feat")||t.includes("feature"))return"minor";if(t.includes("fix")||t.includes("bug"))return"patch";return null}async getFilesFromCommit(e){if(!e)return[];try{return(await Bun.$`git diff-tree --no-commit-id --name-only -r ${e}`.quiet()).stdout.toString().trim().split(`
158
- `).filter(Boolean)}catch{return[]}}}import{mkdtemp as Og,readFile as Mg,rm as Co}from"fs/promises";import{tmpdir as Dg}from"os";import{dirname as bi,join as Pi,resolve as Fg}from"path";import{dirname as sp,join as ap}from"path";function oa(e,t,r){let n=r.map((s)=>`- ${s.name}@${s.newVersion??s.version}`).join(`
159
- `);return`${e.replace("{message}",()=>t.message).replace("{packages}",()=>r.map((s)=>s.name).join(", "))}
160
-
161
- ${n}`}function ca(e){let{author:t,email:r}=e,n=t.trim(),i=r?.trim()??"";if(!n&&!i)return[];if(!n||!/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(i))throw new g("Invalid release commit author","Set valid commit.author and commit.email");return["--author",`${n} <${i}>`]}function la(e){let{author:t,email:r}=e,n={...process.env};if(!t)return n;if(n.GIT_COMMITTER_NAME=t,r)n.GIT_COMMITTER_EMAIL=r;return n}function pa(e,t){let{filename:r,root:n}=e,i=t.map((s)=>ap(sp(s.file),r));if(n)i.push(r);return i}import{mkdtemp as bp,rm as Pp}from"fs/promises";import{tmpdir as vp}from"os";import{join as Sa}from"path";import{createHash as dp}from"crypto";import{lstat as fp,realpath as Pa}from"fs/promises";import{dirname as hp,isAbsolute as wp,relative as va,resolve as Fn,sep as yp}from"path";import{createHash as yr}from"crypto";import{constants as ga}from"fs";import{lstat as op,open as cp,readlink as ua}from"fs/promises";import{isAbsolute as lp,relative as An,resolve as Se,sep as xn}from"path";var On=new Set(["100644","100755"]),lt="120000",St="160000",da=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;async function Pr(e){let t=await Bun.$`git rev-parse --show-toplevel`.quiet(),r=Se(t.stdout.toString().trim()),n=Se(r,e),i=An(r,n);if(!i||ae(i))throw new g("Sisyphus directory is outside the repository","Use a repository-relative sisyphusDir");let s=i.split(xn).join("/"),a=await pp(r,s),o=yr("sha256");for(let c of a){if(c.kind==="tracked"&&!gp(c.mode))throw new g(`Release source has unsupported Git mode ${c.mode}: ${c.path}`);let p=await wa(r,c.path),m=await Dn(p);if(o.update(c.path),o.update("\x00"),o.update(c.kind),o.update("\x00"),!m){if(c.kind==="tracked"&&c.mode===St)throw new g(`Release source gitlink is not initialized: ${c.path}`);o.update("deleted")}else if(c.kind==="untracked"||On.has(c.mode)){if(!m.isFile()||m.isSymbolicLink())throw new g(`Release source path is not a regular file: ${c.path}`);await mp(o,p,c.path)}else if(c.mode===lt){if(!m.isSymbolicLink())throw new g(`Release source path does not match Git mode ${lt}: ${c.path}`);o.update(yr("sha256").update(await ua(p,{encoding:"buffer"})).digest("hex")),o.update(lt)}else{if(!m.isDirectory()||m.isSymbolicLink())throw new g(`Release source path does not match Git mode ${St}: ${c.path}`);o.update(await ba(r,p,c)),await Mn(p),o.update(St)}o.update("\x00")}return o.digest("hex")}async function Mn(e=process.cwd()){let t=await Bun.$`git rev-parse --show-toplevel`.cwd(e).quiet(),r=Se(t.stdout.toString().trim());await fa(r)}async function fa(e){let[t,r]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -v -z --cached`.cwd(e).quiet()]),n=new Set,i=new Map;for(let s of br(r.stdout)){let a=s.slice(0,1),o=s.slice(2);if(!a||s.slice(1,2)!==" "||!o)throw new g("Unable to parse Git index flags while validating release source");i.set(o,a)}for(let s of br(t.stdout)){let a=ha(s);if(a.stage!=="0")throw new g(`Release source has an unresolved index entry: ${a.path}`);if(n.has(a.path))throw new g(`Release source has duplicate index entries: ${a.path}`);if(n.add(a.path),i.get(a.path)!=="H")throw new g(`Release source index flags hide working tree changes: ${a.path}`);let o={kind:"tracked",mode:a.mode,objectId:a.objectId,path:a.path},c=await wa(e,a.path),p=await Dn(c);if(!p)throw new g(`Release source path is missing: ${a.path}`);if(On.has(a.mode)){if(!p.isFile()||p.isSymbolicLink())throw new g(`Release source path is not a regular file: ${a.path}`);let u=(await Bun.$`git hash-object ${`--path=${a.path}`} ${c}`.cwd(e).quiet()).stdout.toString().trim(),f=p.mode&73?"100755":"100644";if(u!==a.objectId||f!==a.mode)throw new g(`Release source path differs from the Git index: ${a.path}`);continue}if(a.mode===lt){if(!p.isSymbolicLink())throw new g(`Release source path does not match Git mode ${lt}: ${a.path}`);let m=await Bun.$`git cat-file blob ${a.objectId}`.cwd(e).quiet(),u=await ua(c,{encoding:"buffer"});if(!Buffer.from(m.stdout).equals(u))throw new g(`Release source symlink differs from the Git index: ${a.path}`);continue}if(a.mode!==St)throw new g(`Release source has unsupported Git mode ${a.mode}: ${a.path}`);if(!p.isDirectory()||p.isSymbolicLink())throw new g(`Release source gitlink is not initialized: ${a.path}`);await ba(e,c,o),await fa(c)}}function vr(e,t){return yr("sha256").update(JSON.stringify(pt({...e,stones:t}))).digest("hex")}function pt(e){if(Array.isArray(e))return e.map(pt);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,pt(r)]))}function ae(e){return e===".."||e.startsWith(`..${xn}`)||lp(e)}async function pp(e,t){let[r,n]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -z --others --exclude-standard`.cwd(e).quiet()]),i=[],s=new Set;for(let a of br(r.stdout)){let o=ha(a);if(ma(o.path,t))continue;if(o.stage!=="0")throw new g(`Release source has an unresolved index entry: ${o.path}`);if(s.has(o.path))throw new g(`Release source has duplicate index entries: ${o.path}`);s.add(o.path),i.push({kind:"tracked",mode:o.mode,objectId:o.objectId,path:o.path})}for(let a of br(n.stdout)){if(ma(a,t))continue;if(s.has(a))throw new g(`Release source path is both tracked and untracked: ${a}`);s.add(a),i.push({kind:"untracked",path:a})}return i.sort((a,o)=>a.path<o.path?-1:a.path>o.path?1:0)}function br(e){let t=e.toString();if(!Buffer.from(t).equals(e))throw new g("Release source contains paths that are not valid UTF-8");return t.split("\x00").filter(Boolean)}function ha(e){let t=e.indexOf("\t");if(t<0)throw new g("Unable to parse Git index entry while hashing release source");let[r,n,i,...s]=e.slice(0,t).split(" "),a=e.slice(t+1);if(!r||!/^[0-7]{6}$/.test(r)||!n||!da.test(n)||!i||s.length>0||!a)throw new g("Unable to parse Git index entry while hashing release source");return{mode:r,objectId:n,path:a,stage:i}}function ma(e,t){return e===t||e.startsWith(`${t}/`)}function gp(e){return On.has(e)||e===lt||e===St}async function wa(e,t){let r=t.split("/"),n=Se(e,t),i=An(e,n);if(r.some((a)=>!a||a==="."||a==="..")||ae(i)||i.split(xn).join("/")!==t)throw new g(`Release source path escapes the repository: ${t}`);let s=e;for(let a of r.slice(0,-1)){s=Se(s,a);let o=await Dn(s);if(!o)break;if(!o.isDirectory()||o.isSymbolicLink())throw new g(`Release source path has an unsafe parent: ${t}`)}return n}async function Dn(e){try{return await op(e)}catch(t){if(ya(t,"ENOENT"))return null;throw t}}function ya(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function mp(e,t,r){let n=await cp(t,ga.O_RDONLY|ga.O_NOFOLLOW).catch((i)=>{if(ya(i,"ELOOP"))throw new g(`Release source path is not a regular file: ${r}`);throw i});try{let i=await n.stat();if(!i.isFile())throw new g(`Release source path is not a regular file: ${r}`);e.update(yr("sha256").update(await n.readFile()).digest("hex")),e.update(i.mode&73?"100755":"100644")}finally{await n.close()}}async function ba(e,t,r){let[n,i,s,a]=await Promise.all([Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet(),Bun.$`git rev-parse --show-superproject-working-tree`.cwd(t).quiet(),Bun.$`git rev-parse --absolute-git-dir`.cwd(t).quiet(),Bun.$`git rev-parse --git-path modules`.cwd(e).quiet()]),o=Se(n.stdout.toString().trim()),c=i.stdout.toString().trim(),p=c?Se(c):null,m=Se(s.stdout.toString().trim()),u=Se(e,a.stdout.toString().trim()),f=An(u,m);if(o!==t||p!==e||!f||ae(f))throw new g(`Release source gitlink is not initialized: ${r.path}`);if((await Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(t).quiet()).stdout.byteLength>0)throw new g(`Release source gitlink is dirty: ${r.path}`,"Commit or discard submodule changes before releasing");let P=(await Bun.$`git rev-parse --verify HEAD`.cwd(t).quiet()).stdout.toString().trim();if(!da.test(P))throw new g(`Release source gitlink has an invalid object ID: ${r.path}`);if(P!==r.objectId)throw new g(`Release source gitlink does not match the recorded commit: ${r.path}`,"Check out the submodule commit recorded by the repository before releasing");return r.objectId}async function x(e,t){try{return await e()}catch(r){let n=Rr(r);throw Error(n?`${t}: ${n}`:t)}}function Rr(e){let t=up(e);if(t)return t;return e instanceof Error?e.message:String(e)}function up(e){if(e&&typeof e==="object"&&"stderr"in e){let t=e.stderr;if(t instanceof Buffer)return t.toString().trim();if(typeof t==="string")return t.trim()}return}function Fe(e){return`:(top,literal)${e}`}async function oe(){let t=(await x(()=>Bun.$`git rev-parse HEAD`.quiet(),"Failed to resolve release commit")).stdout.toString().trim();if(!t)throw Error("Release commit is empty");return t}async function jn(){let e=await Bun.$`git symbolic-ref -q HEAD`.quiet().nothrow();if(e.exitCode===1)return null;if(e.exitCode!==0)throw new g("Failed to resolve the current Git reference");return e.stdout.toString().trim()||null}async function Ra(e){let t=await Bun.$`git rev-parse --verify ${e}`.quiet().nothrow();if(t.exitCode!==0)return null;return t.stdout.toString().trim()||null}async function Nn(e){let t=e.map((a)=>Fe(a)),[r,n,i]=await Promise.all([Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${t}`.quiet(),Bun.$`git diff --cached --binary --no-ext-diff -- ${t}`.quiet(),Bun.$`git diff --binary --no-ext-diff -- ${t}`.quiet()]),s=dp("sha256");for(let a of[r.stdout,n.stdout,i.stdout])s.update(String(a.length)),s.update("\x00"),s.update(a);return s.digest("hex")}function ka(e,t){let r=wp(t)?Fn(t):Fn(e,t),n=va(e,r);if(!n||ae(n))throw new g(`Release-owned path is outside the repository: ${t}`);return n.split(yp).join("/")}async function $a(e,t){let r=await Pa(t);for(let n of e){let i=Fn(t,n),s=await fp(i).catch(()=>null);if(s?.isSymbolicLink())throw new g(`Release-owned path is a symbolic link: ${n}`);let a=s?i:hp(i),o=await Pa(a);if(ae(va(r,o)))throw new g(`Release-owned path escapes the repository: ${n}`)}}async function Tn(e){let t=e.map((r)=>Fe(r));await x(()=>Bun.$`git reset --quiet HEAD -- ${t}`.quiet(),"Failed to unstage release-owned files")}async function kr(e){if((await $r(e)).length===0)return;throw new g("Repository source files changed after the release commit","Commit or stash all source changes before preparing npm artifacts")}async function $r(e){return await Mn(e),(await x(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(e).quiet(),"Failed to inspect release source files")).stdout}async function Ca(e,t,r,n){let i=[];if(e)i.push(`update ${e.ref??"HEAD"} ${e.baseCommit} ${e.oid}`);for(let o of t){let c=r.get(o);if(!c)throw Error(`Missing rollback target for release tag ${o}`);i.push(`delete refs/tags/${o} ${c}`)}if(i.length===0)return;let s=await n(),a=Buffer.from(["start",...i,"prepare","commit",""].join(`
162
- `));await x(async()=>{let o=Bun.spawn(["git","update-ref","--stdin"],{cwd:s,stderr:"pipe",stdin:a,stdout:"pipe"}),[c,p]=await Promise.all([o.exited,new Response(o.stderr).text()]);if(c!==0)throw Error(p.trim()||`git update-ref exited with code ${c}`)},"Failed to atomically restore release refs")}async function Ea(e,t,r){let n=await bp(Sa(vp(),"sisyphus-index-")),i=Sa(n,"index"),s={...process.env,GIT_INDEX_FILE:i},a=t.map((o)=>Fe(o));try{await x(()=>Bun.$`git read-tree ${e}`.cwd(r).env(s).quiet(),"Failed to initialize release tree"),await x(()=>Bun.$`git add -A -- ${a}`.cwd(r).env(s).quiet(),"Failed to build release tree");let c=(await x(()=>Bun.$`git write-tree`.cwd(r).env(s).quiet(),"Failed to write release tree")).stdout.toString().trim();if(!c)throw Error("Git returned an empty release tree object ID");return c}finally{await Pp(n,{force:!0,recursive:!0})}}async function Ia(e){if(!e.releaseCommit)throw new g(`Release ${e.id} has no recorded source commit`,"No external operation will be retried; inspect the local release state manually");let t=await oe();if(t!==e.releaseCommit)throw new g(`Release ${e.id} was prepared from ${e.releaseCommit}, but HEAD is ${t}`,`Check out ${e.releaseCommit} before resuming`);if(!e.expectedReleaseTree)throw new g(`Release ${e.id} has no recorded expected release tree`,"No external operation will be retried; inspect the release ledger manually");await gt(e,t)}async function gt(e,t){if(!e.expectedReleaseTree)throw new g(`Release ${e.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");if(e.options.publishOnly){if(t!==e.baseCommit)throw new g(`Publish-only release ${e.id} must use commit ${e.baseCommit}, found ${t}`,`Check out ${e.baseCommit} before resuming`)}else await Bn(t,e.baseCommit,e.id);await Un(t,e.expectedReleaseTree,e.id)}async function Bn(e,t,r){let n=await x(()=>Bun.$`git rev-list --parents -n 1 ${e}`.quiet(),"Failed to resolve release commit parent"),[i,...s]=n.stdout.toString().trim().split(/\s+/);if(i===e&&s.length===1&&s[0]===t)return;let a=r?` for release ${r}`:"";throw new g(`Release commit parent${a} does not match ${t}`,"No external operation was attempted; inspect the release commit ancestry")}async function Un(e,t,r){let n=await Gn(e);if(n===t)return;let i=r?` for release ${r}`:"";throw new g(`Release commit tree${i} is ${n}, expected ${t}`,"No external operation was attempted; inspect the release commit for unrelated tracked changes")}async function Gn(e){let t=`${e}^{tree}`,n=(await x(()=>Bun.$`git rev-parse ${t}`.quiet(),"Failed to resolve release commit tree")).stdout.toString().trim();if(!n)throw Error(`Git returned an empty tree object ID for ${e}`);return n}import{cp as Rp,mkdir as kp,mkdtemp as $p,rename as Cp,rm as Sp,writeFile as Ep}from"fs/promises";import{tmpdir as Ip}from"os";import{dirname as Aa,join as La,relative as Hn,resolve as je,sep as Lp}from"path";var Cr=512,Ap=100,xp=124,Op=12,Mp=345,Dp=155,Fp="package/package.json",jp=20;async function xa(e,t){let r=Aa(t),n=await Bun.$`npm pack --ignore-scripts --json --pack-destination ${r}`.cwd(e).quiet(),s=JSON.parse(n.stdout.toString())[0];if(typeof s?.filename!=="string"||!s.filename||typeof s.name!=="string"||!s.name||typeof s.version!=="string"||!s.version)throw Error("npm pack did not return a valid artifact identity");let a=je(r,s.filename);if(ae(Hn(r,a)))throw Error("npm pack returned an artifact outside the destination directory");if(a!==je(t))await Cp(a,t);return{name:s.name,version:s.version}}async function Oa(e,t){let r=await Bun.$`npm pack --dry-run --ignore-scripts --json`.cwd(t).quiet(),i=JSON.parse(r.stdout.toString())[0]?.files;if(!Array.isArray(i))throw Error(`npm pack did not return a file list for ${e.name}`);return i.map((s)=>{if(typeof s!=="object"||s===null||Array.isArray(s)||!("path"in s))throw Error(`npm pack returned an invalid file entry for ${e.name}`);let a=s.path;if(typeof a!=="string"||!a)throw Error(`npm pack returned an invalid file path for ${e.name}`);if(ae(Hn(t,je(t,a))))throw new g(`Package ${e.name} includes a file outside its directory: ${a}`);return a})}async function Ma(e,t,r){let n=await Oa(e,t),i=await $p(La(Ip(),"sisyphus-package-stage-"));try{for(let s of n){let a=je(i,s);await kp(Aa(a),{recursive:!0}),await Rp(je(t,s),a,{errorOnExist:!0,force:!1,recursive:!1,verbatimSymlinks:!0})}return await Ep(La(i,"package.json"),r,"utf-8"),i}catch(s){try{await Sp(i,{force:!0,recursive:!0})}catch(a){throw AggregateError([s,a],"Failed to clean staged npm package")}throw s}}async function Da(e,t,r){let[n,i]=await Promise.all([Oa(e,t),ja(r)]);for(let s of n){let a=Hn(r,je(t,s)).split(Lp).join("/");if(!i.has(a))throw new g(`Package ${e.name} includes an untracked or ignored pre-build file: ${s}`)}}async function _n(e,t){let[r,n]=await Promise.all([Bun.$`git ls-files --others --ignored --exclude-standard -z`.cwd(e).quiet(),Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet()]),i=r.stdout.toString().split("\x00").filter(Boolean).filter((s)=>!s.split("/").includes("node_modules"));if(i.length>0){let s=i.slice(0,jp).map((o)=>`${t}${o}`),a=i.length-s.length;throw new g(`Repository contains ${i.length} ignored build input(s) outside node_modules`,`Remove ignored source and stale build outputs before preparing npm artifacts (preview with git clean -ndX):
163
- ${s.join(`
144
+ ${s}
145
+ </details>`}return r}}import{readdir as Go,readFile as Ho}from"fs/promises";import{join as nn}from"path";var tp=".changeset",rp="config.json",sp=kr(pt()),qo=0,on=1;class an{root;constructor(e=process.cwd()){this.root=e}get changesetDir(){return nn(this.root,tp)}async exists(){try{return await Go(this.changesetDir),!0}catch{return!1}}async parse(){let e=[],t=[],r=await this.findChangesetFiles();for(let n of r){let i=await this.parseFile(n);if(i)t.push(i);else e.push(`Failed to parse: ${n}`)}let s=await this.parseConfig();return{changesets:t,config:s,errors:e}}async findChangesetFiles(){try{return(await Go(this.changesetDir)).filter((t)=>t.endsWith(".md")&&t!=="README.md").map((t)=>nn(this.changesetDir,t))}catch{return[]}}async parseFile(e){try{let r=(await Ho(e,"utf-8")).split(`
146
+ `);if(r[qo]?.trim()!=="---")return null;let s=r.findIndex((a,c)=>c>qo&&a.trim()==="---");if(s<on)return null;let n=Bun.YAML.parse(r.slice(on,s).join(`
147
+ `));if(Array.isArray(n))return null;let i=sp(n);if(Object.keys(i).length===0)return null;return{filename:e.split("/").pop()??"",packages:i,summary:r.slice(s+on).join(`
148
+ `).trim()}}catch{return null}}async parseConfig(){try{let e=nn(this.changesetDir,rp),t=await Ho(e,"utf-8");return JSON.parse(t)}catch{return null}}toStoneData(e){let t=[],r=[],s=[],n=[];for(let[c,l]of Object.entries(e.packages))switch(l){case"major":t.push(c);break;case"minor":r.push(c);break;case"patch":s.push(c);break;default:n.push(`${c} uses an unsupported bump type "${l}"`)}if(n.length>0)throw new u(`Changeset ${e.filename}: ${n.join("; ")}`,"Rewrite them as major, minor, or patch before migrating");let i=e.summary.split(`
149
+ `),o=i[0]?.trim()||"Migrated from changeset";return{description:i.slice(1).join(`
150
+ `).trim()||void 0,major:Y(t),message:o,minor:Y(r),patch:Y(s)}}}function Fr(e){let t=new Map;for(let[r,s]of e){let n=s.file.replace(/\\/g,"/"),i=n.substring(0,n.lastIndexOf("/"))||".";t.set(i,r)}return t}function Ft(e,t,r=!0){let s=new Set;for(let n of e)for(let[i,o]of t){let a=i===".",c=n.startsWith(`${i}/`);if(a?r:c)s.add(o)}return s}var zo="*",Ko="^",cn="~",Wo=new Map;function ee(e,t){return t.some((r)=>r===e||up(e,r))}function ae(e,t){let r=e.get("dependents")??Fe.dependents;return{ignore:e.get("ignore")??[],kinds:r.kinds,tag:t,updateInternal:r.updateInternal}}function np(e,t,r){let s=e.slice(Br.length);if(s===zo)return t!==r;if(s!==Ko&&s!==cn)return!1;let n=Ie(t),i=Ie(r);if(!n||!i)return!0;if(Ae(n)||Ae(i))return!0;if(n.major!==i.major)return!0;if(s===cn)return n.minor!==i.minor;if(n.major!==0)return!1;if(n.minor!==0)return n.minor!==i.minor;return n.minor!==i.minor||n.patch!==i.patch}function bt(e,t,r){let s=r.ignore??[],n=cp(t,new Set(r.kinds),s),i=new Map,o=new Set,a=[];for(let c of[...e].sort((l,d)=>wt(l.name,d.name))){if(!t.has(c.name)||ee(c.name,s))continue;if(o.add(c.name),Jo(i,c.name,c.bump))Ur(a,c.name)}while(a.length>0){let c=a.shift();if(!c)continue;let l=t.get(c),d=i.get(c),g=n.get(c);if(!l||!d||!g)continue;let h=r.updateInternal==="outOfRange",f=Ie(l.version),m=f!==null&&Ae(f),y=h&&!m?me.bump(l.version,d,r.tag):l.version;for(let R of g){let S=m?ip(R.specifier):np(R.specifier,l.version,y);if(h&&!S)continue;if(Jo(i,R.dependent,"dependency"))Ur(a,R.dependent)}}return[...i.keys()].filter((c)=>!o.has(c)).sort(wt)}function ip(e){let t=e.slice(Br.length);return t===zo||t===Ko||t===cn}function ln(e,t){if(t.length===0)return{skipped:[],stone:e};let r=[],s=e;for(let n of Ee){let i=e.getPackages(n),o=i.filter((a)=>!ee(a,t));if(o.length===i.length)continue;r.push(...i.filter((a)=>!o.includes(a))),s=s.withPackages(n,o)}return{skipped:[...new Set(r)].sort(wt),stone:s}}function Yo(e,t){if(t.length===0)return{kept:[...e],skipped:[]};let r=[],s=[];for(let n of e)if(ee(n.name,t))s.push(n.name);else r.push(n);return{kept:r,skipped:s}}function Ut(e){let t=new Map(e.map((d)=>[d.name,d])),r=[...t.keys()].sort(wt),s=new Map,n=new Map,i=new Map;for(let d of r){let g=new Set((t.get(d)?.workspaceDependencies??[]).filter((h)=>h.kind!=="devDependencies").map((h)=>h.name).filter((h)=>h!==d&&t.has(h)));s.set(d,g.size),i.set(d,g);for(let h of g)n.set(h,[...n.get(h)??[],d])}let o=r.filter((d)=>s.get(d)===0),a=[],c=new Set,l=[];while(c.size<r.length){if(o.length===0){let h=op(r,c,n,i);if(!h)break;l.push(h),Ur(o,h)}let d=o.shift();if(!d||c.has(d))continue;c.add(d);let g=t.get(d);if(g)a.push(g);for(let h of n.get(d)??[]){if(c.has(h))continue;let f=(s.get(h)??0)-1;if(s.set(h,f),f===0)Ur(o,h)}}return{cycle:l,ordered:a}}function op(e,t,r,s){let n=ap(e,t,s),i=n.size>0?e.filter((c)=>n.has(c)):e,o,a=-1;for(let c of i){if(t.has(c))continue;let l=(r.get(c)??[]).filter((d)=>!t.has(d)).length;if(l<=a)continue;o=c,a=l}return o}function ap(e,t,r){let s=new Map,n=new Map,i=[],o=new Set,a=new Set,c=(l)=>{let d=s.size;s.set(l,d),n.set(l,d),i.push(l),o.add(l);for(let m of r.get(l)??[]){if(t.has(m))continue;if(!s.has(m))c(m),n.set(l,Math.min(n.get(l)??d,n.get(m)??d));else if(o.has(m))n.set(l,Math.min(n.get(l)??d,s.get(m)??d))}if(n.get(l)!==d)return;let g=new Set,h;do{if(h=i.pop(),h===void 0)break;o.delete(h),g.add(h)}while(h!==l);if([...g].some((m)=>[...r.get(m)??[]].some((y)=>!t.has(y)&&!g.has(y))))return;for(let m of g)a.add(m)};for(let l of e)if(!t.has(l)&&!s.has(l))c(l);return a}function cp(e,t,r){let s=new Map;for(let n of[...e.keys()].sort(wt)){if(ee(n,r))continue;for(let i of e.get(n)?.workspaceDependencies??[]){if(!lp(i,t,e,r))continue;s.set(i.name,[...s.get(i.name)??[],{dependent:n,specifier:i.specifier}])}}return s}function lp(e,t,r,s){if(!t.has(e.kind))return!1;if(!r.has(e.name))return!1;return!ee(e.name,s)}function Jo(e,t,r){let s=e.get(t),n=s===void 0?r:Lr(s,r);if(s!==void 0&&n===s)return!1;return e.set(t,n),!0}function Ur(e,t){if(e.includes(t))return;let r=e.findIndex((s)=>wt(s,t)>0);if(r<0)e.push(t);else e.splice(r,0,t)}function wt(e,t){if(e===t)return 0;return e<t?-1:1}function up(e,t){let r=Wo.get(t);if(!r)r=new Bun.Glob(t),Wo.set(t,r);return r.match(e)}import{existsSync as vt}from"fs";import{mkdir as Xo,readdir as un,readFile as Zo,unlink as Qo,writeFile as ea}from"fs/promises";import{dirname as pp,join as Vt,resolve as ta}from"path";var ra=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,sa=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;class E{config;constructor(e){this.config=e}get sisyphusDir(){return this.config.get("sisyphusDir")||mt}get stonesPath(){return this.config.get("stonesPath")||Vt(this.sisyphusDir,bo)}get releasedPath(){return Vt(this.sisyphusDir,vo)}async list(){let e=await this.listIds(),t=[];for(let r of e){let s=await this.get(r);if(s)t.push(s)}return t}async listIds(){return await this.ensureStorageExists(),(await un(this.stonesPath)).filter((t)=>t.endsWith(".json")).map((t)=>this.toStoneId(t)).sort()}async get(e){let t=this.getFilePath(e);if(!vt(t))return null;let r=await Zo(t,"utf-8"),s=this.parseStoneJson(r,t);if(s.id!==e)throw Error(`Stone file ID mismatch: expected "${e}", found "${String(s.id)}"`);return A.fromJson(s)}parseStoneJson(e,t){try{return JSON.parse(e)}catch{throw new u(`Failed to parse stone file ${t}`,"Remove or fix the file")}}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),r=JSON.stringify(e.toJson(),null,2);await ea(t,r,"utf-8"),this.addToConfigStones(e.id)}async delete(e){let t=this.getFilePath(e);if(!vt(t))return!1;return await Qo(t),this.removeFromConfigStones(e),!0}async deleteMany(e){let t=0;for(let r of e)if(await this.delete(r))t++;return t}async create(e){let t=await this.listIds(),r=A.create(e,t.length);return await this.save(r),r}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),r=Vt(this.releasedPath,t);await Xo(r,{recursive:!0});for(let s of e){let n=this.getFilePath(s.id),i=Vt(r,`${s.id}.json`);if(vt(n))await ea(i,JSON.stringify(s.toJson(),null,2),"utf-8"),await Qo(n),this.removeFromConfigStones(s.id)}return t}async getReleasedStones(e,t){let r=this.getArchivePath(e);if(!vt(r))return[];let n=(await un(r)).filter((a)=>a.endsWith(".json")).sort(),i=t?.map((a)=>`${this.validateId(a)}.json`).sort();if(i&&JSON.stringify(n)!==JSON.stringify(i))throw Error(`Released stone archive ${e} does not match currentRelease: expected ${i.join(", ")||"no stones"}, found ${n.join(", ")||"no stones"}`);let o=[];for(let a of n)try{let c=this.validateId(a.slice(0,-5)),l=Vt(r,a),d=await Zo(l,"utf-8"),g=this.parseStoneJson(d,l);if(g.id!==c)throw Error(`Stone file ID mismatch: expected "${c}", found "${String(g.id)}"`);o.push(A.fromJson(g))}catch(c){if(t)throw c;v.warn(p.dim(`Failed to parse stone "${a}": ${c}`))}return o}async listReleasedTimestamps(){if(!vt(this.releasedPath))return[];return(await un(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()&&sa.test(t.name)).map((t)=>t.name)}async getTrackedCommitPackages(){let e=await this.list(),t=new Map;for(let r of e.flatMap((s)=>s.commits??[])){let s=t.get(r.hash)??new Set;for(let n of r.packages)s.add(n);t.set(r.hash,s)}return t}getFilePath(e){let t=this.validateId(e);return this.resolveChildPath(this.stonesPath,`${t}.json`,`Stone path must be a direct child of the stones directory: ${e}`)}getFilePaths(e){return e.map((t)=>this.getFilePath(t.id))}createTimestamp(){return new Date().toISOString().replace(/[:.]/g,"-")}getArchivePath(e){if(!sa.test(e))throw Error(`Invalid released stone timestamp "${e}"`);return this.resolveChildPath(this.releasedPath,e,`Released stone archive must be a direct child of the released directory: ${e}`)}resolveChildPath(e,t,r){let s=ta(e),n=ta(s,t);if(pp(n)!==s)throw Error(r);return n}validateId(e){if(!ra.test(e))throw Error(`Invalid stone ID "${e}"`);return e}toStoneId(e){let t=e.slice(0,-5);if(ra.test(t))return t;throw new u(`Invalid stone ID "${t}" from stone file ${e} in ${this.stonesPath}`,"Remove or rename the file; stone files must match <seq>-<hash>.json")}async ensureStorageExists(){if(!vt(this.stonesPath))await Xo(this.stonesPath,{recursive:!0})}addToConfigStones(e){let t=this.config.getAll();if(!t.stones.includes(e))this.config.set("stones",[...t.stones,e])}removeFromConfigStones(e){let t=this.config.getAll(),r=t.stones.filter((s)=>s!==e);if(r.length!==t.stones.length)this.config.set("stones",r)}}class F{static async scan(e={}){let{filter:t,single:r}=e;if(r)return F.scanRootPackage(t);let s=await F.getWorkspaces();F.validateWorkspaces(s);let n=await F.scanWorkspaces(s);return{packageNames:F.filterNames(Array.from(n.keys()),t),packages:n}}static async getWorkspaces(){try{let t=(await Bun.file("package.json").json())?.workspaces;if(Array.isArray(t))return t;return t?.packages||[]}catch{throw new u("Could not read package.json","Ensure you're in a project root directory.")}}static validateWorkspaces(e){if(e.length===0)throw new u("No workspaces found in package.json.","Use --single flag or set `single: true` in config for single-package mode.")}static filterNames(e,t){if(!t)return e;return e.filter((r)=>r.includes(t))}static async scanRootPackage(e){let t=await Bun.file("package.json").json(),r=z.fromJson(t,"package.json"),s=new Map;return s.set(r.name,r),{packageNames:F.filterNames([r.name],e),packages:s}}static async scanWorkspaces(e){let t=new Map;for(let r of e){let s=new Bun.Glob(`${r}/package.json`).scanSync({cwd:process.cwd()});for(let n of s){let i=await Bun.file(n).json(),o=z.fromJson(i,n);t.set(o.name,o)}}return t}}var dp={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[Be]:"patch"};class et{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new E(e)}async analyze(e={}){let t=await this.getCommitsSinceLastRelease();if(t.length===0)return[];let r=this.config.get("commits")?.skip??Fe.commits.skip;if(t=t.filter((n)=>!this.shouldSkipCommit(n,r)),t.length===0)return[];let s=await this.stoneManager.getTrackedCommitPackages();return this.groupByPackage(t,e,s)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;for(let r of t.messagePatterns)try{if(new RegExp(r,"i").test(e.subject))return!0}catch{v.warn(p.yellow(`Invalid regex pattern in commits.skip.messagePatterns: "${r}"`))}return!1}async getCommitsSinceLastRelease(){let t=this.config.get("lastStone")?.commit||void 0;if(!t)return[];return J.since(t)}async groupByPackage(e,t,r){let{packages:s,packageNames:n}=await F.scan({filter:t.filter,single:t.single}),i=this.config.get("ignore")??[],o=new Set(n.filter((d)=>!ee(d,i))),a=new Map([...s].filter(([d])=>o.has(d))),c=Fr(a),l=new Map;for(let d of e){let g=Ft(d.files,c);for(let y of r.get(d.shortHash)??[])g.delete(y);if(g.size===0)continue;let h=d.breaking?"major":dp[d.type]||"patch",f=`${d.type}${d.breaking?"!":""}`,m=l.get(f);if(!m){let y=this.getGroupMessage(d);m={bump:h,commits:[],message:y,packages:new Set},l.set(f,m)}m.commits.push(d.toInfo([...g]));for(let y of g)m.packages.add(y)}return Array.from(l.entries()).sort(([d],[g])=>(dt[d]??gt)-(dt[g]??gt)).map(([,d])=>d)}getGroupMessage(e){let t=this.config.get("changelog").sections;if(e.breaking)return t.breaking;return t[e.type]??`${e.type} updates`}static buildStoneData(e,t,r){let s=Array.from(e.packages),n=s.map((i)=>({bump:e.bump,name:i}));return{[e.bump]:s,commits:Y(e.commits),dependency:Y(bt(n,t,r)),message:e.message,tag:r.tag}}}import{readFile as gp,writeFile as na}from"fs/promises";var mp=2,hp=1,fp='"version"';class Gt{originals=new Map;async updateAll(e){this.originals.clear();for(let t of e)await this.updatePackage(t)}async rollback(){for(let[e,t]of this.originals)await na(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;Dr(t,`write the new version of ${e.name}`);let r=await gp(e.file,"utf-8");this.originals.set(e.file,r),await na(e.file,yp(r,t),"utf-8")}}function yp(e,t){let r=wp(e);if(!r)return $p(e,t);return`${e.slice(0,r.start)}${JSON.stringify(t)}${e.slice(r.end)}`}function wp(e){let t=0,r=0;while(r<e.length){let s=e[r];if(s==='"'){let n=pn(e,r);if(t===hp&&e.slice(r,n)===fp&&!vp(e,r)){let o=bp(e,n);if(o!==null&&e[o]==='"')return{end:pn(e,o),start:o};return null}r=n;continue}if(s==="{"||s==="[")t+=1;if(s==="}"||s==="]")t-=1;r+=1}return null}function pn(e,t){let r=t+1;while(r<e.length){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r+1;r+=1}return r}function bp(e,t){let r=t;while(r<e.length&&/\s/.test(e[r]??""))r+=1;if(e[r]!==":")return null;r+=1;while(r<e.length&&/\s/.test(e[r]??""))r+=1;return r}function vp(e,t){let r=[],s=0;while(s<t){let n=e[s];if(n==='"'){s=pn(e,s);continue}if(n==="{"||n==="[")r.push(n);if(n==="}"||n==="]")r.pop();s+=1}return r[r.length-1]==="["}function $p(e,t){let r=JSON.parse(e);return r.version=t,`${JSON.stringify(r,null,Pp(e))}
151
+ `}function Pp(e){let t=e.match(/^[\t ]+/m);return t?t[0]:mp}var ia="catalog:",oa="workspace:",aa="default",Rp=2,Sp=new Set(["*","^","~"]);function ca(e){let t=Array.isArray(e.workspaces)?void 0:e.workspaces,r={[aa]:{...e.catalog,...t?.catalog}};return Object.assign(r,e.catalogs,t?.catalogs),r}function la(e){let t={};for(let r of e)t[r.name]={isPrivate:r.isPrivate,version:r.version||null};return t}function Cp(e,t,r,s){let n=t.slice(ia.length)||aa,i=r[n]?.[e];if(!i)throw new u(`Catalog "${n}" has no entry for "${e}" (required by ${s})`,"Add the entry to the root package.json catalog before publishing");return i}function kp(e,t,r,s){let n=t.slice(oa.length),i=r[e];if(!i)throw new u(`Workspace package "${e}" (required by ${s}) was not found in the workspace`,"Check the dependency name against your workspaces globs");if(i.isPrivate)throw new u(`"${s}" depends on private workspace package "${e}", which is not published to the registry`,`Move "${e}" to devDependencies (bundled CLIs do not need it at runtime) or publish it first`);if(!Sp.has(n)){if(!n)throw new u(`Invalid workspace specifier "${t}" for "${e}" (required by ${s})`,"Use workspace:*, workspace:^, workspace:~, or workspace:<range>");return n}let o=i.version;if(!o)throw new u(`Workspace package "${e}" (required by ${s}) has no version in its package.json`,"Add a version field before publishing");return n==="*"?o:`${n}${o}`}function dn(e,t,r,s){if(!e)return e;let n={};for(let[i,o]of Object.entries(e))if(o.startsWith(ia))n[i]=Cp(i,o,t,s);else if(o.startsWith(oa))n[i]=kp(i,o,r,s);else n[i]=o;return n}function xp(e,t,r){let{devDependencies:s,...n}=e;return{...n,dependencies:dn(e.dependencies,t,r,e.name),optionalDependencies:dn(e.optionalDependencies,t,r,e.name),peerDependencies:dn(e.peerDependencies,t,r,e.name)}}function ua(e,t,r){let s=JSON.parse(e),n=xp(s,t,r),i=Tp(e);return`${JSON.stringify(n,null,i)}
152
+ `}function Tp(e){let t=e.match(/^[\t ]+/m);return t?t[0]:Rp}class gn{config;provider=null;constructor(e){this.config=e}async analyze(e){let t=await this.getProvider(),r=e?await this.fetchFromUrl(t,e):await this.fetchFromCurrentBranch(t),s=this.config.get("single"),{packages:n}=await F.scan({single:s}),i=Fr(n),o={isSinglePackage:s,packagePaths:i,provider:t},{commits:a,affectedPackages:c}=r.merged?await this.analyzeAfterMerge(r,o):await this.analyzeBeforeMerge(r,o),l=this.inferBumpFromLabels(r.labels)??this.inferBumpFromTitle(r.title);return{commits:a,packages:c,pr:r,suggestedBump:l}}async analyzeBeforeMerge(e,t){let r=await J.inRange(e.baseBranch,e.branch);return this.processCommits(r,t)}async analyzeAfterMerge(e,t){if(await this.detectMergeMethod(e.mergeCommitSha)==="squash")return this.analyzeSquashMerge(e,t);return this.analyzeMergeCommit(e,t)}async analyzeSquashMerge(e,t){let r=await t.provider.getPrCommits(e.number);if(e.mergeCommitSha&&r.includes(e.mergeCommitSha)){let o=await Promise.all(r.map((a)=>J.fromHash(a)));if(o.every((a)=>a!==null))return this.processCommits(o,t)}let s=await t.provider.getPrFiles(e.number);if(s.length===0)throw new u(`Could not determine changed files for PR #${e.number}`,"Check provider access and retry the analysis");let n=Ft(s,t.packagePaths,t.isSinglePackage),i={body:e.body||void 0,hash:e.mergeCommitSha?.slice(0,Tr)??$o,message:e.title,packages:[...n],subject:e.title,type:this.inferCommitType(e.title)};return{affectedPackages:n,commits:[i]}}async analyzeMergeCommit(e,t){if(!e.mergeCommitSha)return{affectedPackages:new Set,commits:[]};let r=await J.fromMerge(e.mergeCommitSha);return this.processCommits(r,t)}processCommits(e,t){let r=[],s=new Set;for(let n of e){let i=Ft(n.files,t.packagePaths,t.isSinglePackage);if(i.size===0)continue;r.push(n.toInfo([...i]));for(let o of i)s.add(o)}return{affectedPackages:s,commits:r}}async detectMergeMethod(e){if(!e)return"squash";if(await this.getCommitParentCount(e)===2)return"merge";return"squash"}async getCommitParentCount(e){try{let t=await Bun.$`git rev-parse ${e}^@`.quiet().nothrow();if(t.exitCode!==0)return 1;return t.stdout.toString().trim().split(`
153
+ `).filter(Boolean).length}catch{return 1}}inferCommitType(e){return e.match(/^(\w+)(?:\(.*?\))?!?:/)?.[1]??Be}async getProvider(){if(!this.provider)this.provider=await ht();return this.provider}async fetchFromCurrentBranch(e){let t=await e.getPrFromCurrentBranch();return this.mapPullRequest(t)}async fetchFromUrl(e,t){let r=To(t);if(!r)throw new u("Invalid PR URL","Expected a PR/MR URL from GitHub, GitLab, or Bitbucket");if(r.provider!==e.name)throw new u(`PR URL is from ${r.provider}, but repository is on ${e.name}`,"Make sure the PR URL matches the repository provider");let s=Xe(await Dt()??"");if(!s||s.owner.toLowerCase()!==r.owner.toLowerCase()||s.repo.toLowerCase()!==r.repo.toLowerCase())throw new u("PR URL does not match this repository","Use a PR/MR URL from the repository configured as origin");let n=await e.getPr(r.number);return this.mapPullRequest(n)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping;for(let r of e){let s=r.toLowerCase();for(let[n,i]of Object.entries(t))if(s===n.toLowerCase())return i}return null}inferBumpFromTitle(e){let t=e.toLowerCase();if(t.includes("breaking")||e.includes("!:"))return"major";if(t.includes("feat")||t.includes("feature"))return"minor";if(t.includes("fix")||t.includes("bug"))return"patch";return null}}import{mkdtemp as mg,readFile as hg,rm as Oc}from"fs/promises";import{tmpdir as fg}from"os";import{dirname as _c,join as oi,resolve as yg}from"path";var pa=Cr().map((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:Ye()),Ep=pa.map(Js({publishConfig:pa.map(Js({access:mo(["public","restricted"]).or(qs())})).or(qs())}));function Vr(e){try{return Ep(JSON.parse(e)).publishConfig?.access??"public"}catch(t){throw Error("Invalid publishConfig.access: expected public or restricted",{cause:t})}}import{rm as Xp}from"fs/promises";import{isAbsolute as Zp,resolve as Ea}from"path";import{createHash as Gr}from"crypto";import{constants as da}from"fs";import{lstat as Ip,open as Ap,readlink as ma}from"fs/promises";import{isAbsolute as Op,relative as mn,resolve as Oe,sep as hn}from"path";var fn=new Set(["100644","100755"]),$t="120000",Ht="160000",ha=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;async function qr(e){let t=await Bun.$`git rev-parse --show-toplevel`.quiet(),r=Oe(t.stdout.toString().trim()),s=Oe(r,e),n=mn(r,s);if(!n||ne(n))throw new u("Sisyphus directory is outside the repository","Use a repository-relative sisyphusDir");let i=n.split(hn).join("/"),o=await _p(r,i),a=Gr("sha256");for(let c of o){if(c.kind==="tracked"&&!Mp(c.mode))throw new u(`Release source has unsupported Git mode ${c.mode}: ${c.path}`);let l=await wa(r,c.path),d=await wn(l);if(a.update(c.path),a.update("\x00"),a.update(c.kind),a.update("\x00"),!d){if(c.kind==="tracked"&&c.mode===Ht)throw new u(`Release source gitlink is not initialized: ${c.path}`);a.update("deleted")}else if(c.kind==="untracked"||fn.has(c.mode)){if(!d.isFile()||d.isSymbolicLink())throw new u(`Release source path is not a regular file: ${c.path}`);await Lp(a,l,c.path)}else if(c.mode===$t){if(!d.isSymbolicLink())throw new u(`Release source path does not match Git mode ${$t}: ${c.path}`);a.update(Gr("sha256").update(await ma(l,{encoding:"buffer"})).digest("hex")),a.update($t)}else{if(!d.isDirectory()||d.isSymbolicLink())throw new u(`Release source path does not match Git mode ${Ht}: ${c.path}`);a.update(await va(r,l,c)),await yn(l),a.update(Ht)}a.update("\x00")}return a.digest("hex")}async function yn(e=process.cwd()){let t=await Bun.$`git rev-parse --show-toplevel`.cwd(e).quiet(),r=Oe(t.stdout.toString().trim());await fa(r)}async function fa(e){let[t,r]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -v -z --cached`.cwd(e).quiet()]),s=new Set,n=new Map;for(let i of Hr(r.stdout)){let o=i.slice(0,1),a=i.slice(2);if(!o||i.slice(1,2)!==" "||!a)throw new u("Unable to parse Git index flags while validating release source");n.set(a,o)}for(let i of Hr(t.stdout)){let o=ya(i);if(o.stage!=="0")throw new u(`Release source has an unresolved index entry: ${o.path}`);if(s.has(o.path))throw new u(`Release source has duplicate index entries: ${o.path}`);if(s.add(o.path),n.get(o.path)!=="H")throw new u(`Release source index flags hide working tree changes: ${o.path}`);let a={kind:"tracked",mode:o.mode,objectId:o.objectId,path:o.path},c=await wa(e,o.path),l=await wn(c);if(!l)throw new u(`Release source path is missing: ${o.path}`);if(fn.has(o.mode)){if(!l.isFile()||l.isSymbolicLink())throw new u(`Release source path is not a regular file: ${o.path}`);let g=(await Bun.$`git hash-object ${`--path=${o.path}`} ${c}`.cwd(e).quiet()).stdout.toString().trim(),h=l.mode&73?"100755":"100644";if(g!==o.objectId||h!==o.mode)throw new u(`Release source path differs from the Git index: ${o.path}`);continue}if(o.mode===$t){if(!l.isSymbolicLink())throw new u(`Release source path does not match Git mode ${$t}: ${o.path}`);let d=await Bun.$`git cat-file blob ${o.objectId}`.cwd(e).quiet(),g=await ma(c,{encoding:"buffer"});if(!Buffer.from(d.stdout).equals(g))throw new u(`Release source symlink differs from the Git index: ${o.path}`);continue}if(o.mode!==Ht)throw new u(`Release source has unsupported Git mode ${o.mode}: ${o.path}`);if(!l.isDirectory()||l.isSymbolicLink())throw new u(`Release source gitlink is not initialized: ${o.path}`);await va(e,c,a),await fa(c)}}function Wr(e,t){return Gr("sha256").update(JSON.stringify(Pt({...e,stones:t}))).digest("hex")}function Pt(e){if(Array.isArray(e))return e.map(Pt);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,Pt(r)]))}function ne(e){return e===".."||e.startsWith(`..${hn}`)||Op(e)}async function _p(e,t){let[r,s]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -z --others --exclude-standard`.cwd(e).quiet()]),n=[],i=new Set;for(let o of Hr(r.stdout)){let a=ya(o);if(ga(a.path,t))continue;if(a.stage!=="0")throw new u(`Release source has an unresolved index entry: ${a.path}`);if(i.has(a.path))throw new u(`Release source has duplicate index entries: ${a.path}`);i.add(a.path),n.push({kind:"tracked",mode:a.mode,objectId:a.objectId,path:a.path})}for(let o of Hr(s.stdout)){if(ga(o,t))continue;if(i.has(o))throw new u(`Release source path is both tracked and untracked: ${o}`);i.add(o),n.push({kind:"untracked",path:o})}return n.sort((o,a)=>o.path<a.path?-1:o.path>a.path?1:0)}function Hr(e){let t=e.toString();if(!Buffer.from(t).equals(e))throw new u("Release source contains paths that are not valid UTF-8");return t.split("\x00").filter(Boolean)}function ya(e){let t=e.indexOf("\t");if(t<0)throw new u("Unable to parse Git index entry while hashing release source");let[r,s,n,...i]=e.slice(0,t).split(" "),o=e.slice(t+1);if(!r||!/^[0-7]{6}$/.test(r)||!s||!ha.test(s)||!n||i.length>0||!o)throw new u("Unable to parse Git index entry while hashing release source");return{mode:r,objectId:s,path:o,stage:n}}function ga(e,t){return e===t||e.startsWith(`${t}/`)}function Mp(e){return fn.has(e)||e===$t||e===Ht}async function wa(e,t){let r=t.split("/"),s=Oe(e,t),n=mn(e,s);if(r.some((o)=>!o||o==="."||o==="..")||ne(n)||n.split(hn).join("/")!==t)throw new u(`Release source path escapes the repository: ${t}`);let i=e;for(let o of r.slice(0,-1)){i=Oe(i,o);let a=await wn(i);if(!a)break;if(!a.isDirectory()||a.isSymbolicLink())throw new u(`Release source path has an unsafe parent: ${t}`)}return s}async function wn(e){try{return await Ip(e)}catch(t){if(ba(t,"ENOENT"))return null;throw t}}function ba(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function Lp(e,t,r){let s=await Ap(t,da.O_RDONLY|da.O_NOFOLLOW).catch((n)=>{if(ba(n,"ELOOP"))throw new u(`Release source path is not a regular file: ${r}`);throw n});try{let n=await s.stat();if(!n.isFile())throw new u(`Release source path is not a regular file: ${r}`);e.update(Gr("sha256").update(await s.readFile()).digest("hex")),e.update(n.mode&73?"100755":"100644")}finally{await s.close()}}async function va(e,t,r){let[s,n,i,o]=await Promise.all([Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet(),Bun.$`git rev-parse --show-superproject-working-tree`.cwd(t).quiet(),Bun.$`git rev-parse --absolute-git-dir`.cwd(t).quiet(),Bun.$`git rev-parse --git-path modules`.cwd(e).quiet()]),a=Oe(s.stdout.toString().trim()),c=n.stdout.toString().trim(),l=c?Oe(c):null,d=Oe(i.stdout.toString().trim()),g=Oe(e,o.stdout.toString().trim()),h=mn(g,d);if(a!==t||l!==e||!h||ne(h))throw new u(`Release source gitlink is not initialized: ${r.path}`);if((await Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(t).quiet()).stdout.byteLength>0)throw new u(`Release source gitlink is dirty: ${r.path}`,"Commit or discard submodule changes before releasing");let y=(await Bun.$`git rev-parse --verify HEAD`.cwd(t).quiet()).stdout.toString().trim();if(!ha.test(y))throw new u(`Release source gitlink has an invalid object ID: ${r.path}`);if(y!==r.objectId)throw new u(`Release source gitlink does not match the recorded commit: ${r.path}`,"Check out the submodule commit recorded by the repository before releasing");return r.objectId}var Ue={isOutput:()=>!1};function bn(e){if(e.length===0)return Ue;let t=e.flatMap((r)=>{let s=r.endsWith("/")?`${r}**`:r;if(s.endsWith("**"))return[new Bun.Glob(s)];return[new Bun.Glob(s),new Bun.Glob(`${s}/**`)]});return{isOutput:(r)=>t.some((s)=>s.match(r))}}import{cp as Dp,mkdir as Np,mkdtemp as jp,rename as Bp,rm as Fp,writeFile as Up}from"fs/promises";import{tmpdir as Vp}from"os";import{dirname as Pa,join as $a,relative as $n,resolve as Ve,sep as Gp}from"path";var Jr=512,Hp=100,qp=124,Wp=12,Jp=345,zp=155,Kp="package/package.json",Yp=20;function Ra(e){let t=JSON.parse(e),r=Array.isArray(t)?t:typeof t==="object"&&t!==null?Object.values(t):[],[s]=r;return typeof s==="object"&&s!==null&&!Array.isArray(s)?s:void 0}async function Sa(e,t){let r=Pa(t),s=await Bun.$`npm pack --ignore-scripts --json --pack-destination ${r}`.cwd(e).quiet(),n=Ra(s.stdout.toString());if(typeof n?.filename!=="string"||!n.filename||typeof n.name!=="string"||!n.name||typeof n.version!=="string"||!n.version)throw Error("npm pack did not return a valid artifact identity");let i=Ve(r,n.filename);if(ne($n(r,i)))throw Error("npm pack returned an artifact outside the destination directory");if(i!==Ve(t))await Bp(i,t);return{name:n.name,version:n.version}}async function Ca(e,t){let r=await Bun.$`npm pack --dry-run --ignore-scripts --json`.cwd(t).quiet(),s=Ra(r.stdout.toString())?.files;if(!Array.isArray(s))throw Error(`npm pack did not return a file list for ${e.name}`);return s.map((n)=>{if(typeof n!=="object"||n===null||Array.isArray(n)||!("path"in n))throw Error(`npm pack returned an invalid file entry for ${e.name}`);let i=n.path;if(typeof i!=="string"||!i)throw Error(`npm pack returned an invalid file path for ${e.name}`);if(ne($n(t,Ve(t,i))))throw new u(`Package ${e.name} includes a file outside its directory: ${i}`);return i})}async function ka(e,t,r){let s=await Ca(e,t),n=await jp($a(Vp(),"sisyphus-package-stage-"));try{for(let i of s){let o=Ve(n,i);await Np(Pa(o),{recursive:!0}),await Dp(Ve(t,i),o,{errorOnExist:!0,force:!1,recursive:!1,verbatimSymlinks:!0})}return await Up($a(n,"package.json"),r,"utf-8"),n}catch(i){try{await Fp(n,{force:!0,recursive:!0})}catch(o){throw AggregateError([i,o],"Failed to clean staged npm package")}throw i}}async function xa(e,t,r,s=Ue){let[n,i]=await Promise.all([Ca(e,t),Kr(r)]);for(let o of n){let a=$n(r,Ve(t,o)).split(Gp).join("/");if(!i.has(a)&&!s.isOutput(a))throw new u(`Package ${e.name} includes an untracked or ignored pre-build file: ${o}`)}}async function Pn(e,t){return(await Bun.$`git ls-files --others --ignored --exclude-standard -z`.cwd(e).quiet()).stdout.toString().split("\x00").filter(Boolean).filter((s)=>!s.split("/").includes("node_modules")).map((s)=>`${t}${s}`)}async function Rn(e,t,r=Ue){let[s,n]=await Promise.all([Pn(e,t),Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet()]),i=s.filter((o)=>!r.isOutput(o));if(i.length>0){let o=i.slice(0,Yp),a=i.length-o.length;throw new u(`Repository contains ${i.length} ignored build input(s) outside node_modules`,`Remove ignored source and stale build outputs before preparing npm artifacts (preview with git clean -ndX):
154
+ ${o.join(`
164
155
  `)}${a>0?`
165
- ...and ${a} more`:""}`)}for(let{mode:s,path:a}of Fa(n.stdout.toString()))if(s==="160000")await _n(je(e,a),`${t}${a}/`)}function Fa(e){return e.split("\x00").filter(Boolean).map((t)=>{let r=t.indexOf("\t"),n=r<0?[]:t.slice(0,r).split(" "),[i,,s,...a]=n,o=r<0?"":t.slice(r+1);if(!i||!s||a.length>0||!o)throw Error("Unable to parse Git index while collecting tracked package inputs");return{mode:i,path:o,stage:s}})}async function ja(e,t=""){let r=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),n=new Set;for(let{mode:i,stage:s,path:a}of Fa(r.stdout.toString())){if(s!=="0")throw new g(`Repository has an unresolved index entry: ${a}`);let o=`${t}${a}`;if(n.add(o),i!=="160000")continue;let c=await ja(je(e,a),`${o}/`);for(let p of c)n.add(p)}return n}async function Na(e){let t=new Uint8Array(await Bun.file(e).arrayBuffer()),r=Bun.gunzipSync(t),n=new TextDecoder;for(let i=0;i+Cr<=r.length;){let s=qn(r,i,Ap,n);if(!s)break;let a=qn(r,i+Mp,Dp,n),o=a?`${a}/${s}`:s,c=qn(r,i+xp,Op,n).trim(),p=Number.parseInt(c,8);if(!Number.isSafeInteger(p)||p<0)throw Error(`Invalid tar entry size for ${o}`);let m=i+Cr,u=m+p;if(u>r.length)throw Error(`Truncated tar entry for ${o}`);if(o===Fp)return n.decode(r.subarray(m,u));i=m+Math.ceil(p/Cr)*Cr}throw Error("Packed artifact does not contain package/package.json")}function qn(e,t,r,n){let i=e.subarray(t,t+r),s=i.indexOf(0);return n.decode(s<0?i:i.subarray(0,s))}function Ta(e,t){return JSON.stringify(pt(JSON.parse(e)))===JSON.stringify(pt(JSON.parse(t)))}import{readFile as Np}from"fs/promises";import{dirname as Ba}from"path";var Tp=/^[A-Za-z][0-9A-Za-z._-]*$/,Bp=/^(?:[vV]?\d+(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?|[xX])$/;function Ua(e){return Tp.test(e)&&!Bp.test(e)}function Ga(e){let t=(e||lr).trim();if(!Ua(t))throw new g(`Invalid npm dist-tag "${t}"`,"Use a non-semver tag containing only letters, numbers, dots, underscores, or hyphens");return t}function qa(e){return e.startsWith("@")?e.split("/")[0]:void 0}function Vn(e,t){let r=qa(e);return r?[`--${r}:registry=${t}`]:[]}async function Ha(e){let t=qa(e.name);if(t){let a=await Bun.$`npm config get ${`${t}:registry`}`.cwd(Ba(e.file)).quiet().nothrow();if(a.exitCode===0){let o=a.stdout.toString().trim();if(o&&o!=="undefined"&&o!=="null"){let c=Sr(o);if(c)return c;throw new g(`Invalid ${t}:registry for ${e.name}`,"Registry must be a credential-free HTTP or HTTPS URL")}}}let n=(await Va(e)).publishConfig;if(n!==void 0){if(typeof n!=="object"||n===null||Array.isArray(n))throw new g(`Invalid publishConfig in ${e.name}`,"publishConfig must be an object");let a=Reflect.get(n,"registry");if(a!==void 0){if(typeof a!=="string")throw new g(`Invalid publishConfig.registry in ${e.name}`,"Registry must be an HTTP or HTTPS URL");let o=Sr(a);if(!o)throw new g(`Invalid publishConfig.registry in ${e.name}`,"Registry must be a credential-free HTTP or HTTPS URL");return o}}let i=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(i){let a=Sr(i);if(a)return a}let s=await Bun.$`npm config get registry`.cwd(Ba(e.file)).quiet().nothrow();if(s.exitCode===0){let a=s.stdout.toString().trim();if(a&&a!=="undefined"&&a!=="null"){let o=Sr(a);if(o)return o}}throw new g(`Cannot resolve a credential-free npm registry for ${e.name}`,"Configure registry or @scope:registry as an HTTP or HTTPS URL without embedded credentials")}function Sr(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.search||t.hash)return;return t.href}catch{return}}function _a(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;let t=Reflect.get(e,"name"),r=Reflect.get(e,"version"),n=Reflect.get(e,"dist");if(typeof n!=="object"||n===null||Array.isArray(n))return;let i=Reflect.get(n,"integrity");if(typeof t!=="string"||typeof r!=="string"||typeof i!=="string")return;return{integrity:i,name:t,version:r}}async function Va(e){let t;try{t=await Np(e.file,"utf-8")}catch(n){throw Error(`Failed to read ${e.name}: ${Rr(n)}`)}let r;try{r=JSON.parse(t)}catch(n){throw Error(`Failed to parse ${e.name}: ${Rr(n)}`)}if(typeof r!=="object"||r===null||Array.isArray(r))throw Error(`Invalid ${e.name} manifest object`);return r}async function Wa(e){let t=[];for(let r of e){let i=(await Va(r)).private;if(i!==void 0&&typeof i!=="boolean")throw Error(`Failed to validate ${r.name} manifest: "private" must be a boolean`);if(i)continue;t.push(r)}return t}function Wn(e,t,r){let n=t.newVersion??t.version;return{notes:Gp(Up(e,t.name),t,r),tag:`${t.name}@${n}`,title:`${t.name} v${n}`}}function Up(e,t){return e.filter((r)=>r.affectsPackage(t))}function Gp(e,t,r){let n=[],i=t.newVersion??t.version;if(n.push(`\`${t.name}\` ${t.version} \u2192 ${i}`),e.length===0)return n.join(`
166
- `);n.push(""),n.push("<details>"),n.push(`<summary>Stones (${e.length})</summary>`),n.push("");for(let s of e){if(n.push(`### ${s.message}`),n.push(""),s.description)n.push(s.description),n.push("");let a=qp(s.commits,t.name);if(a.length>0){n.push("<details>"),n.push(`<summary>Commits (${a.length})</summary>`),n.push("");for(let o of a)n.push(Hp(o,r));n.push(""),n.push("</details>"),n.push("")}}return n.push("</details>"),n.join(`
167
- `)}function qp(e,t){if(!e)return[];return e.filter((r)=>r.packages.includes(t))}function Hp(e,t){return`- ${t?`[\`${e.hash}\`](${t(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}import{resolve as _p}from"path";import{pathToFileURL as Vp}from"url";async function Er(e,t){let r=Pt(e);return{canonicalUrl:await Wp(e,t),...r?{owner:r.owner,provider:r.provider,repo:r.repo}:{}}}async function Wp(e,t){let r=null;try{r=new URL(e)}catch{r=null}if(r){let i=r.protocol==="ssh:"||r.protocol==="git+ssh:";if(r.password||r.username&&!i)throw new g("Push URL contains embedded credentials","Configure git authentication outside the remote URL");return r.search="",r.hash="",r.href}let n=e.match(/^(?:([^@/\s]+)@)?([^:/\s]+):(.+)$/);if(n?.[2]&&n[3])return`ssh://${n[1]?`${n[1]}@`:""}${n[2].toLowerCase()}/${n[3].replace(/^\/+/,"")}`;return Vp(_p(await t(),e)).href}function Ir(e){if(!e?.provider||!e.owner||!e.repo)return;return{owner:e.owner,provider:e.provider,repo:e.repo}}async function Lr(e){let r=(await x(()=>Bun.$`git remote get-url --push --all ${e}`.quiet(),`Failed to resolve push URL for ${e}`)).stdout.toString().trim().split(`
168
- `).filter(Boolean);if(r.length!==1)throw new g(`Push remote ${e} must have exactly one push URL, found ${r.length}`,"Remove additional push URLs before starting or resuming a release");let[n]=r;if(!n)throw new g(`Push remote ${e} has no URL`);return n}async function Ar(e,t){let r=await Lr(e.remote),n=await Er(r,t);if(JSON.stringify(n)!==JSON.stringify(e.destination))throw new g(`Push remote ${e.remote} no longer matches the recorded release destination`,"Restore the original remote before resuming the release");return r}async function zn(e){for(let t of e){let n=(await x(()=>Bun.$`git rev-parse ${t.source}`.quiet(),`Failed to resolve ${t.source}`)).stdout.toString().trim();if(n!==t.oid)throw new g(`Release ref ${t.source} points to ${n}, expected ${t.oid}`,"Do not move release refs before the release completes")}}async function Kn(e,t){let r=await Ar(e,t),n=e.refs.map((i)=>`${i.oid}:${i.destination}`);await x(()=>Bun.$`git push --atomic ${r} ${n}`.quiet(),"Failed to atomically push release refs")}async function Ja(e,t,r=e.refs){let n=await Yn(e,r,t),i=r.find((s)=>n.get(s.destination)!==s.oid);if(i)throw new g(`Cannot safely resume remote push: ${i.destination} is not at ${i.oid}`,"The previous push may not have completed; inspect the remote refs manually")}async function Yn(e,t,r){let n=await Ar(e,r),i=t.map((a)=>a.destination),s=await x(()=>Bun.$`git ls-remote --refs ${n} ${i}`.quiet(),"Failed to inspect remote release refs");return new Map(s.stdout.toString().trim().split(`
169
- `).filter(Boolean).map((a)=>{let[o="",c=""]=a.split("\t");return[c,o]}))}async function Zn(){let e=await Bun.$`git symbolic-ref --quiet --short HEAD`.quiet().nothrow();if(e.exitCode!==0)return;return e.stdout.toString().trim()||void 0}async function za(){let e=await Zn();if(!e)throw new g("Cannot push a release from detached HEAD","Check out the branch that should receive the release");return{branch:e,remote:await Xn(e)}}async function Xn(e){let t=e?await Jn(`branch.${e}.pushRemote`):null,r=await Jn("remote.pushDefault"),n=e?await Jn(`branch.${e}.remote`):null,i=t??r??n;if(!i){let a=(await x(()=>Bun.$`git remote`.quiet(),"Failed to list git remotes")).stdout.toString().trim().split(`
170
- `).filter(Boolean);if(a.length===1&&a[0]==="origin")i="origin"}if(!i){let s=e?` for branch ${e}`:"";throw new g(`No push remote is configured${s}`,e?"Configure a branch push remote or remote.pushDefault":"Configure remote.pushDefault")}return await x(()=>Bun.$`git remote get-url --push ${i}`.quiet(),`Invalid push remote ${i}`),i}async function Jn(e){let t=await Bun.$`git config --get ${e}`.quiet().nothrow();if(t.exitCode===1)return null;if(t.exitCode!==0){let n=t.stderr.toString().trim();throw Error(n?`Failed to read git config ${e}: ${n}`:`Failed to read git config ${e}`)}let r=t.stdout.toString().trim();if(!r)throw Error(`Git config ${e} is empty`);return r}import{createHash as vg,randomUUID as Rg}from"crypto";import{constants as kg}from"fs";import{copyFile as $g,link as Cg,lstat as Sg,readFile as Ro,rename as ko,rm as $o,stat as Eg,unlink as Ig}from"fs/promises";import{extname as Lg,join as Ag,resolve as xg}from"path";import{createHash as oo,randomUUID as rg}from"crypto";import{link as ng,lstat as Dt,mkdir as Tr,open as ig,readFile as co,realpath as Te,rename as sg,rm as ag,unlink as og}from"fs/promises";import{dirname as xt,isAbsolute as ao,join as Ot,relative as lo,resolve as ue,sep as cg}from"path";var Et=1,We=["planned","local-ready","external","completed"],Qn=["pending","started","completed"],Jp=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,Je=/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/,Ka=/^sha512-[0-9A-Za-z+/]{86}==$/,Ya=/^[0-9A-Za-z][0-9A-Za-z._/-]*$/,ei=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Za=/^(?:linux:[0-9a-f-]{36}:[0-9]+|ps:.+|windows:[0-9]+)$/i,xr=2,Xa=3,Qa=19;class w extends Error{_tag="ReleaseLedgerError"}function v(e,t){throw new w(`Invalid release ledger at ${e}: ${t}`)}function It(e,t){if(typeof e!=="string")v(t,"must be a string");return e}function L(e,t){let r=It(e,t);if(!r.trim())v(t,"must be nonempty");return r}function ze(e,t){let r=L(e,t);if(!Jp.test(r))v(t,`invalid release ID ${r}`);return r}function Or(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function Y(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function M(e){return e instanceof Error?e.message:String(e)}import{randomUUID as zp}from"crypto";import{constants as eo,readFileSync as to}from"fs";import{link as Kp,lstat as Ke,open as ni,readFile as ro,rename as Yp,rm as Dr,unlink as Fr}from"fs/promises";import{hostname as no}from"os";import{dirname as Ne,join as ti}from"path";async function Nr(e){let t=ti(e,".write.lock");for(let r=0;r<Xa;r+=1){let n=io(process.pid);if(!n)throw new w("Failed to identify the release ledger lock owner process");let i={acquiredAt:new Date().toISOString(),hostname:no(),ownerId:zp(),pid:process.pid,processStartedAt:n,schemaVersion:xr},s=jr(e,i.ownerId,"owner");await Zp(s,i);try{await Kp(s,t)}catch(o){if(await Dr(s,{force:!0}),!Y(o,"EEXIST"))throw new w(`Failed to acquire release ledger lock at ${t}: ${M(o)}`);let c=await Xp(t);if(!c)continue;await Qp(c);continue}let a={lockPath:t,metadata:i,ownerPath:s};try{return await re(e),a}catch(o){try{await At(a)}catch(c){throw AggregateError([o,c],`Failed to durably acquire release ledger lock at ${t}`)}throw new w(`Failed to durably acquire release ledger lock at ${t}: ${M(o)}`)}}throw new w(`Release ledger is locked by another process at ${t}: lock changed during acquisition`)}async function Zp(e,t){let r;try{r=await ni(e,"wx",384),await r.writeFile(`${JSON.stringify(t)}
171
- `,"utf-8"),await r.sync()}catch(n){throw await Dr(e,{force:!0}),new w(`Failed to create release ledger lock owner: ${M(n)}`)}finally{await r?.close()}await re(Ne(e))}async function Xp(e){let t,r,n;try{n=await ni(e,eo.O_RDONLY|eo.O_NOFOLLOW),t=await n.stat(),r=await n.readFile("utf-8")}catch(m){if(Y(m,"ENOENT"))return null;throw new w(`Failed to inspect release ledger lock at ${e}: ${M(m)}`)}finally{await n?.close()}if(!t.isFile())throw new w(`Release ledger is locked by another process at ${e}: lock owner is unknown`);let i=null;try{i=ri(JSON.parse(r))}catch{i=null}if(!i)return await Mr(e,t,"lock metadata is malformed");let s=jr(Ne(e),i.ownerId,"owner"),a=jr(Ne(e),i.ownerId,"claim"),o;try{o=await Ke(s)}catch(m){if(Y(m,"ENOENT")){try{await Ke(a)}catch(u){if(Y(u,"ENOENT"))return await Mr(e,t,"stale lock ownership is incomplete");throw new w(`Failed to inspect release ledger lock claim: ${M(u)}`)}throw new w(`Release ledger is locked by another process at ${e}: stale lock recovery is incomplete (claim ${a} remains; remove both after verifying the owner process is dead)`)}throw new w(`Failed to inspect release ledger lock owner: ${M(m)}`)}if(!o.isFile()||o.isSymbolicLink())return await Mr(e,t,"stale lock ownership is invalid");let c=null;try{c=ri(JSON.parse(await ro(s,"utf-8")))}catch{c=null}if(!c||!tg(i,c))return await Mr(e,t,"stale lock ownership is invalid");if(!await so(e,t))return null;if(!Lt(t,o))return{lockPath:e,lockStat:t,metadata:i,ownerPath:s,ownerStat:o};if(i.hostname!==no())throw new w(`Release ledger is locked by another process at ${e}: lock owner is on an unknown host ${i.hostname} (pid ${i.pid})`);let p=eg(i);if(p==="alive")throw new w(`Release ledger is locked by another process at ${e}: lock owner is still live (pid ${i.pid} on ${i.hostname})`);if(p==="unknown")throw new w(`Release ledger is locked by another process at ${e}: lock owner liveness is unknown (pid ${i.pid} on ${i.hostname})`);return{lockPath:e,lockStat:t,metadata:i,ownerPath:s,ownerStat:o}}async function Qp(e){let t=jr(Ne(e.lockPath),e.metadata.ownerId,"claim");if(e.ownerPath!==t)try{await Yp(e.ownerPath,t),await re(Ne(e.lockPath))}catch(i){if(Y(i,"ENOENT")||Y(i,"EEXIST"))return;throw new w(`Failed to claim stale release ledger lock: ${M(i)}`)}let r,n;try{[r,n]=await Promise.all([Ke(e.lockPath),Ke(t)])}catch(i){if(Y(i,"ENOENT"))return;throw new w(`Failed to verify stale release ledger lock: ${M(i)}`)}if(!Lt(e.lockStat,r))return;if(!Lt(e.ownerStat,n))return;try{await Fr(e.lockPath),await re(Ne(e.lockPath)),await Fr(t),await re(Ne(e.lockPath))}catch(i){if(Y(i,"ENOENT"))return;throw new w(`Failed to recover stale release ledger lock: ${M(i)}`)}}async function At(e){let t,r;try{[t,r]=await Promise.all([Ke(e.lockPath),Ke(e.ownerPath)])}catch(i){if(Y(i,"ENOENT"))throw await Dr(e.ownerPath,{force:!0}),new w("Failed to release ledger write lock: ownership record is missing");throw new w(`Failed to inspect release ledger lock during release: ${M(i)}`)}if(!Lt(t,r))throw await Dr(e.ownerPath,{force:!0}),new w("Failed to release ledger write lock: ownership changed");let n=null;try{n=ri(JSON.parse(await ro(e.lockPath,"utf-8")))}catch{n=null}if(n?.ownerId!==e.metadata.ownerId)throw new w("Failed to release ledger write lock: owner identity changed");try{await Fr(e.lockPath),await Fr(e.ownerPath),await re(Ne(e.lockPath))}catch(i){throw new w(`Failed to release ledger write lock: ${M(i)}`)}}function ri(e){if(typeof e!=="object"||e===null||Array.isArray(e))return null;let t=e,r=Object.keys(t);if(r.length!==6||!r.every((n)=>["acquiredAt","hostname","ownerId","pid","processStartedAt","schemaVersion"].includes(n))||t.schemaVersion!==xr||typeof t.ownerId!=="string"||!ei.test(t.ownerId)||typeof t.hostname!=="string"||!t.hostname||typeof t.pid!=="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.processStartedAt!=="string"||!Za.test(t.processStartedAt)||typeof t.acquiredAt!=="string"||!Or(t.acquiredAt))return null;return{acquiredAt:t.acquiredAt,hostname:t.hostname,ownerId:t.ownerId,pid:t.pid,processStartedAt:t.processStartedAt,schemaVersion:xr}}function jr(e,t,r){if(!ei.test(t))throw new w(`Release ledger is locked by another process at ${ti(e,".write.lock")}: lock owner identity is malformed`);return ti(e,`.write.lock.${t}.${r}`)}function eg(e){try{process.kill(e.pid,0)}catch(r){return Y(r,"ESRCH")?"dead":"unknown"}let t=io(e.pid);if(!t)return"unknown";if(t.split(":",1)[0]!==e.processStartedAt.split(":",1)[0])return"unknown";return t===e.processStartedAt?"alive":"dead"}function io(e){if(process.platform==="linux")try{let t=to("/proc/sys/kernel/random/boot_id","utf-8").trim(),r=to(`/proc/${e}/stat`,"utf-8"),n=r.lastIndexOf(")"),i=n<0?void 0:r.slice(n+1).trim().split(/\s+/)[Qa];if(t&&i)return`linux:${t}:${i}`}catch{}if(process.platform==="win32")try{let t=Bun.spawnSync({cmd:["powershell.exe","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().Ticks`],stderr:"pipe",stdout:"pipe"}),r=t.stdout.toString().trim();if(t.exitCode===0&&/^[0-9]+$/.test(r))return`windows:${r}`}catch{return null}try{let t=Bun.spawnSync({cmd:["ps","-o","lstart=","-p",String(e)],env:{...process.env,LC_ALL:"C",TZ:"UTC"},stderr:"pipe",stdout:"pipe"});if(t.exitCode!==0)return null;let r=t.stdout.toString().trim().replace(/\s+/g," ");return r?`ps:${r}`:null}catch{return null}}function Lt(e,t){return e.dev===t.dev&&e.ino===t.ino}async function so(e,t){try{return Lt(t,await Ke(e))}catch(r){if(Y(r,"ENOENT"))return!1;throw new w(`Failed to verify release ledger lock at ${e}: ${M(r)}`)}}async function Mr(e,t,r){if(!await so(e,t))return null;throw new w(`Release ledger is locked by another process at ${e}: ${r}`)}function tg(e,t){return e.schemaVersion===t.schemaVersion&&e.ownerId===t.ownerId&&e.hostname===t.hostname&&e.pid===t.pid&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}async function re(e){let t=await ni(e,"r");try{await t.sync()}finally{await t.close()}}async function ii(e){let t=ue(e),r=await Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet().nothrow();if(r.exitCode!==0)throw new w(`Failed to resolve repository root from ${t}: ${r.stderr.toString().trim()||"git exited unsuccessfully"}`);let n=r.stdout.toString().trim();if(!n)throw new w(`Failed to resolve repository root from ${t}: empty git output`);let i=ao(n)?ue(n):ue(t,n),s=await Bun.$`git rev-parse --git-path sisyphus/release`.cwd(i).quiet().nothrow();if(s.exitCode!==0)throw new w(`Failed to resolve release ledger git path from ${i}: ${s.stderr.toString().trim()||"git exited unsuccessfully"}`);let a=s.stdout.toString().trim();if(!a)throw new w(`Failed to resolve release ledger git path from ${i}: empty git output`);let o=ao(a)?ue(a):ue(i,a);return{activePath:Ot(o,"active.json"),artifactsRoot:Ot(o,"artifacts"),historyDirectory:Ot(o,"history"),releaseDirectory:o,removingPath:Ot(o,"removing.json"),repositoryRoot:i}}async function po(e,t){let r=`${t}^{tree}`,n=await Bun.$`git rev-parse ${r}`.cwd(e).quiet().nothrow(),i=n.stdout.toString().trim();if(n.exitCode!==0||!Je.test(i))throw new w(`Cannot resolve release tree for commit ${t}`);return i}async function Ft(e,t){await Tr(e.releaseDirectory,{recursive:!0}),await Be(e.releaseDirectory,"release directory"),await Tr(e.artifactsRoot,{recursive:!0}),await Be(e.artifactsRoot,"artifacts root"),await Tr(Tt(e,t),{recursive:!0}),await go(e,t)}async function go(e,t){let r=Tt(e,t);await Be(e.releaseDirectory,"release directory"),await Be(e.artifactsRoot,"artifacts root"),await Be(r,`artifacts directory for release ${t}`);let n=await Te(e.releaseDirectory),i=await Te(e.artifactsRoot),s=await Te(r);return Mt(n,i,"Artifacts root escapes the release directory"),Mt(i,s,`Artifacts directory for release ${t} escapes the artifacts root`),s}async function mo(e){await Be(e.releaseDirectory,"release directory"),await Tr(e.historyDirectory,{recursive:!0}),await Be(e.historyDirectory,"history directory");let t=await Te(e.releaseDirectory),r=await Te(e.historyDirectory);Mt(t,r,"History directory escapes the release directory")}async function Br(e,t){for(let[r,n]of Object.entries(e.artifacts)){let i=ue(t.releaseDirectory,n.path);if(await Nt(t,e.id,i),await Ur(i)!==n.integrity)throw new w(`Invalid release ledger artifact for ${r}: sha512 integrity mismatch`)}}async function jt(e,t){let r=await Te(t.repositoryRoot);for(let n of e.packages){let i=ue(t.repositoryRoot,n.file),s;try{s=await Dt(i)}catch(o){throw new w(`Invalid package manifest for ${n.name} at ${n.file}: ${M(o)}`)}if(!s.isFile()||s.isSymbolicLink())throw new w(`Invalid package manifest for ${n.name} at ${n.file}: expected a regular file`);let a=await Te(i);Mt(r,a,`Package manifest for ${n.name} escapes the repository: ${n.file}`)}}async function Nt(e,t,r){let n=await go(e,t),i;try{i=await Dt(r)}catch(a){throw new w(`Invalid release artifact at ${r}: ${M(a)}`)}if(!i.isFile()||i.isSymbolicLink())throw new w(`Invalid release artifact at ${r}: expected a regular file`);let s=await Te(r);Mt(n,s,`Release artifact escapes artifacts directory: ${r}`)}async function si(e,t,r,n){let i=`${JSON.stringify(t,null,2)}
172
- `,s=Ot(xt(e),`.${rg()}.json.tmp`),a=await Nr(xt(e));try{if(await Be(xt(e),"release directory"),r){await lg(e,"active release ledger");let c;try{c=JSON.parse(await co(e,"utf-8"))}catch(p){throw new w(`Failed to read active release ledger at ${e} before writing: ${M(p)}`)}if(c.updatedAt!==n)throw new w("Active release ledger changed in another process")}let o=await ig(s,"wx",384);try{await o.writeFile(i,"utf-8"),await o.sync()}finally{await o.close()}if(r)await sg(s,e);else{try{await ng(s,e)}catch(c){if(Y(c,"EEXIST"))throw new w(`Cannot create release ledger: active ledger already exists at ${e}`);throw c}await og(s)}await re(xt(e))}catch(o){await ai(s,o,`Failed to clean temporary ledger file at ${s}`)}finally{await At(a)}}async function ai(e,t,r){try{await ag(e,{force:!0})}catch(n){throw AggregateError([t,n],r)}throw t}async function Ur(e){let t;try{t=await co(e)}catch(r){throw new w(`Failed to read release artifact at ${e}: ${M(r)}`)}return`sha512-${oo("sha512").update(t).digest("base64")}`}async function Be(e,t){let r;try{r=await Dt(e)}catch(n){throw new w(`Invalid ${t} at ${e}: ${M(n)}`)}if(!r.isDirectory()||r.isSymbolicLink())throw new w(`Invalid ${t} at ${e}: expected a real directory`)}async function lg(e,t){let r;try{r=await Dt(e)}catch(n){throw new w(`Invalid ${t} at ${e}: ${M(n)}`)}if(!r.isFile()||r.isSymbolicLink())throw new w(`Invalid ${t} at ${e}: expected a regular file`)}async function Ye(e){try{return await Dt(e),!0}catch(t){if(Y(t,"ENOENT"))return!1;throw t}}function Tt(e,t){return ue(e.artifactsRoot,ze(t,"id"))}function oi(e,t,r){let n=`${oo("sha256").update(r).digest("hex")}.tgz`;return ue(Tt(e,t),n)}function Gr(e,t,r){return lo(e.releaseDirectory,oi(e,t,r)).split(cg).join("/")}function ci(e,t){let r=ue(e.historyDirectory,`${ze(t,"id")}.json`);if(xt(r)!==ue(e.historyDirectory))throw new w(`Invalid release history path for ID ${t}`);return r}function Mt(e,t,r){let n=lo(e,t);if(!n||ae(n))throw new w(r)}import{isAbsolute as uo,relative as pg,resolve as gg}from"path";function mi(e){if(Object.values(e.operations.npm).some((t)=>t.state!=="pending"))return!0;if(e.operations.push&&e.operations.push.state!=="pending")return!0;return Object.values(e.operations.providerReleases).some((t)=>t.state!=="pending")}function fo(e){return e.map((t,r)=>{let n=`create.packages[${r}]`,i=t.oldVersion??t.version;if(t.oldVersion!==void 0&&t.version!==void 0&&t.oldVersion!==t.version)v(n,"oldVersion and version must match when both are provided");return wo({file:t.file,isPrivate:t.isPrivate,name:t.name,newVersion:t.newVersion,oldVersion:i},n)})}function ho(e){return e.map((t,r)=>{let n=typeof t==="object"&&t!==null&&"toJson"in t&&typeof t.toJson==="function"?t.toJson():t,i;try{i=JSON.parse(JSON.stringify(n))}catch(s){throw new w(`Invalid release ledger at create.stones[${r}]: ${M(s)}`)}return yo(i,`create.stones[${r}]`)})}function Bt(e,t){let r=Z(e,"root");if(ge(r,["schemaVersion","id","baseCommit","createdAt","updatedAt","phase","options","packages","releaseTags","tagsReady","stones","artifacts","operations"],["expectedReleaseTree","releaseCommit"],"root"),r.schemaVersion!==Et)v("schemaVersion",`unsupported schema version ${String(r.schemaVersion)}`);let n=ze(r.id,"id"),i=mt(r.baseCommit,"baseCommit"),s=qr(r.createdAt,"createdAt"),a=qr(r.updatedAt,"updatedAt");if(Date.parse(a)<Date.parse(s))v("updatedAt","must not precede createdAt");let o=bo(r.phase,We,"phase","release phase"),c=ug(r.options,"options"),p=dg(r.packages,t.repositoryRoot),m=mg(r.releaseTags,p,c),u=Ue(r.tagsReady,"tagsReady");if(!c.tags&&!u)v("tagsReady","must be true when tags are disabled");let f=fg(r.stones),b=r.expectedReleaseTree===void 0?void 0:mt(r.expectedReleaseTree,"expectedReleaseTree"),d=r.releaseCommit===void 0?void 0:mt(r.releaseCommit,"releaseCommit"),P=wg(r.artifacts,p,t,n),S=yg(r.operations,p,c,s,a),$={artifacts:P,baseCommit:i,createdAt:s,id:n,operations:S,options:c,packages:p,phase:o,releaseTags:m,schemaVersion:Et,stones:f,tagsReady:u,updatedAt:a};if(b!==void 0)$.expectedReleaseTree=b;if(d!==void 0)$.releaseCommit=d;if(c.tags&&u&&!d)v("tagsReady","cannot be true before releaseCommit is recorded");if(o==="completed")fi($);return $}function mg(e,t,r){if(!Array.isArray(e))v("releaseTags","must be an array");let n=e.map((s,a)=>{let o=L(s,`releaseTags[${a}]`);return gi(`refs/tags/${o}`,`releaseTags[${a}]`),o});if(new Set(n).size!==n.length)v("releaseTags","must not contain duplicates");let i=r.tags?t.map((s)=>`${s.name}@${s.newVersion}`).sort():[];if(JSON.stringify([...n].sort())!==JSON.stringify(i))v("releaseTags","must exactly match the release package versions when tags are enabled");return n}function ug(e,t){let r=Z(e,t);return ge(r,["changelog","createRelease","dryRun","npm","npmTag","publishOnly","push","tags"],[],t),{changelog:Ue(r.changelog,`${t}.changelog`),createRelease:Ue(r.createRelease,`${t}.createRelease`),dryRun:hi(r.dryRun),npm:Ue(r.npm,`${t}.npm`),npmTag:L(r.npmTag,`${t}.npmTag`),publishOnly:Ue(r.publishOnly,`${t}.publishOnly`),push:Ue(r.push,`${t}.push`),tags:Ue(r.tags,`${t}.tags`)}}function dg(e,t){if(!Array.isArray(e)||e.length===0)v("packages","must be a nonempty array");let r=new Set,n=new Set;return e.map((i,s)=>{let a=`packages[${s}]`,o=wo(i,a);if(uo(o.file))v(`${a}.file`,"must be repository-relative");if(r.has(o.name))v(a,`duplicate package name ${o.name}`);let c=gg(t,o.file),p=pg(t,c);if(!p||ae(p))v(`${a}.file`,"must resolve inside the repository");if(n.has(c))v(a,`duplicate package file ${o.file}`);return r.add(o.name),n.add(c),o})}function wo(e,t){let r=Z(e,t);ge(r,["name","file","oldVersion","newVersion","isPrivate"],[],t);let n=L(r.file,`${t}.file`);if(n.includes("\x00"))v(`${t}.file`,"must not contain a null byte");return{file:n,isPrivate:Ue(r.isPrivate,`${t}.isPrivate`),name:L(r.name,`${t}.name`),newVersion:L(r.newVersion,`${t}.newVersion`),oldVersion:L(r.oldVersion,`${t}.oldVersion`)}}function fg(e){if(!Array.isArray(e))v("stones","must be an array");let t=new Set;return e.map((r,n)=>{let i=yo(r,`stones[${n}]`);if(t.has(i.id))v(`stones[${n}].id`,`duplicate stone ID ${i.id}`);return t.add(i.id),i})}function yo(e,t){let r=Z(e,t);ge(r,["id","message"],["tag","description","commits","major","minor","patch","dependency","snapshot"],t);let n={id:L(r.id,`${t}.id`),message:L(r.message,`${t}.message`)};if(r.tag!==void 0)n.tag=L(r.tag,`${t}.tag`);if(r.description!==void 0)n.description=It(r.description,`${t}.description`);if(r.commits!==void 0)n.commits=hg(r.commits,`${t}.commits`);for(let i of["major","minor","patch","dependency","snapshot"])if(r[i]!==void 0)n[i]=vo(r[i],`${t}.${i}`);return n}function hg(e,t){if(!Array.isArray(e))v(t,"must be an array");return e.map((r,n)=>{let i=`${t}[${n}]`,s=Z(r,i);return ge(s,["hash","subject","type","message","packages"],["body","scope"],i),{...{hash:L(s.hash,`${i}.hash`),message:L(s.message,`${i}.message`),packages:vo(s.packages,`${i}.packages`),subject:L(s.subject,`${i}.subject`),type:L(s.type,`${i}.type`)},...s.body===void 0?{}:{body:It(s.body,`${i}.body`)},...s.scope===void 0?{}:{scope:L(s.scope,`${i}.scope`)}}})}function wg(e,t,r,n){let i=Z(e,"artifacts"),s=new Map(t.map((o)=>[o.name,o])),a=Ee();for(let[o,c]of Object.entries(i)){let p=s.get(o);if(!p)v(`artifacts.${o}`,"references an unknown package");if(p.isPrivate)v(`artifacts.${o}`,"private packages cannot have artifacts");let m=`artifacts.${o}`,u=Z(c,m);ge(u,["path","integrity"],[],m);let f=L(u.path,`${m}.path`);if(uo(f))v(`${m}.path`,"must be relative to the release directory");let b=Gr(r,n,o);if(f!==b)v(`${m}.path`,`must be ${b}`);let d=L(u.integrity,`${m}.integrity`);if(!Ka.test(d))v(`${m}.integrity`,"must be a sha512 SRI value");de(a,o,{integrity:d,path:f})}return a}function yg(e,t,r,n,i){let s=Z(e,"operations");ge(s,["npm","npmRegistries","providerReleases"],["push"],"operations");let a=new Map(t.map((P)=>[P.name,P])),o=Z(s.npm,"operations.npm"),c=Ee();for(let[P,S]of Object.entries(o)){let $=a.get(P);if(!$)v(`operations.npm.${P}`,"references an unknown package");if($.isPrivate)v(`operations.npm.${P}`,"private packages cannot have npm operations");if(!r.npm)v(`operations.npm.${P}`,"npm is disabled");let R=li(S,`operations.npm.${P}`);pi(R,n,i,`operations.npm.${P}`),de(c,P,R)}let p=r.npm?t.filter((P)=>!P.isPrivate).map((P)=>P.name):[];for(let P of p)if(!c[P])v("operations.npm",`missing public package ${P}`);let m=Z(s.npmRegistries,"operations.npmRegistries"),u=Ee();for(let[P,S]of Object.entries(m)){if(!c[P])v(`operations.npmRegistries.${P}`,"references an unknown npm operation");de(u,P,wi(S,`operations.npmRegistries.${P}`))}let f;if(s.push!==void 0){if(!r.push&&!r.tags)v("operations.push","push and tags are disabled");let P=Z(s.push,"operations.push");ge(P,["destination","remote","refs","state"],["startedAt","completedAt"],"operations.push");let S=ui(P,"operations.push"),$=li(P,"operations.push",["destination","remote","refs"]);pi($,n,i,"operations.push"),f={...S,...$}}let b=Z(s.providerReleases,"operations.providerReleases"),d=Ee();for(let[P,S]of Object.entries(b)){if(!a.has(P))v(`operations.providerReleases.${P}`,"references an unknown package");if(!r.createRelease)v(`operations.providerReleases.${P}`,"createRelease is disabled");let $=`operations.providerReleases.${P}`,R=Z(S,$);ge(R,["tag","title","notes","state"],["startedAt","completedAt"],$);let _=di(R,$),F=li(R,$,["tag","title","notes"]);pi(F,n,i,$),de(d,P,{..._,...F})}return{npm:c,npmRegistries:u,providerReleases:d,...f?{push:f}:{}}}function li(e,t,r=[]){let n=Z(e,t);ge(n,["state",...r],["startedAt","completedAt"],t);let i=bo(n.state,Qn,`${t}.state`,"operation state");if(i==="pending"){if(n.startedAt!==void 0||n.completedAt!==void 0)v(t,"pending operations cannot have timestamps");return{state:i}}let s=qr(n.startedAt,`${t}.startedAt`);if(i==="started"){if(n.completedAt!==void 0)v(t,"started operations cannot have completedAt");return{startedAt:s,state:i}}let a=qr(n.completedAt,`${t}.completedAt`);if(Date.parse(a)<Date.parse(s))v(t,"completedAt must not precede startedAt");return{completedAt:a,startedAt:s,state:i}}function ui(e,t){let r=Z(e,t),n=bg(r.destination,`${t}.destination`),i=L(r.remote,`${t}.remote`);if(!Ya.test(i)||i.includes("..")||i.includes("//"))v(`${t}.remote`,"must be a git remote name, not a URL or credential-bearing value");if(!Array.isArray(r.refs)||r.refs.length===0)v(`${t}.refs`,"must be a nonempty array");let s=new Set,a=new Set,o=r.refs.map((c,p)=>{let m=`${t}.refs[${p}]`,u=Z(c,m);ge(u,["source","destination","oid"],[],m);let f=gi(u.source,`${m}.source`),b=gi(u.destination,`${m}.destination`),d=L(u.oid,`${m}.oid`);if(!Je.test(d))v(`${m}.oid`,"must be a full 40- or 64-character git object ID");if(s.has(f))v(`${m}.source`,`duplicate source ref ${f}`);if(a.has(b))v(`${m}.destination`,`duplicate destination ref ${b}`);return s.add(f),a.add(b),{destination:b,oid:d,source:f}});return{destination:n,refs:o,remote:i}}function bg(e,t){let r=Z(e,t);ge(r,["canonicalUrl"],["owner","provider","repo"],t);let n=L(r.canonicalUrl,`${t}.canonicalUrl`),i;try{i=new URL(n)}catch{v(`${t}.canonicalUrl`,"must be an absolute credential-free URL")}let s=i.protocol==="ssh:"||i.protocol==="git+ssh:";if(i.password||i.username&&!s||i.search||i.hash)v(`${t}.canonicalUrl`,"must not contain credentials, query parameters, or fragments");let a=[r.provider,r.owner,r.repo];if(a.every((c)=>c===void 0))return{canonicalUrl:n};if(a.some((c)=>c===void 0))v(t,"provider, owner, and repo must be set together");let o=L(r.provider,`${t}.provider`);if(o!=="github"&&o!=="gitlab"&&o!=="bitbucket")v(`${t}.provider`,"must be github, gitlab, or bitbucket");return{canonicalUrl:n,owner:L(r.owner,`${t}.owner`),provider:o,repo:L(r.repo,`${t}.repo`)}}function di(e,t){let r=Z(e,t);return{notes:It(r.notes,`${t}.notes`),tag:L(r.tag,`${t}.tag`),title:L(r.title,`${t}.title`)}}function Hr(e,t,r){if(!Pg(t))throw new w(`Unknown release operation state ${String(t)}`);if(e.state===t)return e;if(e.state==="pending"&&t==="started")return{startedAt:r,state:t};if(e.state==="started"&&t==="completed")return{completedAt:r,startedAt:e.startedAt,state:t};throw new w(`Invalid release operation transition from ${e.state} to ${t}`)}function fi(e){if(!e.tagsReady)throw new w(`Cannot complete release ${e.id}: local release tags are not ready`);for(let[t,r]of Object.entries(e.operations.npm)){if(r.state!=="completed")throw new w(`Cannot complete release ${e.id}: npm operation for ${t} is ${r.state}`);if(!e.artifacts[t])throw new w(`Cannot complete release ${e.id}: npm artifact for ${t} is missing`);if(!e.operations.npmRegistries[t])throw new w(`Cannot complete release ${e.id}: npm registry for ${t} is missing`)}if((e.options.push||e.options.publishOnly&&e.options.tags)&&!e.operations.push)throw new w(`Cannot complete release ${e.id}: push operation is not configured`);if(e.operations.push&&e.operations.push.state!=="completed")throw new w(`Cannot complete release ${e.id}: push operation is ${e.operations.push.state}`);if(e.options.createRelease)for(let t of e.packages){let r=e.operations.providerReleases[t.name];if(!r)throw new w(`Cannot complete release ${e.id}: provider release for ${t.name} is not configured`);if(r.state!=="completed")throw new w(`Cannot complete release ${e.id}: provider release for ${t.name} is ${r.state}`)}}function hi(e){if(e!==!1)v("options.dryRun","durable ledgers require dryRun to be false");return!1}function wi(e,t){let r=L(e,t),n;try{n=new URL(r)}catch{v(t,"must be an absolute HTTP or HTTPS URL")}if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||n.search||n.hash)v(t,"must be a credential-free HTTP or HTTPS URL");return n.href}function pi(e,t,r,n){if(e.state==="pending")return;let i=Date.parse(e.startedAt);if(i<Date.parse(t)||i>Date.parse(r))v(`${n}.startedAt`,"must be between createdAt and updatedAt");if(e.state==="completed"){let s=Date.parse(e.completedAt);if(s<i||s>Date.parse(r))v(`${n}.completedAt`,"must be between startedAt and updatedAt")}}function gi(e,t){let r=L(e,t);if(!r.startsWith("refs/")||r.includes("..")||r.includes("//")||/[\s~^:?*[\\]/.test(r))v(t,"must be an exact full git ref");return r}function bo(e,t,r,n){if(typeof e!=="string"||!t.includes(e))v(r,`unknown ${n} ${String(e)}`);return e}function Po(e){return We.includes(e)}function Pg(e){return Qn.includes(e)}function Z(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))v(t,"must be an object");return e}function ge(e,t,r,n){let i=new Set([...t,...r]);for(let s of t)if(!Object.hasOwn(e,s))v(n,`missing required key ${s}`);for(let s of Object.keys(e))if(!i.has(s))v(n,`unknown key ${s}`)}function Ue(e,t){if(typeof e!=="boolean")v(t,"must be a boolean");return e}function qr(e,t){let r=L(e,t);if(!Or(r))v(t,"must be a canonical ISO timestamp");return r}function mt(e,t){let r=L(e,t);if(!Je.test(r))v(t,"must be a full 40- or 64-character git object ID");return r}function vo(e,t){if(!Array.isArray(e))v(t,"must be an array");return e.map((r,n)=>L(r,`${t}[${n}]`))}function yi(e){return new Date(Math.max(Date.now(),Date.parse(e)+1)).toISOString()}function Ee(){return Object.create(null)}function de(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}class ye{value;paths;releaseDirectory;artifactsDirectory;activePath;active=!0;constructor(e,t){this.value=e;this.paths=t;this.releaseDirectory=t.releaseDirectory,this.artifactsDirectory=Tt(t,e.id),this.activePath=t.activePath}static async create(e,t=process.cwd()){let r=await ii(t);if(await Ye(r.activePath))throw new w(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);if(await Ye(r.removingPath))throw new w(`Cannot create release ledger: an interrupted removal left ${r.removingPath}; delete it and its artifacts directory to finish cleanup`);let n=new Date().toISOString(),i=await Bun.$`git rev-parse HEAD`.cwd(r.repositoryRoot).quiet().nothrow(),s=i.stdout.toString().trim();if(i.exitCode!==0||!Je.test(s))throw new w("Cannot create release ledger: failed to resolve the current commit");let a=e.options.publishOnly?await po(r.repositoryRoot,s):void 0,o=fo(e.packages),c=ho(e.stones),p=ze(e.id??vg("sha256").update(JSON.stringify({baseCommit:s,options:e.options,packages:o,stones:c})).digest("hex"),"create.id"),m=Ee(),u=e.options.tags?o.map((P)=>`${P.name}@${P.newVersion}`).sort():[];if(e.options.npm){for(let P of o)if(!P.isPrivate)de(m,P.name,{state:"pending"})}let f={artifacts:Ee(),baseCommit:s,createdAt:n,id:p,operations:{npm:m,npmRegistries:Ee(),providerReleases:Ee()},options:{changelog:e.options.changelog,createRelease:e.options.createRelease,dryRun:hi(e.options.dryRun),npm:e.options.npm,npmTag:L(e.options.npmTag,"create.options.npmTag"),publishOnly:e.options.publishOnly,push:e.options.push,tags:e.options.tags},packages:o,phase:"planned",releaseTags:u,schemaVersion:Et,stones:c,tagsReady:!e.options.tags,updatedAt:n};if(a)f.expectedReleaseTree=a;let b=Bt(f,r);if(await jt(b,r),await Ft(r,p),await Ye(r.activePath))throw new w(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);let d=ci(r,p);if(await Ye(d))throw new w(`Release ${p} is already completed at ${d}`);return await si(r.activePath,b,!1),new ye(b,r)}static async loadActive(e=process.cwd()){let t=await ii(e),r;try{r=await Sg(t.activePath)}catch(a){if(Y(a,"ENOENT")){if(await Ye(t.removingPath))throw new w(`Release cleanup is incomplete: an interrupted removal left ${t.removingPath}; delete it and its artifacts directory to finish cleanup`);return null}throw new w(`Failed to inspect active release ledger at ${t.activePath}: ${M(a)}`)}if(!r.isFile()||r.isSymbolicLink())throw new w(`Invalid active release ledger at ${t.activePath}: expected a regular file`);let n;try{n=await Ro(t.activePath,"utf-8")}catch(a){if(Y(a,"ENOENT"))return null;throw new w(`Failed to read active release ledger at ${t.activePath}: ${M(a)}`)}let i;try{i=JSON.parse(n)}catch(a){throw new w(`Failed to parse active release ledger at ${t.activePath}: ${M(a)}`)}let s=Bt(i,t);return await jt(s,t),await Ft(t,s.id),await Br(s,t),new ye(s,t)}get data(){return structuredClone(this.value)}get id(){return this.value.id}get phase(){return this.value.phase}async setPhase(e){if(this.assertActive("set phase"),e==="completed")throw new w("Cannot set release phase to completed: use complete() instead");if(!Po(e))throw new w(`Cannot set release phase: unknown phase ${String(e)}`);if(e===this.value.phase)return;let t=We.indexOf(this.value.phase);if(We.indexOf(e)<t)throw new w(`Cannot move release phase backwards from ${this.value.phase} to ${e}`);let n=structuredClone(this.value);n.phase=e,await this.persist(n)}async setReleaseCommit(e){this.assertActive("set release commit");let t=mt(e,"releaseCommit");if(!this.value.expectedReleaseTree)throw new w("Cannot set release commit before the expected release tree");if(this.value.releaseCommit===t)return;if(this.value.releaseCommit)throw new w(`Cannot replace release commit ${this.value.releaseCommit} with ${t} in release ${this.value.id}`);let r=structuredClone(this.value);r.releaseCommit=t,await this.persist(r)}async setExpectedReleaseTree(e){this.assertActive("set expected release tree");let t=mt(e,"expectedReleaseTree");if(this.value.expectedReleaseTree===t)return;if(this.value.expectedReleaseTree)throw new w(`Cannot replace expected release tree ${this.value.expectedReleaseTree} with ${t} in release ${this.value.id}`);if(this.value.releaseCommit)throw new w(`Cannot set expected release tree after release commit ${this.value.releaseCommit}`);let r=structuredClone(this.value);r.expectedReleaseTree=t,await this.persist(r)}async markTagsReady(){if(this.assertActive("mark release tags ready"),!this.value.options.tags)return;if(!this.value.releaseCommit)throw new w("Cannot mark release tags ready without a release commit");if(this.value.tagsReady)return;let e=structuredClone(this.value);e.tagsReady=!0,await this.persist(e)}async setArtifact(e,t){if(this.assertActive("set artifact"),this.getPackage(e).isPrivate)throw new w(`Cannot store an artifact for private package ${e}`);let n=this.value.operations.npm[e];if(!n)throw new w(`Cannot store an artifact for unconfigured npm package ${e}`);if(n.state!=="pending")throw new w(`Cannot replace artifact for ${e} after its npm operation has started`);if(Lg(t)!==".tgz")throw new w(`Cannot store artifact for ${e}: source must be a .tgz file`);let i;try{i=await Eg(t)}catch(m){throw new w(`Cannot read source artifact for ${e} at ${t}: ${M(m)}`)}if(!i.isFile())throw new w(`Cannot store artifact for ${e}: source is not a regular file`);await Ft(this.paths,this.value.id);let s=oi(this.paths,this.value.id,e),a=Ag(this.artifactsDirectory,`.${Rg()}.tgz.tmp`),o;try{await $g(t,a,kg.COPYFILE_EXCL),await re(a),await Nt(this.paths,this.value.id,a),o=await Ur(a);try{await Cg(a,s)}catch(m){if(!Y(m,"EEXIST"))throw m;if(await Nt(this.paths,this.value.id,s),await Ur(s)!==o){let u=this.value.artifacts[e]?`A different durable artifact already exists for ${e} at ${s}`:`A different durable artifact already exists for ${e} at ${s}; the ledger records no artifact for it, so it is likely left by an interrupted run - delete the file and retry`;throw new w(u)}}await $o(a,{force:!0}),await re(this.artifactsDirectory),await Nt(this.paths,this.value.id,s)}catch(m){await ai(a,m,`Failed to clean temporary artifact for ${e}`)}if(!o)throw new w(`Failed to calculate artifact integrity for ${e}`);let c={integrity:o,path:Gr(this.paths,this.value.id,e)},p=structuredClone(this.value);return de(p.artifacts,e,c),await this.persist(p),{...c}}resolveArtifactPath(e){let t=this.value.artifacts[e];if(!t)throw new w(`Release artifact is not configured for ${e}`);return xg(this.releaseDirectory,t.path)}async configurePush(e,t,r){if(this.assertActive("configure push"),!this.value.options.push&&!this.value.options.tags)throw new w("Cannot configure push: neither push nor tags are enabled for this release");let n=ui({destination:t,refs:r,remote:e},"configurePush"),i=this.value.operations.push;if(i){if(JSON.stringify([i.remote,i.destination,i.refs])===JSON.stringify([n.remote,n.destination,n.refs]))return;throw new w("Cannot replace an existing push configuration")}let s=structuredClone(this.value);s.operations.push={...n,state:"pending"},await this.persist(s)}async configureProviderRelease(e,t){if(this.assertActive("configure provider release"),this.getPackage(e),!this.value.options.createRelease)throw new w("Cannot configure a provider release when createRelease is disabled");let r=di(t,`providerReleases.${e}`),n=this.value.operations.providerReleases[e];if(n){if(n.tag===r.tag&&n.title===r.title&&n.notes===r.notes)return;throw new w(`Cannot replace provider release configuration for ${e}`)}let i=structuredClone(this.value);de(i.operations.providerReleases,e,{...r,state:"pending"}),await this.persist(i)}async markNpm(e,t){this.assertActive("mark npm operation");let r=this.value.operations.npm[e];if(!r)throw new w(`Npm operation is not configured for package ${e}`);if(r.state===t)return;if(t==="started"&&!this.value.artifacts[e])throw new w(`Cannot start npm operation for ${e} without a durable artifact`);let n=structuredClone(this.value);de(n.operations.npm,e,Hr(r,t,this.operationTimestamp())),await this.persist(n)}async setNpmRegistry(e,t){this.assertActive("set npm registry");let r=this.value.operations.npm[e];if(!r)throw new w(`Npm operation is not configured for package ${e}`);if(r.state!=="pending")throw new w(`Cannot change npm registry for ${e} after publication has started`);let n=wi(t,`operations.npmRegistries.${e}`),i=this.value.operations.npmRegistries[e];if(i===n)return;if(i)throw new w(`Cannot replace npm registry for ${e}`);let s=structuredClone(this.value);de(s.operations.npmRegistries,e,n),await this.persist(s)}async markPush(e){this.assertActive("mark push operation");let t=this.value.operations.push;if(!t)throw new w("Push operation is not configured");if(t.state===e)return;let r=structuredClone(this.value);r.operations.push={destination:t.destination,refs:t.refs,remote:t.remote,...Hr(t,e,this.operationTimestamp())},await this.persist(r)}async markProviderRelease(e,t){this.assertActive("mark provider release operation");let r=this.value.operations.providerReleases[e];if(!r)throw new w(`Provider release is not configured for package ${e}`);if(r.state===t)return;let n=structuredClone(this.value);de(n.operations.providerReleases,e,{notes:r.notes,tag:r.tag,title:r.title,...Hr(r,t,this.operationTimestamp())}),await this.persist(n)}hasExternalProgress(){return mi(this.value)}async complete(){this.assertActive("complete");let e=structuredClone(this.value);if(e.phase!=="completed")fi(e),e.phase="completed",await this.persist(e),e=this.value;await mo(this.paths);let t=ci(this.paths,e.id);if(await Ye(t))throw new w(`Cannot complete release ${e.id}: history ledger already exists at ${t}`);try{await ko(this.activePath,t),await re(this.paths.historyDirectory),await re(this.releaseDirectory)}catch(r){throw new w(`Failed to move completed release ${e.id} to history: ${M(r)}`)}return this.active=!1,t}async remove(){this.assertActive("remove");let e=await Nr(this.releaseDirectory);try{await Ft(this.paths,this.value.id);let t=Bt(JSON.parse(await Ro(this.activePath,"utf-8")),this.paths);if(await jt(t,this.paths),await Br(t,this.paths),t.id!==this.value.id||t.updatedAt!==this.value.updatedAt)throw new w("Active release ledger changed in another process");if(mi(t))throw new w(`Cannot remove release ${t.id}: an external operation has started`);await ko(this.activePath,this.paths.removingPath),await re(this.releaseDirectory),await $o(this.artifactsDirectory,{force:!0,recursive:!0}),await Ig(this.paths.removingPath),await re(this.releaseDirectory)}catch(t){if(t instanceof w)throw t;throw new w(`Failed to remove release ${this.value.id}: ${M(t)}`)}finally{await At(e)}this.active=!1}async persist(e){e.updatedAt=yi(this.value.updatedAt);let t=Bt(e,this.paths);await jt(t,this.paths),await Br(t,this.paths),await si(this.activePath,t,!0,this.value.updatedAt),this.value=t}getPackage(e){let t=this.value.packages.find((r)=>r.name===e);if(!t)throw new w(`Unknown release package ${e}`);return t}operationTimestamp(){return yi(this.value.updatedAt)}assertActive(e){if(!this.active)throw new w(`Cannot ${e}: release ledger ${this.value.id} is no longer active`)}}class Ie{config;packageUpdater=new Ct;changelogGenerator;remoteParser=new Rt;stoneManager;provider=null;commitUrlFn=null;options;createdTags=[];createdTagTargets=new Map;commitCreated=!1;createdCommit=null;irreversibleOperation=null;ownedPaths=null;repositoryRoot=null;rollbackBlockedReason=null;ignoredBuildInputsValidated=!1;preparedNpmPublish=null;ledger=null;publishContext=null;constructor(e,t){this.config=e;this.options=t,this.changelogGenerator=new _e(this.config.get("changelog")),this.stoneManager=new I(this.config)}static async assertNoActiveRelease(){let e=await ye.loadActive();if(!e)return;throw new g(`Release ${e.id} is incomplete`,"Run sis roll --resume before starting another release")}static async resume(e){let t=await ye.loadActive();if(!t)throw new g("No incomplete release found","Run sis roll to start a release");let r=t.data,n=new Ie(e,r.options);n.ledger=t;let i=r.packages.map((a)=>new Q({file:a.file,isPrivate:a.isPrivate,name:a.name,newVersion:a.newVersion,version:a.oldVersion})),s=r.stones.map((a)=>A.fromJson(a));if(n.createdTags=[...r.releaseTags],r.phase==="completed")return await t.complete(),{packages:i};try{if(await n.recoverReleaseCommit(r),await Ia(t.data),await n.ensureLedgerPlan(i,s),r.options.npm){if(i.some((o)=>t.data.operations.npm[o.name]&&!t.data.artifacts[o.name]))await kr(await n.getRepositoryRoot());await n.prepareNpmPublish(i)}if(t.phase==="planned")await t.setPhase("local-ready");return await n.resumeExternalOperations(i,s),{packages:i}}catch(a){if(a instanceof g||!n.hasCrossedIrreversibleBoundary())throw a;throw n.createIncompleteReleaseError(a)}}async initializeExternalRelease(e,t,r){if(this.options.dryRun||!this.needsReleaseLedger(r))return;this.ledger=await ye.create({options:{...this.options,npmTag:this.options.npm?Ga(this.config.get("tag")):lr,publishOnly:r},packages:e.map((n)=>({file:n.file,isPrivate:n.isPrivate,name:n.name,newVersion:n.newVersion,version:n.version})),stones:t})}async finalizeExternalRelease(e,t){if(!this.ledger)return;if(this.options.npm||this.ledger.data.options.publishOnly)await kr(await this.getRepositoryRoot());let r=await oe();await this.ensureExpectedReleaseTree(this.ledger.data,r),await gt(this.ledger.data,r),await this.ledger.setReleaseCommit(r),await this.ensureLedgerPlan(e,t)}async markExternalReleaseReady(){if(this.ledger)await this.ledger.setPhase("local-ready")}async completeRelease(){if(this.ledger)await this.ledger.complete()}async getProvider(){if(!this.provider){let e=this.ledger?.data.operations.push?.destination,t=Ir(e);this.provider=await it(t)}return this.provider}async initCommitLinks(){if(this.commitUrlFn!==null)return;let e=this.ledger?.data.operations.push?.destination,t=Ir(e);if(t){this.commitUrlFn=kn(t);return}let r=await this.remoteParser.getRemoteInfo();this.commitUrlFn=r?.commitUrl??null}async preflight(e,t){if(this.options.dryRun)return;await Ie.assertNoActiveRelease();let r=await this.getOwnedPaths(e,t);await $a(r,await this.getRepositoryRoot());let n=r.map((s)=>Fe(s));if((await x(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${n}`.quiet(),"Failed to inspect release files")).stdout.length===0)return;throw new g("Release files have uncommitted changes",`Commit or stash these files:
156
+ ...and ${a} more`:""}`)}for(let{mode:o,path:a}of zr(n.stdout.toString()))if(o==="160000")await Rn(Ve(e,a),`${t}${a}/`,r)}function zr(e){return e.split("\x00").filter(Boolean).map((t)=>{let r=t.indexOf("\t"),s=r<0?[]:t.slice(0,r).split(" "),[n,,i,...o]=s,a=r<0?"":t.slice(r+1);if(!n||!i||o.length>0||!a)throw Error("Unable to parse Git index while collecting tracked package inputs");return{mode:n,path:a,stage:i}})}async function Kr(e,t=""){let r=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),s=new Set;for(let{mode:n,stage:i,path:o}of zr(r.stdout.toString())){if(i!=="0")throw new u(`Repository has an unresolved index entry: ${o}`);let a=`${t}${o}`;if(s.add(a),n!=="160000")continue;let c=await Kr(Ve(e,o),`${a}/`);for(let l of c)s.add(l)}return s}async function Yr(e){let t=new Uint8Array(await Bun.file(e).arrayBuffer()),r=Bun.gunzipSync(t),s=new TextDecoder;for(let n=0;n+Jr<=r.length;){let i=vn(r,n,Hp,s);if(!i)break;let o=vn(r,n+Jp,zp,s),a=o?`${o}/${i}`:i,c=vn(r,n+qp,Wp,s).trim(),l=Number.parseInt(c,8);if(!Number.isSafeInteger(l)||l<0)throw Error(`Invalid tar entry size for ${a}`);let d=n+Jr,g=d+l;if(g>r.length)throw Error(`Truncated tar entry for ${a}`);if(a===Kp)return s.decode(r.subarray(d,g));n=d+Math.ceil(l/Jr)*Jr}throw Error("Packed artifact does not contain package/package.json")}function vn(e,t,r,s){let n=e.subarray(t,t+r),i=n.indexOf(0);return s.decode(i<0?n:n.subarray(0,i))}function Ta(e,t){return JSON.stringify(Pt(JSON.parse(e)))===JSON.stringify(Pt(JSON.parse(t)))}var Qp="160000",ed="./";function Aa(e){let t=e?.command??[...Ys],r=e?.root??[],s=e?.outputs??[];Xr(t,"release.build.command"),Xr(r,"release.build.root"),Xr(s,"release.build.outputs"),Ia(t,"release.build.command");for(let[n,i]of r.entries())if(Xr(i,`release.build.root[${n}]`),Ia(i,`release.build.root[${n}]`),i.length===0)throw new u(`Invalid release.build.root[${n}]`,'Each root build command must be a non-empty array of arguments, e.g. ["bun", "run", "build:dts"]');for(let n of s)if(!n||Zp(n)||n.startsWith(ed)||rd(n))throw new u(`Invalid release.build.outputs entry: ${n||"(empty)"}`,"Build output globs must be relative to the repository root, e.g. packages/*/dist/**");if(s.length>0&&t.length===0&&r.length===0)throw new u("release.build.outputs is declared but no build command runs","Set release.build.command or release.build.root, or remove the declared outputs");return{command:t,matcher:bn(s),outputs:s,root:r}}async function Oa(e,t){if(t===Ue)return;let r=await Kr(e);for(let s of r){if(!t.isOutput(s))continue;throw new u(`Declared build output ${s} is tracked by Git`,"Add it to .gitignore, or narrow release.build.outputs so it excludes committed files")}}async function Sn(e,t,r){if(r===Ue)return 0;let s=0;for(let i of await Pn(e,t)){if(!r.isOutput(i))continue;await Xp(Ea(e,i.slice(t.length)),{force:!0}),s+=1}let n=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet();for(let{mode:i,path:o}of zr(n.stdout.toString())){if(i!==Qp)continue;s+=await Sn(Ea(e,o),`${t}${o}/`,r)}return s}async function Cn(e,t,r){let s=td(e,t,r),n,i;try{[n,i]=await Promise.all([s.exited,new Response(s.stderr).text(),new Response(s.stdout).text()])}catch(o){throw s.kill(),o}if(n!==0)throw Error(`${r}: ${i.trim()||`${e[0]} exited with code ${n}`}`)}function td(e,t,r){try{return Bun.spawn([...e],{cwd:t,stderr:"pipe",stdout:"pipe"})}catch(s){throw Error(`${r}: ${s instanceof Error?s.message:String(s)}`)}}function Xr(e,t){if(Array.isArray(e))return;throw new u(`Invalid ${t}`,`${t} must be an array`)}function rd(e){if(ne(e))return!0;return e.split("/").includes("..")}function Ia(e,t){for(let r of e){if(typeof r==="string"&&r.length>0)continue;throw new u(`Invalid ${t}`,"Every build command argument must be a non-empty string")}}import{dirname as sd,join as nd}from"path";function _a(e,t,r){let s=r.map((i)=>`- ${i.name}@${i.newVersion??i.version}`).join(`
157
+ `);return`${e.replace("{message}",()=>t.message).replace("{packages}",()=>r.map((i)=>i.name).join(", "))}
158
+
159
+ ${s}`}function Ma(e){let{author:t,email:r}=e,s=t.trim(),n=r?.trim()??"";if(!s&&!n)return[];if(!s||!/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(n))throw new u("Invalid release commit author","Set valid commit.author and commit.email");return["--author",`${s} <${n}>`]}function La(e){let{author:t,email:r}=e,s={...process.env};if(!t)return s;if(s.GIT_COMMITTER_NAME=t,r)s.GIT_COMMITTER_EMAIL=r;return s}function Da(e,t){let{filename:r,root:s}=e,n=t.map((i)=>nd(sd(i.file),r));if(s)n.push(r);return n}import{mkdtemp as pd,rm as dd}from"fs/promises";import{tmpdir as gd}from"os";import{join as Ga}from"path";import{createHash as od}from"crypto";import{lstat as ad,realpath as Na}from"fs/promises";import{dirname as cd,isAbsolute as ld,relative as ja,resolve as kn,sep as ud}from"path";async function O(e,t){try{return await e()}catch(r){let s=Zr(r);throw Error(s?`${t}: ${s}`:t)}}function Zr(e){let t=id(e);if(t)return t;return e instanceof Error?e.message:String(e)}function id(e){if(e&&typeof e==="object"&&"stderr"in e){let t=e.stderr;if(t instanceof Buffer)return t.toString().trim();if(typeof t==="string")return t.trim()}return}function Ge(e){return`:(top,literal)${e}`}async function ie(){let t=(await O(()=>Bun.$`git rev-parse HEAD`.quiet(),"Failed to resolve release commit")).stdout.toString().trim();if(!t)throw Error("Release commit is empty");return t}async function xn(){let e=await Bun.$`git symbolic-ref -q HEAD`.quiet().nothrow();if(e.exitCode===1)return null;if(e.exitCode!==0)throw new u("Failed to resolve the current Git reference");return e.stdout.toString().trim()||null}async function Ba(e){let t=await Bun.$`git rev-parse --verify ${e}`.quiet().nothrow();if(t.exitCode!==0)return null;return t.stdout.toString().trim()||null}async function Tn(e){let t=e.map((o)=>Ge(o)),[r,s,n]=await Promise.all([Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${t}`.quiet(),Bun.$`git diff --cached --binary --no-ext-diff -- ${t}`.quiet(),Bun.$`git diff --binary --no-ext-diff -- ${t}`.quiet()]),i=od("sha256");for(let o of[r.stdout,s.stdout,n.stdout])i.update(String(o.length)),i.update("\x00"),i.update(o);return i.digest("hex")}function Fa(e,t){let r=ld(t)?kn(t):kn(e,t),s=ja(e,r);if(!s||ne(s))throw new u(`Release-owned path is outside the repository: ${t}`);return s.split(ud).join("/")}async function Ua(e,t){let r=await Na(t);for(let s of e){let n=kn(t,s),i=await ad(n).catch(()=>null);if(i?.isSymbolicLink())throw new u(`Release-owned path is a symbolic link: ${s}`);let o=i?n:cd(n),a=await Na(o);if(ne(ja(r,a)))throw new u(`Release-owned path escapes the repository: ${s}`)}}async function En(e){let t=e.map((r)=>Ge(r));await O(()=>Bun.$`git reset --quiet HEAD -- ${t}`.quiet(),"Failed to unstage release-owned files")}async function qt(e){if((await Wt(e)).length===0)return;throw new u("Repository source files changed after the release commit","Commit or stash all source changes before preparing npm artifacts")}async function Wt(e){return await yn(e),(await O(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(e).quiet(),"Failed to inspect release source files")).stdout}async function Va(e,t,r,s){let n=[];if(e)n.push(`update ${e.ref??"HEAD"} ${e.baseCommit} ${e.oid}`);for(let a of t){let c=r.get(a);if(!c)throw Error(`Missing rollback target for release tag ${a}`);n.push(`delete refs/tags/${a} ${c}`)}if(n.length===0)return;let i=await s(),o=Buffer.from(["start",...n,"prepare","commit",""].join(`
160
+ `));await O(async()=>{let a=Bun.spawn(["git","update-ref","--stdin"],{cwd:i,stderr:"pipe",stdin:o,stdout:"pipe"}),[c,l]=await Promise.all([a.exited,new Response(a.stderr).text()]);if(c!==0)throw Error(l.trim()||`git update-ref exited with code ${c}`)},"Failed to atomically restore release refs")}async function Ha(e,t,r){let s=await pd(Ga(gd(),"sisyphus-index-")),n=Ga(s,"index"),i={...process.env,GIT_INDEX_FILE:n},o=t.map((a)=>Ge(a));try{await O(()=>Bun.$`git read-tree ${e}`.cwd(r).env(i).quiet(),"Failed to initialize release tree"),await O(()=>Bun.$`git add -A -- ${o}`.cwd(r).env(i).quiet(),"Failed to build release tree");let c=(await O(()=>Bun.$`git write-tree`.cwd(r).env(i).quiet(),"Failed to write release tree")).stdout.toString().trim();if(!c)throw Error("Git returned an empty release tree object ID");return c}finally{await dd(s,{force:!0,recursive:!0})}}async function qa(e){if(!e.releaseCommit)throw new u(`Release ${e.id} has no recorded source commit`,"No external operation will be retried; inspect the local release state manually");let t=await ie();if(t!==e.releaseCommit)throw new u(`Release ${e.id} was prepared from ${e.releaseCommit}, but HEAD is ${t}`,`Check out ${e.releaseCommit} before resuming`);if(!e.expectedReleaseTree)throw new u(`Release ${e.id} has no recorded expected release tree`,"No external operation will be retried; inspect the release ledger manually");await Rt(e,t)}async function Rt(e,t){if(!e.expectedReleaseTree)throw new u(`Release ${e.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");if(e.options.publishOnly){if(t!==e.baseCommit)throw new u(`Publish-only release ${e.id} must use commit ${e.baseCommit}, found ${t}`,`Check out ${e.baseCommit} before resuming`)}else await In(t,e.baseCommit,e.id);await An(t,e.expectedReleaseTree,e.id)}async function In(e,t,r){let s=await O(()=>Bun.$`git rev-list --parents -n 1 ${e}`.quiet(),"Failed to resolve release commit parent"),[n,...i]=s.stdout.toString().trim().split(/\s+/);if(n===e&&i.length===1&&i[0]===t)return;let o=r?` for release ${r}`:"";throw new u(`Release commit parent${o} does not match ${t}`,"No external operation was attempted; inspect the release commit ancestry")}async function An(e,t,r){let s=await On(e);if(s===t)return;let n=r?` for release ${r}`:"";throw new u(`Release commit tree${n} is ${s}, expected ${t}`,"No external operation was attempted; inspect the release commit for unrelated tracked changes")}async function On(e){let t=`${e}^{tree}`,s=(await O(()=>Bun.$`git rev-parse ${t}`.quiet(),"Failed to resolve release commit tree")).stdout.toString().trim();if(!s)throw Error(`Git returned an empty tree object ID for ${e}`);return s}import{dirname as bd}from"path";import{readFile as md}from"fs/promises";import{dirname as Wa}from"path";var hd=/^[A-Za-z][0-9A-Za-z._-]*$/,fd=/-\d{14,}$/,yd=/^(?:[vV]?\d+(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?|[xX])$/;function _n(e){return hd.test(e)&&!yd.test(e)}function es(e){let t=(e||de).trim();if(!_n(t))throw new u(`Invalid npm dist-tag "${t}"`,"Use a non-semver tag containing only letters, numbers, dots, underscores, or hyphens");return t}function Jt(e,t){let r=es(t),s=new Set;for(let n of e){if(n.isPrivate)continue;let i=n.newVersion??n.version,o=Ie(i);if(!o)throw new u(`Cannot derive an npm dist-tag for ${n.name}@${i}`,"The version is not valid SemVer; fix it before publishing");if(o.prerelease.length===0){s.add(r);continue}let a=wd(o);if(!a||!_n(a))throw new u(`Cannot derive an npm dist-tag for ${n.name}@${i}`,"Use a prerelease identifier that is a valid npm dist-tag (e.g. beta, rc)");s.add(a)}if(s.size<=1)return[...s][0]??r;throw new u(`Release mixes npm dist-tags (${[...s].sort().join(", ")})`,"Roll stable and prerelease packages separately, or give every prerelease the same tag")}function wd(e){let t=jt(e);if(t)return t;let[r]=e.prerelease;if(typeof r!=="string")return;return r.replace(fd,"")}function Ja(e){return e.startsWith("@")?e.split("/")[0]:void 0}function ts(e,t){let r=Ja(e);return r?[`--${r}:registry=${t}`]:[]}async function za(e){let t=Ja(e.name);if(t){let o=await Bun.$`npm config get ${`${t}:registry`}`.cwd(Wa(e.file)).quiet().nothrow();if(o.exitCode===0){let a=o.stdout.toString().trim();if(a&&a!=="undefined"&&a!=="null"){let c=Qr(a);if(c)return c;throw new u(`Invalid ${t}:registry for ${e.name}`,"Registry must be a credential-free HTTP or HTTPS URL")}}}let s=(await Ya(e)).publishConfig;if(s!==void 0){if(typeof s!=="object"||s===null||Array.isArray(s))throw new u(`Invalid publishConfig in ${e.name}`,"publishConfig must be an object");let o=Reflect.get(s,"registry");if(o!==void 0){if(typeof o!=="string")throw new u(`Invalid publishConfig.registry in ${e.name}`,"Registry must be an HTTP or HTTPS URL");let a=Qr(o);if(!a)throw new u(`Invalid publishConfig.registry in ${e.name}`,"Registry must be a credential-free HTTP or HTTPS URL");return a}}let n=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(n){let o=Qr(n);if(o)return o}let i=await Bun.$`npm config get registry`.cwd(Wa(e.file)).quiet().nothrow();if(i.exitCode===0){let o=i.stdout.toString().trim();if(o&&o!=="undefined"&&o!=="null"){let a=Qr(o);if(a)return a}}throw new u(`Cannot resolve a credential-free npm registry for ${e.name}`,"Configure registry or @scope:registry as an HTTP or HTTPS URL without embedded credentials")}function Qr(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.search||t.hash)return;return t.href}catch{return}}function Ka(e){let t=Array.isArray(e)?e.length===1?e[0]:void 0:e;if(typeof t!=="object"||t===null||Array.isArray(t))return;let r=Reflect.get(t,"name"),s=Reflect.get(t,"version"),n=Reflect.get(t,"dist");if(typeof n!=="object"||n===null||Array.isArray(n))return;let i=Reflect.get(n,"integrity");if(typeof r!=="string"||typeof s!=="string"||typeof i!=="string")return;return{integrity:i,name:r,version:s}}async function Ya(e){let t;try{t=await md(e.file,"utf-8")}catch(s){throw Error(`Failed to read ${e.name}: ${Zr(s)}`)}let r;try{r=JSON.parse(t)}catch(s){throw Error(`Failed to parse ${e.name}: ${Zr(s)}`)}if(typeof r!=="object"||r===null||Array.isArray(r))throw Error(`Invalid ${e.name} manifest object`);return r}async function Xa(e){let t=[];for(let r of e){let n=(await Ya(r)).private;if(n!==void 0&&typeof n!=="boolean")throw Error(`Failed to validate ${r.name} manifest: "private" must be a boolean`);if(n)continue;t.push(r)}return t}async function Za(e,t){let r=e.data.artifacts[t.name];if(!r)throw Error(`Release artifact is missing for ${t.name}`);let s=e.data.operations.npmRegistries[t.name];if(!s)throw Error(`Npm registry is not configured for ${t.name}`);let n=t.newVersion??t.version,i=`${t.name}@${n}`,o=ts(t.name,s),a=await Bun.$`npm view ${i} --json --registry ${s} ${o}`.cwd(bd(t.file)).quiet().nothrow();if(a.exitCode!==0)throw new u(`Cannot safely resume npm publication for ${i}`,`The registry at ${s} does not confirm ${i}; if the version is truly absent, publish the durable artifact at ${e.resolveArtifactPath(t.name)} manually and re-run sis roll --resume`);let c;try{c=JSON.parse(a.stdout.toString())}catch{throw new u(`Cannot safely resume npm publication for ${i}`,"Registry metadata is not valid JSON")}let l=Ka(c);if(!l)throw new u(`Cannot safely resume npm publication for ${i}`,"Registry metadata does not report name, version, and dist.integrity; verify the upload manually");if(l.name!==t.name||l.version!==n||l.integrity!==r.integrity)throw new u(`Cannot safely resume npm publication for ${i}: artifact integrity does not match`,"Do not republish this version; compare the registry artifact with the durable release artifact");await e.markNpm(t.name,"completed")}import{resolve as vd}from"path";import{pathToFileURL as $d}from"url";async function rs(e,t){let r=Xe(e);return{canonicalUrl:await Pd(e,t),...r?{owner:r.owner,provider:r.provider,repo:r.repo}:{}}}async function Pd(e,t){let r=null;try{r=new URL(e)}catch{r=null}if(r){let n=r.protocol==="ssh:"||r.protocol==="git+ssh:";if(r.password||r.username&&!n)throw new u("Push URL contains embedded credentials","Configure git authentication outside the remote URL");return r.search="",r.hash="",r.href}let s=e.match(/^(?:([^@/\s]+)@)?([^:/\s]+):(.+)$/);if(s?.[2]&&s[3])return`ssh://${s[1]?`${s[1]}@`:""}${s[2].toLowerCase()}/${s[3].replace(/^\/+/,"")}`;return $d(vd(await t(),e)).href}function ss(e){if(!e?.provider||!e.owner||!e.repo)return;return{owner:e.owner,provider:e.provider,repo:e.repo}}async function ns(e){let r=(await O(()=>Bun.$`git remote get-url --push --all ${e}`.quiet(),`Failed to resolve push URL for ${e}`)).stdout.toString().trim().split(`
161
+ `).filter(Boolean);if(r.length!==1)throw new u(`Push remote ${e} must have exactly one push URL, found ${r.length}`,"Remove additional push URLs before starting or resuming a release");let[s]=r;if(!s)throw new u(`Push remote ${e} has no URL`);return s}async function St(e,t){let r=await ns(e.remote),s=await rs(r,t);if(JSON.stringify(s)!==JSON.stringify(e.destination))throw new u(`Push remote ${e.remote} no longer matches the recorded release destination`,"Restore the original remote before resuming the release");return r}async function Ln(e){for(let t of e){let s=(await O(()=>Bun.$`git rev-parse ${t.source}`.quiet(),`Failed to resolve ${t.source}`)).stdout.toString().trim();if(s!==t.oid)throw new u(`Release ref ${t.source} points to ${s}, expected ${t.oid}`,"Do not move release refs before the release completes")}}async function is(e,t){let r=await St(e,t),s=e.refs.map((n)=>`${n.oid}:${n.destination}`);await O(()=>Bun.$`git push --atomic ${r} ${s}`.quiet(),"Failed to atomically push release refs")}async function Qa(e,t,r=e.refs){let s=await Dn(e,r,t),n=r.find((i)=>s.get(i.destination)!==i.oid);if(n)throw new u(`Cannot safely resume remote push: ${n.destination} is not at ${n.oid}`,"The previous push may not have completed; inspect the remote refs manually")}async function Dn(e,t,r){let s=await St(e,r),n=t.map((o)=>o.destination),i=await O(()=>Bun.$`git ls-remote --refs ${s} ${n}`.quiet(),"Failed to inspect remote release refs");return new Map(i.stdout.toString().trim().split(`
162
+ `).filter(Boolean).map((o)=>{let[a="",c=""]=o.split("\t");return[c,a]}))}async function Nn(){let e=await Bun.$`git symbolic-ref --quiet --short HEAD`.quiet().nothrow();if(e.exitCode!==0)return;return e.stdout.toString().trim()||void 0}async function ec(){let e=await Nn();if(!e)throw new u("Cannot push a release from detached HEAD","Check out the branch that should receive the release");return{branch:e,remote:await jn(e)}}async function jn(e){let t=e?await Mn(`branch.${e}.pushRemote`):null,r=await Mn("remote.pushDefault"),s=e?await Mn(`branch.${e}.remote`):null,n=t??r??s;if(!n){let o=(await O(()=>Bun.$`git remote`.quiet(),"Failed to list git remotes")).stdout.toString().trim().split(`
163
+ `).filter(Boolean);if(o.length===1&&o[0]==="origin")n="origin"}if(!n){let i=e?` for branch ${e}`:"";throw new u(`No push remote is configured${i}`,e?"Configure a branch push remote or remote.pushDefault":"Configure remote.pushDefault")}return await O(()=>Bun.$`git remote get-url --push ${n}`.quiet(),`Invalid push remote ${n}`),n}async function Mn(e){let t=await Bun.$`git config --get ${e}`.quiet().nothrow();if(t.exitCode===1)return null;if(t.exitCode!==0){let s=t.stderr.toString().trim();throw Error(s?`Failed to read git config ${e}: ${s}`:`Failed to read git config ${e}`)}let r=t.stdout.toString().trim();if(!r)throw Error(`Git config ${e} is empty`);return r}var Rd=1;async function rc(e,t,r){let s=await Dn(t,t.refs,r),n=[];for(let i of t.refs){let o=s.get(i.destination);if(o===i.oid)continue;if(!o){n.push(i);continue}if(i.destination.startsWith("refs/heads/")){if(await Sd(o,t,r),await tc(i.oid,o))continue;if(await tc(o,i.oid)){n.push(i);continue}}throw new u(`Cannot safely resume remote push: ${i.destination} is not at ${i.oid}`,"The remote ref diverged from the recorded release; inspect it manually before resuming")}if(n.length>0)await is({...t,refs:n},r);await e.markPush("completed")}async function Sd(e,t,r){if((await Bun.$`git cat-file -e ${`${e}^{commit}`}`.quiet().nothrow()).exitCode===0)return;let n=await St(t,r);await O(()=>Bun.$`git fetch --no-tags --no-write-fetch-head --no-recurse-submodules ${n} ${e}`.quiet(),"Failed to inspect the remote branch ancestry")}async function tc(e,t){let r=await Bun.$`git merge-base --is-ancestor ${e} ${t}`.quiet().nothrow();if(r.exitCode===0)return!0;if(r.exitCode===Rd)return!1;throw Error(`Failed to inspect remote branch ancestry: ${r.stderr.toString().trim()}`)}function Bn(e,t,r){let s=t.newVersion??t.version;return{notes:kd(Cd(e,t.name),t,r),tag:`${t.name}@${s}`,title:`${t.name} v${s}`}}function Cd(e,t){return e.filter((r)=>r.affectsPackage(t))}function kd(e,t,r){let s=[],n=t.newVersion??t.version;if(s.push(`\`${t.name}\` ${t.version} \u2192 ${n}`),e.length===0)return s.join(`
164
+ `);s.push(""),s.push("<details>"),s.push(`<summary>Stones (${e.length})</summary>`),s.push("");for(let i of e){if(s.push(`### ${i.message}`),s.push(""),i.description)s.push(i.description),s.push("");let o=xd(i.commits,t.name);if(o.length>0){s.push("<details>"),s.push(`<summary>Commits (${o.length})</summary>`),s.push("");for(let a of o)s.push(Td(a,r));s.push(""),s.push("</details>"),s.push("")}}return s.push("</details>"),s.join(`
165
+ `)}function xd(e,t){if(!e)return[];return e.filter((r)=>r.packages.includes(t))}function Td(e,t){return`- ${t?`[\`${e.hash}\`](${t(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}import{createHash as sg,randomUUID as ng}from"crypto";import{constants as ig}from"fs";import{copyFile as og,link as ag,lstat as cg,readFile as Ec,rename as Ic,rm as Ac,stat as lg,unlink as ug}from"fs/promises";import{extname as pg,join as dg,resolve as gg}from"path";import{createHash as hc,randomUUID as jd}from"crypto";import{link as Bd,lstat as tr,mkdir as gs,open as Fd,readFile as fc,realpath as qe,rename as Ud,rm as Vd,unlink as Gd}from"fs/promises";import{dirname as Zt,isAbsolute as mc,join as Qt,relative as yc,resolve as be,sep as Hd}from"path";var zt=1,Ct=["planned","local-ready","external","completed"],Fn=["pending","started","completed"],Ed=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,tt=/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/,sc=/^sha512-[0-9A-Za-z+/]{86}==$/,nc=/^[0-9A-Za-z][0-9A-Za-z._/-]*$/,Un=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ic=/^(?:linux:[0-9a-f-]{36}:[0-9]+|ps:.+|windows:[0-9]+)$/i,os=2,oc=3,ac=19;class b extends Error{_tag="ReleaseLedgerError"}function P(e,t){throw new b(`Invalid release ledger at ${e}: ${t}`)}function Kt(e,t){if(typeof e!=="string")P(t,"must be a string");return e}function I(e,t){let r=Kt(e,t);if(!r.trim())P(t,"must be nonempty");return r}function rt(e,t){let r=I(e,t);if(!Ed.test(r))P(t,`invalid release ID ${r}`);return r}function as(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function X(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function _(e){return e instanceof Error?e.message:String(e)}import{randomUUID as Id}from"crypto";import{constants as cc,readFileSync as lc}from"fs";import{link as Ad,lstat as st,open as Hn,readFile as uc,rename as Od,rm as ls,unlink as us}from"fs/promises";import{hostname as pc}from"os";import{dirname as He,join as Vn}from"path";async function ds(e){let t=Vn(e,".write.lock");for(let r=0;r<oc;r+=1){let s=dc(process.pid);if(!s)throw new b("Failed to identify the release ledger lock owner process");let n={acquiredAt:new Date().toISOString(),hostname:pc(),ownerId:Id(),pid:process.pid,processStartedAt:s,schemaVersion:os},i=ps(e,n.ownerId,"owner");await _d(i,n);try{await Ad(i,t)}catch(a){if(await ls(i,{force:!0}),!X(a,"EEXIST"))throw new b(`Failed to acquire release ledger lock at ${t}: ${_(a)}`);let c=await Md(t);if(!c)continue;await Ld(c);continue}let o={lockPath:t,metadata:n,ownerPath:i};try{return await oe(e),o}catch(a){try{await Xt(o)}catch(c){throw AggregateError([a,c],`Failed to durably acquire release ledger lock at ${t}`)}throw new b(`Failed to durably acquire release ledger lock at ${t}: ${_(a)}`)}}throw new b(`Release ledger is locked by another process at ${t}: lock changed during acquisition`)}async function _d(e,t){let r;try{r=await Hn(e,"wx",384),await r.writeFile(`${JSON.stringify(t)}
166
+ `,"utf-8"),await r.sync()}catch(s){throw await ls(e,{force:!0}),new b(`Failed to create release ledger lock owner: ${_(s)}`)}finally{await r?.close()}await oe(He(e))}async function Md(e){let t,r,s;try{s=await Hn(e,cc.O_RDONLY|cc.O_NOFOLLOW),t=await s.stat(),r=await s.readFile("utf-8")}catch(d){if(X(d,"ENOENT"))return null;throw new b(`Failed to inspect release ledger lock at ${e}: ${_(d)}`)}finally{await s?.close()}if(!t.isFile())throw new b(`Release ledger is locked by another process at ${e}: lock owner is unknown`);let n=null;try{n=Gn(JSON.parse(r))}catch{n=null}if(!n)return await cs(e,t,"lock metadata is malformed");let i=ps(He(e),n.ownerId,"owner"),o=ps(He(e),n.ownerId,"claim"),a;try{a=await st(i)}catch(d){if(X(d,"ENOENT")){try{await st(o)}catch(g){if(X(g,"ENOENT"))return await cs(e,t,"stale lock ownership is incomplete");throw new b(`Failed to inspect release ledger lock claim: ${_(g)}`)}throw new b(`Release ledger is locked by another process at ${e}: stale lock recovery is incomplete (claim ${o} remains; remove both after verifying the owner process is dead)`)}throw new b(`Failed to inspect release ledger lock owner: ${_(d)}`)}if(!a.isFile()||a.isSymbolicLink())return await cs(e,t,"stale lock ownership is invalid");let c=null;try{c=Gn(JSON.parse(await uc(i,"utf-8")))}catch{c=null}if(!c||!Nd(n,c))return await cs(e,t,"stale lock ownership is invalid");if(!await gc(e,t))return null;if(!Yt(t,a))return{lockPath:e,lockStat:t,metadata:n,ownerPath:i,ownerStat:a};if(n.hostname!==pc())throw new b(`Release ledger is locked by another process at ${e}: lock owner is on an unknown host ${n.hostname} (pid ${n.pid})`);let l=Dd(n);if(l==="alive")throw new b(`Release ledger is locked by another process at ${e}: lock owner is still live (pid ${n.pid} on ${n.hostname})`);if(l==="unknown")throw new b(`Release ledger is locked by another process at ${e}: lock owner liveness is unknown (pid ${n.pid} on ${n.hostname})`);return{lockPath:e,lockStat:t,metadata:n,ownerPath:i,ownerStat:a}}async function Ld(e){let t=ps(He(e.lockPath),e.metadata.ownerId,"claim");if(e.ownerPath!==t)try{await Od(e.ownerPath,t),await oe(He(e.lockPath))}catch(n){if(X(n,"ENOENT")||X(n,"EEXIST"))return;throw new b(`Failed to claim stale release ledger lock: ${_(n)}`)}let r,s;try{[r,s]=await Promise.all([st(e.lockPath),st(t)])}catch(n){if(X(n,"ENOENT"))return;throw new b(`Failed to verify stale release ledger lock: ${_(n)}`)}if(!Yt(e.lockStat,r))return;if(!Yt(e.ownerStat,s))return;try{await us(e.lockPath),await oe(He(e.lockPath)),await us(t),await oe(He(e.lockPath))}catch(n){if(X(n,"ENOENT"))return;throw new b(`Failed to recover stale release ledger lock: ${_(n)}`)}}async function Xt(e){let t,r;try{[t,r]=await Promise.all([st(e.lockPath),st(e.ownerPath)])}catch(n){if(X(n,"ENOENT"))throw await ls(e.ownerPath,{force:!0}),new b("Failed to release ledger write lock: ownership record is missing");throw new b(`Failed to inspect release ledger lock during release: ${_(n)}`)}if(!Yt(t,r))throw await ls(e.ownerPath,{force:!0}),new b("Failed to release ledger write lock: ownership changed");let s=null;try{s=Gn(JSON.parse(await uc(e.lockPath,"utf-8")))}catch{s=null}if(s?.ownerId!==e.metadata.ownerId)throw new b("Failed to release ledger write lock: owner identity changed");try{await us(e.lockPath),await us(e.ownerPath),await oe(He(e.lockPath))}catch(n){throw new b(`Failed to release ledger write lock: ${_(n)}`)}}function Gn(e){if(typeof e!=="object"||e===null||Array.isArray(e))return null;let t=e,r=Object.keys(t);if(r.length!==6||!r.every((s)=>["acquiredAt","hostname","ownerId","pid","processStartedAt","schemaVersion"].includes(s))||t.schemaVersion!==os||typeof t.ownerId!=="string"||!Un.test(t.ownerId)||typeof t.hostname!=="string"||!t.hostname||typeof t.pid!=="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.processStartedAt!=="string"||!ic.test(t.processStartedAt)||typeof t.acquiredAt!=="string"||!as(t.acquiredAt))return null;return{acquiredAt:t.acquiredAt,hostname:t.hostname,ownerId:t.ownerId,pid:t.pid,processStartedAt:t.processStartedAt,schemaVersion:os}}function ps(e,t,r){if(!Un.test(t))throw new b(`Release ledger is locked by another process at ${Vn(e,".write.lock")}: lock owner identity is malformed`);return Vn(e,`.write.lock.${t}.${r}`)}function Dd(e){try{process.kill(e.pid,0)}catch(r){return X(r,"ESRCH")?"dead":"unknown"}let t=dc(e.pid);if(!t)return"unknown";if(t.split(":",1)[0]!==e.processStartedAt.split(":",1)[0])return"unknown";return t===e.processStartedAt?"alive":"dead"}function dc(e){if(process.platform==="linux")try{let t=lc("/proc/sys/kernel/random/boot_id","utf-8").trim(),r=lc(`/proc/${e}/stat`,"utf-8"),s=r.lastIndexOf(")"),n=s<0?void 0:r.slice(s+1).trim().split(/\s+/)[ac];if(t&&n)return`linux:${t}:${n}`}catch{}if(process.platform==="win32")try{let t=Bun.spawnSync({cmd:["powershell.exe","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().Ticks`],stderr:"pipe",stdout:"pipe"}),r=t.stdout.toString().trim();if(t.exitCode===0&&/^[0-9]+$/.test(r))return`windows:${r}`}catch{return null}try{let t=Bun.spawnSync({cmd:["ps","-o","lstart=","-p",String(e)],env:{...process.env,LC_ALL:"C",TZ:"UTC"},stderr:"pipe",stdout:"pipe"});if(t.exitCode!==0)return null;let r=t.stdout.toString().trim().replace(/\s+/g," ");return r?`ps:${r}`:null}catch{return null}}function Yt(e,t){return e.dev===t.dev&&e.ino===t.ino}async function gc(e,t){try{return Yt(t,await st(e))}catch(r){if(X(r,"ENOENT"))return!1;throw new b(`Failed to verify release ledger lock at ${e}: ${_(r)}`)}}async function cs(e,t,r){if(!await gc(e,t))return null;throw new b(`Release ledger is locked by another process at ${e}: ${r}`)}function Nd(e,t){return e.schemaVersion===t.schemaVersion&&e.ownerId===t.ownerId&&e.hostname===t.hostname&&e.pid===t.pid&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}async function oe(e){let t=await Hn(e,"r");try{await t.sync()}finally{await t.close()}}async function qn(e){let t=be(e),r=await Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet().nothrow();if(r.exitCode!==0)throw new b(`Failed to resolve repository root from ${t}: ${r.stderr.toString().trim()||"git exited unsuccessfully"}`);let s=r.stdout.toString().trim();if(!s)throw new b(`Failed to resolve repository root from ${t}: empty git output`);let n=mc(s)?be(s):be(t,s),i=await Bun.$`git rev-parse --git-path sisyphus/release`.cwd(n).quiet().nothrow();if(i.exitCode!==0)throw new b(`Failed to resolve release ledger git path from ${n}: ${i.stderr.toString().trim()||"git exited unsuccessfully"}`);let o=i.stdout.toString().trim();if(!o)throw new b(`Failed to resolve release ledger git path from ${n}: empty git output`);let a=mc(o)?be(o):be(n,o);return{activePath:Qt(a,"active.json"),artifactsRoot:Qt(a,"artifacts"),historyDirectory:Qt(a,"history"),releaseDirectory:a,removingPath:Qt(a,"removing.json"),repositoryRoot:n}}async function wc(e,t){let r=`${t}^{tree}`,s=await Bun.$`git rev-parse ${r}`.cwd(e).quiet().nothrow(),n=s.stdout.toString().trim();if(s.exitCode!==0||!tt.test(n))throw new b(`Cannot resolve release tree for commit ${t}`);return n}async function rr(e,t){await gs(e.releaseDirectory,{recursive:!0}),await We(e.releaseDirectory,"release directory"),await gs(e.artifactsRoot,{recursive:!0}),await We(e.artifactsRoot,"artifacts root"),await gs(ir(e,t),{recursive:!0}),await bc(e,t)}async function bc(e,t){let r=ir(e,t);await We(e.releaseDirectory,"release directory"),await We(e.artifactsRoot,"artifacts root"),await We(r,`artifacts directory for release ${t}`);let s=await qe(e.releaseDirectory),n=await qe(e.artifactsRoot),i=await qe(r);return er(s,n,"Artifacts root escapes the release directory"),er(n,i,`Artifacts directory for release ${t} escapes the artifacts root`),i}async function vc(e){await We(e.releaseDirectory,"release directory"),await gs(e.historyDirectory,{recursive:!0}),await We(e.historyDirectory,"history directory");let t=await qe(e.releaseDirectory),r=await qe(e.historyDirectory);er(t,r,"History directory escapes the release directory")}async function ms(e,t){for(let[r,s]of Object.entries(e.artifacts)){let n=be(t.releaseDirectory,s.path);if(await nr(t,e.id,n),await hs(n)!==s.integrity)throw new b(`Invalid release ledger artifact for ${r}: sha512 integrity mismatch`)}}async function sr(e,t){let r=await qe(t.repositoryRoot);for(let s of e.packages){let n=be(t.repositoryRoot,s.file),i;try{i=await tr(n)}catch(a){throw new b(`Invalid package manifest for ${s.name} at ${s.file}: ${_(a)}`)}if(!i.isFile()||i.isSymbolicLink())throw new b(`Invalid package manifest for ${s.name} at ${s.file}: expected a regular file`);let o=await qe(n);er(r,o,`Package manifest for ${s.name} escapes the repository: ${s.file}`)}}async function nr(e,t,r){let s=await bc(e,t),n;try{n=await tr(r)}catch(o){throw new b(`Invalid release artifact at ${r}: ${_(o)}`)}if(!n.isFile()||n.isSymbolicLink())throw new b(`Invalid release artifact at ${r}: expected a regular file`);let i=await qe(r);er(s,i,`Release artifact escapes artifacts directory: ${r}`)}async function Wn(e,t,r,s){let n=`${JSON.stringify(t,null,2)}
167
+ `,i=Qt(Zt(e),`.${jd()}.json.tmp`),o=await ds(Zt(e));try{if(await We(Zt(e),"release directory"),r){await qd(e,"active release ledger");let c;try{c=JSON.parse(await fc(e,"utf-8"))}catch(l){throw new b(`Failed to read active release ledger at ${e} before writing: ${_(l)}`)}if(c.updatedAt!==s)throw new b("Active release ledger changed in another process")}let a=await Fd(i,"wx",384);try{await a.writeFile(n,"utf-8"),await a.sync()}finally{await a.close()}if(r)await Ud(i,e);else{try{await Bd(i,e)}catch(c){if(X(c,"EEXIST"))throw new b(`Cannot create release ledger: active ledger already exists at ${e}`);throw c}await Gd(i)}await oe(Zt(e))}catch(a){await Jn(i,a,`Failed to clean temporary ledger file at ${i}`)}finally{await Xt(o)}}async function Jn(e,t,r){try{await Vd(e,{force:!0})}catch(s){throw AggregateError([t,s],r)}throw t}async function hs(e){let t;try{t=await fc(e)}catch(r){throw new b(`Failed to read release artifact at ${e}: ${_(r)}`)}return`sha512-${hc("sha512").update(t).digest("base64")}`}async function We(e,t){let r;try{r=await tr(e)}catch(s){throw new b(`Invalid ${t} at ${e}: ${_(s)}`)}if(!r.isDirectory()||r.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a real directory`)}async function qd(e,t){let r;try{r=await tr(e)}catch(s){throw new b(`Invalid ${t} at ${e}: ${_(s)}`)}if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a regular file`)}async function nt(e){try{return await tr(e),!0}catch(t){if(X(t,"ENOENT"))return!1;throw t}}function ir(e,t){return be(e.artifactsRoot,rt(t,"id"))}function zn(e,t,r){let s=`${hc("sha256").update(r).digest("hex")}.tgz`;return be(ir(e,t),s)}function fs(e,t,r){return yc(e.releaseDirectory,zn(e,t,r)).split(Hd).join("/")}function Kn(e,t){let r=be(e.historyDirectory,`${rt(t,"id")}.json`);if(Zt(r)!==be(e.historyDirectory))throw new b(`Invalid release history path for ID ${t}`);return r}function er(e,t,r){let s=yc(e,t);if(!s||ne(s))throw new b(r)}import{isAbsolute as $c,relative as Wd,resolve as Jd}from"path";function Qn(e){if(Object.values(e.operations.npm).some((t)=>t.state!=="pending"))return!0;if(e.operations.push&&e.operations.push.state!=="pending")return!0;return Object.values(e.operations.providerReleases).some((t)=>t.state!=="pending")}function Pc(e){return e.map((t,r)=>{let s=`create.packages[${r}]`,n=t.oldVersion??t.version;if(t.oldVersion!==void 0&&t.version!==void 0&&t.oldVersion!==t.version)P(s,"oldVersion and version must match when both are provided");return Sc({file:t.file,isPrivate:t.isPrivate,name:t.name,newVersion:t.newVersion,oldVersion:n},s)})}function Rc(e){return e.map((t,r)=>{let s=typeof t==="object"&&t!==null&&"toJson"in t&&typeof t.toJson==="function"?t.toJson():t,n;try{n=JSON.parse(JSON.stringify(s))}catch(i){throw new b(`Invalid release ledger at create.stones[${r}]: ${_(i)}`)}return Cc(n,`create.stones[${r}]`)})}function or(e,t){let r=Z(e,"root");if(he(r,["schemaVersion","id","baseCommit","createdAt","updatedAt","phase","options","packages","releaseTags","tagsReady","stones","artifacts","operations"],["expectedReleaseTree","releaseCommit"],"root"),r.schemaVersion!==zt)P("schemaVersion",`unsupported schema version ${String(r.schemaVersion)}`);let s=rt(r.id,"id"),n=kt(r.baseCommit,"baseCommit"),i=ys(r.createdAt,"createdAt"),o=ys(r.updatedAt,"updatedAt");if(Date.parse(o)<Date.parse(i))P("updatedAt","must not precede createdAt");let a=kc(r.phase,Ct,"phase","release phase"),c=Kd(r.options,"options"),l=Yd(r.packages,t.repositoryRoot),d=zd(r.releaseTags,l,c),g=Je(r.tagsReady,"tagsReady");if(!c.tags&&!g)P("tagsReady","must be true when tags are disabled");let h=Xd(r.stones),f=r.expectedReleaseTree===void 0?void 0:kt(r.expectedReleaseTree,"expectedReleaseTree"),m=r.releaseCommit===void 0?void 0:kt(r.releaseCommit,"releaseCommit"),y=Qd(r.artifacts,l,t,s),R=eg(r.operations,l,c,i,o),S={artifacts:y,baseCommit:n,createdAt:i,id:s,operations:R,options:c,packages:l,phase:a,releaseTags:d,schemaVersion:zt,stones:h,tagsReady:g,updatedAt:o};if(f!==void 0)S.expectedReleaseTree=f;if(m!==void 0)S.releaseCommit=m;if(c.tags&&g&&!m)P("tagsReady","cannot be true before releaseCommit is recorded");if(a==="completed")ri(S);return S}function zd(e,t,r){if(!Array.isArray(e))P("releaseTags","must be an array");let s=e.map((i,o)=>{let a=I(i,`releaseTags[${o}]`);return Zn(`refs/tags/${a}`,`releaseTags[${o}]`),a});if(new Set(s).size!==s.length)P("releaseTags","must not contain duplicates");let n=r.tags?t.map((i)=>`${i.name}@${i.newVersion}`).sort():[];if(JSON.stringify([...s].sort())!==JSON.stringify(n))P("releaseTags","must exactly match the release package versions when tags are enabled");return s}function Kd(e,t){let r=Z(e,t);return he(r,["changelog","createRelease","dryRun","npm","npmTag","publishOnly","push","tags"],[],t),{changelog:Je(r.changelog,`${t}.changelog`),createRelease:Je(r.createRelease,`${t}.createRelease`),dryRun:si(r.dryRun),npm:Je(r.npm,`${t}.npm`),npmTag:I(r.npmTag,`${t}.npmTag`),publishOnly:Je(r.publishOnly,`${t}.publishOnly`),push:Je(r.push,`${t}.push`),tags:Je(r.tags,`${t}.tags`)}}function Yd(e,t){if(!Array.isArray(e)||e.length===0)P("packages","must be a nonempty array");let r=new Set,s=new Set;return e.map((n,i)=>{let o=`packages[${i}]`,a=Sc(n,o);if($c(a.file))P(`${o}.file`,"must be repository-relative");if(r.has(a.name))P(o,`duplicate package name ${a.name}`);let c=Jd(t,a.file),l=Wd(t,c);if(!l||ne(l))P(`${o}.file`,"must resolve inside the repository");if(s.has(c))P(o,`duplicate package file ${a.file}`);return r.add(a.name),s.add(c),a})}function Sc(e,t){let r=Z(e,t);he(r,["name","file","oldVersion","newVersion","isPrivate"],[],t);let s=I(r.file,`${t}.file`);if(s.includes("\x00"))P(`${t}.file`,"must not contain a null byte");return{file:s,isPrivate:Je(r.isPrivate,`${t}.isPrivate`),name:I(r.name,`${t}.name`),newVersion:I(r.newVersion,`${t}.newVersion`),oldVersion:I(r.oldVersion,`${t}.oldVersion`)}}function Xd(e){if(!Array.isArray(e))P("stones","must be an array");let t=new Set;return e.map((r,s)=>{let n=Cc(r,`stones[${s}]`);if(t.has(n.id))P(`stones[${s}].id`,`duplicate stone ID ${n.id}`);return t.add(n.id),n})}function Cc(e,t){let r=Z(e,t);he(r,["id","message"],["tag","description","commits","major","minor","patch","dependency","snapshot"],t);let s={id:I(r.id,`${t}.id`),message:I(r.message,`${t}.message`)};if(r.tag!==void 0)s.tag=I(r.tag,`${t}.tag`);if(r.description!==void 0)s.description=Kt(r.description,`${t}.description`);if(r.commits!==void 0)s.commits=Zd(r.commits,`${t}.commits`);for(let n of["major","minor","patch","dependency","snapshot"])if(r[n]!==void 0)s[n]=Tc(r[n],`${t}.${n}`);return s}function Zd(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,s)=>{let n=`${t}[${s}]`,i=Z(r,n);return he(i,["hash","subject","type","message","packages"],["body","scope"],n),{...{hash:I(i.hash,`${n}.hash`),message:I(i.message,`${n}.message`),packages:Tc(i.packages,`${n}.packages`),subject:I(i.subject,`${n}.subject`),type:I(i.type,`${n}.type`)},...i.body===void 0?{}:{body:Kt(i.body,`${n}.body`)},...i.scope===void 0?{}:{scope:I(i.scope,`${n}.scope`)}}})}function Qd(e,t,r,s){let n=Z(e,"artifacts"),i=new Map(t.map((a)=>[a.name,a])),o=_e();for(let[a,c]of Object.entries(n)){let l=i.get(a);if(!l)P(`artifacts.${a}`,"references an unknown package");if(l.isPrivate)P(`artifacts.${a}`,"private packages cannot have artifacts");let d=`artifacts.${a}`,g=Z(c,d);he(g,["path","integrity"],[],d);let h=I(g.path,`${d}.path`);if($c(h))P(`${d}.path`,"must be relative to the release directory");let f=fs(r,s,a);if(h!==f)P(`${d}.path`,`must be ${f}`);let m=I(g.integrity,`${d}.integrity`);if(!sc.test(m))P(`${d}.integrity`,"must be a sha512 SRI value");ve(o,a,{integrity:m,path:h})}return o}function eg(e,t,r,s,n){let i=Z(e,"operations");he(i,["npm","npmRegistries","providerReleases"],["push"],"operations");let o=new Map(t.map((y)=>[y.name,y])),a=Z(i.npm,"operations.npm"),c=_e();for(let[y,R]of Object.entries(a)){let S=o.get(y);if(!S)P(`operations.npm.${y}`,"references an unknown package");if(S.isPrivate)P(`operations.npm.${y}`,"private packages cannot have npm operations");if(!r.npm)P(`operations.npm.${y}`,"npm is disabled");let C=Yn(R,`operations.npm.${y}`);Xn(C,s,n,`operations.npm.${y}`),ve(c,y,C)}let l=r.npm?t.filter((y)=>!y.isPrivate).map((y)=>y.name):[];for(let y of l)if(!c[y])P("operations.npm",`missing public package ${y}`);let d=Z(i.npmRegistries,"operations.npmRegistries"),g=_e();for(let[y,R]of Object.entries(d)){if(!c[y])P(`operations.npmRegistries.${y}`,"references an unknown npm operation");ve(g,y,ni(R,`operations.npmRegistries.${y}`))}let h;if(i.push!==void 0){if(!r.push&&!r.tags)P("operations.push","push and tags are disabled");let y=Z(i.push,"operations.push");he(y,["destination","remote","refs","state"],["startedAt","completedAt"],"operations.push");let R=ei(y,"operations.push"),S=Yn(y,"operations.push",["destination","remote","refs"]);Xn(S,s,n,"operations.push"),h={...R,...S}}let f=Z(i.providerReleases,"operations.providerReleases"),m=_e();for(let[y,R]of Object.entries(f)){if(!o.has(y))P(`operations.providerReleases.${y}`,"references an unknown package");if(!r.createRelease)P(`operations.providerReleases.${y}`,"createRelease is disabled");let S=`operations.providerReleases.${y}`,C=Z(R,S);he(C,["tag","title","notes","state"],["startedAt","completedAt"],S);let q=ti(C,S),L=Yn(C,S,["tag","title","notes"]);Xn(L,s,n,S),ve(m,y,{...q,...L})}return{npm:c,npmRegistries:g,providerReleases:m,...h?{push:h}:{}}}function Yn(e,t,r=[]){let s=Z(e,t);he(s,["state",...r],["startedAt","completedAt"],t);let n=kc(s.state,Fn,`${t}.state`,"operation state");if(n==="pending"){if(s.startedAt!==void 0||s.completedAt!==void 0)P(t,"pending operations cannot have timestamps");return{state:n}}let i=ys(s.startedAt,`${t}.startedAt`);if(n==="started"){if(s.completedAt!==void 0)P(t,"started operations cannot have completedAt");return{startedAt:i,state:n}}let o=ys(s.completedAt,`${t}.completedAt`);if(Date.parse(o)<Date.parse(i))P(t,"completedAt must not precede startedAt");return{completedAt:o,startedAt:i,state:n}}function ei(e,t){let r=Z(e,t),s=tg(r.destination,`${t}.destination`),n=I(r.remote,`${t}.remote`);if(!nc.test(n)||n.includes("..")||n.includes("//"))P(`${t}.remote`,"must be a git remote name, not a URL or credential-bearing value");if(!Array.isArray(r.refs)||r.refs.length===0)P(`${t}.refs`,"must be a nonempty array");let i=new Set,o=new Set,a=r.refs.map((c,l)=>{let d=`${t}.refs[${l}]`,g=Z(c,d);he(g,["source","destination","oid"],[],d);let h=Zn(g.source,`${d}.source`),f=Zn(g.destination,`${d}.destination`),m=I(g.oid,`${d}.oid`);if(!tt.test(m))P(`${d}.oid`,"must be a full 40- or 64-character git object ID");if(i.has(h))P(`${d}.source`,`duplicate source ref ${h}`);if(o.has(f))P(`${d}.destination`,`duplicate destination ref ${f}`);return i.add(h),o.add(f),{destination:f,oid:m,source:h}});return{destination:s,refs:a,remote:n}}function tg(e,t){let r=Z(e,t);he(r,["canonicalUrl"],["owner","provider","repo"],t);let s=I(r.canonicalUrl,`${t}.canonicalUrl`),n;try{n=new URL(s)}catch{P(`${t}.canonicalUrl`,"must be an absolute credential-free URL")}let i=n.protocol==="ssh:"||n.protocol==="git+ssh:";if(n.password||n.username&&!i||n.search||n.hash)P(`${t}.canonicalUrl`,"must not contain credentials, query parameters, or fragments");let o=[r.provider,r.owner,r.repo];if(o.every((c)=>c===void 0))return{canonicalUrl:s};if(o.some((c)=>c===void 0))P(t,"provider, owner, and repo must be set together");let a=I(r.provider,`${t}.provider`);if(a!=="github"&&a!=="gitlab"&&a!=="bitbucket")P(`${t}.provider`,"must be github, gitlab, or bitbucket");return{canonicalUrl:s,owner:I(r.owner,`${t}.owner`),provider:a,repo:I(r.repo,`${t}.repo`)}}function ti(e,t){let r=Z(e,t);return{notes:Kt(r.notes,`${t}.notes`),tag:I(r.tag,`${t}.tag`),title:I(r.title,`${t}.title`)}}function ws(e,t,r){if(!rg(t))throw new b(`Unknown release operation state ${String(t)}`);if(e.state===t)return e;if(e.state==="pending"&&t==="started")return{startedAt:r,state:t};if(e.state==="started"&&t==="completed")return{completedAt:r,startedAt:e.startedAt,state:t};throw new b(`Invalid release operation transition from ${e.state} to ${t}`)}function ri(e){if(!e.tagsReady)throw new b(`Cannot complete release ${e.id}: local release tags are not ready`);for(let[t,r]of Object.entries(e.operations.npm)){if(r.state!=="completed")throw new b(`Cannot complete release ${e.id}: npm operation for ${t} is ${r.state}`);if(!e.artifacts[t])throw new b(`Cannot complete release ${e.id}: npm artifact for ${t} is missing`);if(!e.operations.npmRegistries[t])throw new b(`Cannot complete release ${e.id}: npm registry for ${t} is missing`)}if((e.options.push||e.options.publishOnly&&e.options.tags)&&!e.operations.push)throw new b(`Cannot complete release ${e.id}: push operation is not configured`);if(e.operations.push&&e.operations.push.state!=="completed")throw new b(`Cannot complete release ${e.id}: push operation is ${e.operations.push.state}`);if(e.options.createRelease)for(let t of e.packages){let r=e.operations.providerReleases[t.name];if(!r)throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is not configured`);if(r.state!=="completed")throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is ${r.state}`)}}function si(e){if(e!==!1)P("options.dryRun","durable ledgers require dryRun to be false");return!1}function ni(e,t){let r=I(e,t),s;try{s=new URL(r)}catch{P(t,"must be an absolute HTTP or HTTPS URL")}if(s.protocol!=="http:"&&s.protocol!=="https:"||s.username||s.password||s.search||s.hash)P(t,"must be a credential-free HTTP or HTTPS URL");return s.href}function Xn(e,t,r,s){if(e.state==="pending")return;let n=Date.parse(e.startedAt);if(n<Date.parse(t)||n>Date.parse(r))P(`${s}.startedAt`,"must be between createdAt and updatedAt");if(e.state==="completed"){let i=Date.parse(e.completedAt);if(i<n||i>Date.parse(r))P(`${s}.completedAt`,"must be between startedAt and updatedAt")}}function Zn(e,t){let r=I(e,t);if(!r.startsWith("refs/")||r.includes("..")||r.includes("//")||/[\s~^:?*[\\]/.test(r))P(t,"must be an exact full git ref");return r}function kc(e,t,r,s){if(typeof e!=="string"||!t.includes(e))P(r,`unknown ${s} ${String(e)}`);return e}function xc(e){return Ct.includes(e)}function rg(e){return Fn.includes(e)}function Z(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))P(t,"must be an object");return e}function he(e,t,r,s){let n=new Set([...t,...r]);for(let i of t)if(!Object.hasOwn(e,i))P(s,`missing required key ${i}`);for(let i of Object.keys(e))if(!n.has(i))P(s,`unknown key ${i}`)}function Je(e,t){if(typeof e!=="boolean")P(t,"must be a boolean");return e}function ys(e,t){let r=I(e,t);if(!as(r))P(t,"must be a canonical ISO timestamp");return r}function kt(e,t){let r=I(e,t);if(!tt.test(r))P(t,"must be a full 40- or 64-character git object ID");return r}function Tc(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,s)=>I(r,`${t}[${s}]`))}function ii(e){return new Date(Math.max(Date.now(),Date.parse(e)+1)).toISOString()}function _e(){return Object.create(null)}function ve(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}class $e{value;paths;releaseDirectory;artifactsDirectory;activePath;active=!0;constructor(e,t){this.value=e;this.paths=t;this.releaseDirectory=t.releaseDirectory,this.artifactsDirectory=ir(t,e.id),this.activePath=t.activePath}static async create(e,t=process.cwd()){let r=await qn(t);if(await nt(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);if(await nt(r.removingPath))throw new b(`Cannot create release ledger: an interrupted removal left ${r.removingPath}; delete it and its artifacts directory to finish cleanup`);let s=new Date().toISOString(),n=await Bun.$`git rev-parse HEAD`.cwd(r.repositoryRoot).quiet().nothrow(),i=n.stdout.toString().trim();if(n.exitCode!==0||!tt.test(i))throw new b("Cannot create release ledger: failed to resolve the current commit");let o=e.options.publishOnly?await wc(r.repositoryRoot,i):void 0,a=Pc(e.packages),c=Rc(e.stones),l=rt(e.id??sg("sha256").update(JSON.stringify({baseCommit:i,options:e.options,packages:a,stones:c})).digest("hex"),"create.id"),d=_e(),g=e.options.tags?a.map((y)=>`${y.name}@${y.newVersion}`).sort():[];if(e.options.npm){for(let y of a)if(!y.isPrivate)ve(d,y.name,{state:"pending"})}let h={artifacts:_e(),baseCommit:i,createdAt:s,id:l,operations:{npm:d,npmRegistries:_e(),providerReleases:_e()},options:{changelog:e.options.changelog,createRelease:e.options.createRelease,dryRun:si(e.options.dryRun),npm:e.options.npm,npmTag:I(e.options.npmTag,"create.options.npmTag"),publishOnly:e.options.publishOnly,push:e.options.push,tags:e.options.tags},packages:a,phase:"planned",releaseTags:g,schemaVersion:zt,stones:c,tagsReady:!e.options.tags,updatedAt:s};if(o)h.expectedReleaseTree=o;let f=or(h,r);if(await sr(f,r),await rr(r,l),await nt(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);let m=Kn(r,l);if(await nt(m))throw new b(`Release ${l} is already completed at ${m}`);return await Wn(r.activePath,f,!1),new $e(f,r)}static async loadActive(e=process.cwd()){let t=await qn(e),r;try{r=await cg(t.activePath)}catch(o){if(X(o,"ENOENT")){if(await nt(t.removingPath))throw new b(`Release cleanup is incomplete: an interrupted removal left ${t.removingPath}; delete it and its artifacts directory to finish cleanup`);return null}throw new b(`Failed to inspect active release ledger at ${t.activePath}: ${_(o)}`)}if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid active release ledger at ${t.activePath}: expected a regular file`);let s;try{s=await Ec(t.activePath,"utf-8")}catch(o){if(X(o,"ENOENT"))return null;throw new b(`Failed to read active release ledger at ${t.activePath}: ${_(o)}`)}let n;try{n=JSON.parse(s)}catch(o){throw new b(`Failed to parse active release ledger at ${t.activePath}: ${_(o)}`)}let i=or(n,t);return await sr(i,t),await rr(t,i.id),await ms(i,t),new $e(i,t)}get data(){return structuredClone(this.value)}get id(){return this.value.id}get phase(){return this.value.phase}async setPhase(e){if(this.assertActive("set phase"),e==="completed")throw new b("Cannot set release phase to completed: use complete() instead");if(!xc(e))throw new b(`Cannot set release phase: unknown phase ${String(e)}`);if(e===this.value.phase)return;let t=Ct.indexOf(this.value.phase);if(Ct.indexOf(e)<t)throw new b(`Cannot move release phase backwards from ${this.value.phase} to ${e}`);let s=structuredClone(this.value);s.phase=e,await this.persist(s)}async setReleaseCommit(e){this.assertActive("set release commit");let t=kt(e,"releaseCommit");if(!this.value.expectedReleaseTree)throw new b("Cannot set release commit before the expected release tree");if(this.value.releaseCommit===t)return;if(this.value.releaseCommit)throw new b(`Cannot replace release commit ${this.value.releaseCommit} with ${t} in release ${this.value.id}`);let r=structuredClone(this.value);r.releaseCommit=t,await this.persist(r)}async setExpectedReleaseTree(e){this.assertActive("set expected release tree");let t=kt(e,"expectedReleaseTree");if(this.value.expectedReleaseTree===t)return;if(this.value.expectedReleaseTree)throw new b(`Cannot replace expected release tree ${this.value.expectedReleaseTree} with ${t} in release ${this.value.id}`);if(this.value.releaseCommit)throw new b(`Cannot set expected release tree after release commit ${this.value.releaseCommit}`);let r=structuredClone(this.value);r.expectedReleaseTree=t,await this.persist(r)}async markTagsReady(){if(this.assertActive("mark release tags ready"),!this.value.options.tags)return;if(!this.value.releaseCommit)throw new b("Cannot mark release tags ready without a release commit");if(this.value.tagsReady)return;let e=structuredClone(this.value);e.tagsReady=!0,await this.persist(e)}async setArtifact(e,t){if(this.assertActive("set artifact"),this.getPackage(e).isPrivate)throw new b(`Cannot store an artifact for private package ${e}`);let s=this.value.operations.npm[e];if(!s)throw new b(`Cannot store an artifact for unconfigured npm package ${e}`);if(s.state!=="pending")throw new b(`Cannot replace artifact for ${e} after its npm operation has started`);if(pg(t)!==".tgz")throw new b(`Cannot store artifact for ${e}: source must be a .tgz file`);let n;try{n=await lg(t)}catch(d){throw new b(`Cannot read source artifact for ${e} at ${t}: ${_(d)}`)}if(!n.isFile())throw new b(`Cannot store artifact for ${e}: source is not a regular file`);await rr(this.paths,this.value.id);let i=zn(this.paths,this.value.id,e),o=dg(this.artifactsDirectory,`.${ng()}.tgz.tmp`),a;try{await og(t,o,ig.COPYFILE_EXCL),await oe(o),await nr(this.paths,this.value.id,o),a=await hs(o);try{await ag(o,i)}catch(d){if(!X(d,"EEXIST"))throw d;if(await nr(this.paths,this.value.id,i),await hs(i)!==a){let g=this.value.artifacts[e]?`A different durable artifact already exists for ${e} at ${i}`:`A different durable artifact already exists for ${e} at ${i}; the ledger records no artifact for it, so it is likely left by an interrupted run - delete the file and retry`;throw new b(g)}}await Ac(o,{force:!0}),await oe(this.artifactsDirectory),await nr(this.paths,this.value.id,i)}catch(d){await Jn(o,d,`Failed to clean temporary artifact for ${e}`)}if(!a)throw new b(`Failed to calculate artifact integrity for ${e}`);let c={integrity:a,path:fs(this.paths,this.value.id,e)},l=structuredClone(this.value);return ve(l.artifacts,e,c),await this.persist(l),{...c}}resolveArtifactPath(e){let t=this.value.artifacts[e];if(!t)throw new b(`Release artifact is not configured for ${e}`);return gg(this.releaseDirectory,t.path)}async configurePush(e,t,r){if(this.assertActive("configure push"),!this.value.options.push&&!this.value.options.tags)throw new b("Cannot configure push: neither push nor tags are enabled for this release");let s=ei({destination:t,refs:r,remote:e},"configurePush"),n=this.value.operations.push;if(n){if(JSON.stringify([n.remote,n.destination,n.refs])===JSON.stringify([s.remote,s.destination,s.refs]))return;throw new b("Cannot replace an existing push configuration")}let i=structuredClone(this.value);i.operations.push={...s,state:"pending"},await this.persist(i)}async configureProviderRelease(e,t){if(this.assertActive("configure provider release"),this.getPackage(e),!this.value.options.createRelease)throw new b("Cannot configure a provider release when createRelease is disabled");let r=ti(t,`providerReleases.${e}`),s=this.value.operations.providerReleases[e];if(s){if(s.tag===r.tag&&s.title===r.title&&s.notes===r.notes)return;throw new b(`Cannot replace provider release configuration for ${e}`)}let n=structuredClone(this.value);ve(n.operations.providerReleases,e,{...r,state:"pending"}),await this.persist(n)}async markNpm(e,t){this.assertActive("mark npm operation");let r=this.value.operations.npm[e];if(!r)throw new b(`Npm operation is not configured for package ${e}`);if(r.state===t)return;if(t==="started"&&!this.value.artifacts[e])throw new b(`Cannot start npm operation for ${e} without a durable artifact`);let s=structuredClone(this.value);ve(s.operations.npm,e,ws(r,t,this.operationTimestamp())),await this.persist(s)}async setNpmRegistry(e,t){this.assertActive("set npm registry");let r=this.value.operations.npm[e];if(!r)throw new b(`Npm operation is not configured for package ${e}`);if(r.state!=="pending")throw new b(`Cannot change npm registry for ${e} after publication has started`);let s=ni(t,`operations.npmRegistries.${e}`),n=this.value.operations.npmRegistries[e];if(n===s)return;if(n)throw new b(`Cannot replace npm registry for ${e}`);let i=structuredClone(this.value);ve(i.operations.npmRegistries,e,s),await this.persist(i)}async markPush(e){this.assertActive("mark push operation");let t=this.value.operations.push;if(!t)throw new b("Push operation is not configured");if(t.state===e)return;let r=structuredClone(this.value);r.operations.push={destination:t.destination,refs:t.refs,remote:t.remote,...ws(t,e,this.operationTimestamp())},await this.persist(r)}async markProviderRelease(e,t){this.assertActive("mark provider release operation");let r=this.value.operations.providerReleases[e];if(!r)throw new b(`Provider release is not configured for package ${e}`);if(r.state===t)return;let s=structuredClone(this.value);ve(s.operations.providerReleases,e,{notes:r.notes,tag:r.tag,title:r.title,...ws(r,t,this.operationTimestamp())}),await this.persist(s)}hasExternalProgress(){return Qn(this.value)}async complete(){this.assertActive("complete");let e=structuredClone(this.value);if(e.phase!=="completed")ri(e),e.phase="completed",await this.persist(e),e=this.value;await vc(this.paths);let t=Kn(this.paths,e.id);if(await nt(t))throw new b(`Cannot complete release ${e.id}: history ledger already exists at ${t}`);try{await Ic(this.activePath,t),await oe(this.paths.historyDirectory),await oe(this.releaseDirectory)}catch(r){throw new b(`Failed to move completed release ${e.id} to history: ${_(r)}`)}return this.active=!1,t}async remove(){this.assertActive("remove");let e=await ds(this.releaseDirectory);try{await rr(this.paths,this.value.id);let t=or(JSON.parse(await Ec(this.activePath,"utf-8")),this.paths);if(await sr(t,this.paths),await ms(t,this.paths),t.id!==this.value.id||t.updatedAt!==this.value.updatedAt)throw new b("Active release ledger changed in another process");if(Qn(t))throw new b(`Cannot remove release ${t.id}: an external operation has started`);await Ic(this.activePath,this.paths.removingPath),await oe(this.releaseDirectory),await Ac(this.artifactsDirectory,{force:!0,recursive:!0}),await ug(this.paths.removingPath),await oe(this.releaseDirectory)}catch(t){if(t instanceof b)throw t;throw new b(`Failed to remove release ${this.value.id}: ${_(t)}`)}finally{await Xt(e)}this.active=!1}async persist(e){e.updatedAt=ii(this.value.updatedAt);let t=or(e,this.paths);await sr(t,this.paths),await ms(t,this.paths),await Wn(this.activePath,t,!0,this.value.updatedAt),this.value=t}getPackage(e){let t=this.value.packages.find((r)=>r.name===e);if(!t)throw new b(`Unknown release package ${e}`);return t}operationTimestamp(){return ii(this.value.updatedAt)}assertActive(e){if(!this.active)throw new b(`Cannot ${e}: release ledger ${this.value.id} is no longer active`)}}class Me{config;packageUpdater=new Gt;changelogGenerator;remoteParser=new Bt;stoneManager;provider=null;commitUrlFn=null;options;createdTags=[];createdTagTargets=new Map;commitCreated=!1;createdCommit=null;irreversibleOperation=null;ownedPaths=null;repositoryRoot=null;rollbackBlockedReason=null;ignoredBuildInputsValidated=!1;buildConfig=null;buildOutputsPrepared=!1;preparedNpmPublish=null;ledger=null;publishContext=null;constructor(e,t){this.config=e;this.options=t,this.changelogGenerator=new Qe(this.config.get("changelog")),this.stoneManager=new E(this.config)}static async assertNoActiveRelease(){let e=await $e.loadActive();if(!e)return;throw new u(`Release ${e.id} is incomplete`,"Run sis roll --resume before starting another release")}static async resume(e){let t=await $e.loadActive();if(!t)throw new u("No incomplete release found","Run sis roll to start a release");let r=t.data,s=new Me(e,r.options);s.ledger=t;let n=r.packages.map((o)=>new z({file:o.file,isPrivate:o.isPrivate,name:o.name,newVersion:o.newVersion,version:o.oldVersion})),i=r.stones.map((o)=>A.fromJson(o));if(s.createdTags=[...r.releaseTags],r.phase==="completed")return await t.complete(),{ledger:s.getLedgerSnapshot(),packages:n,stones:i};try{if(await s.recoverReleaseCommit(r),await qa(t.data),await s.ensureLedgerPlan(n,i),r.options.npm){if(n.some((a)=>t.data.operations.npm[a.name]&&!t.data.artifacts[a.name]))await qt(await s.getRepositoryRoot());await s.prepareNpmPublish(n)}if(t.phase==="planned")await t.setPhase("local-ready");return await s.resumeExternalOperations(n,i),{ledger:s.getLedgerSnapshot(),packages:n,stones:i}}catch(o){if(o instanceof u||!s.hasCrossedIrreversibleBoundary())throw o;throw s.createIncompleteReleaseError(o)}}async initializeExternalRelease(e,t,r){if(this.options.dryRun||!this.needsReleaseLedger(r))return;this.ledger=await $e.create({options:{...this.options,npmTag:this.options.npm?Jt(e,this.config.get("tag")):de,publishOnly:r},packages:e.map((s)=>({file:s.file,isPrivate:s.isPrivate,name:s.name,newVersion:s.newVersion,version:s.version})),stones:t})}async finalizeExternalRelease(e,t){if(!this.ledger)return;if(this.options.npm||this.ledger.data.options.publishOnly)await qt(await this.getRepositoryRoot());let r=await ie();await this.ensureExpectedReleaseTree(this.ledger.data,r),await Rt(this.ledger.data,r),await this.ledger.setReleaseCommit(r),await this.ensureLedgerPlan(e,t)}async markExternalReleaseReady(){if(this.ledger)await this.ledger.setPhase("local-ready")}async completeRelease(){if(this.ledger)await this.ledger.complete()}async getProvider(){if(!this.provider){let e=this.ledger?.data.operations.push?.destination,t=ss(e);this.provider=await ht(t)}return this.provider}async initCommitLinks(){if(this.commitUrlFn!==null)return;let e=this.ledger?.data.operations.push?.destination,t=ss(e);if(t){this.commitUrlFn=sn(t);return}let r=await this.remoteParser.getRemoteInfo();this.commitUrlFn=r?.commitUrl??null}async preflight(e,t){if(this.options.dryRun)return;await Me.assertNoActiveRelease();let r=await this.getOwnedPaths(e,t);await Ua(r,await this.getRepositoryRoot());let s=r.map((i)=>Ge(i));if((await O(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${s}`.quiet(),"Failed to inspect release files")).stdout.length===0)return;throw new u("Release files have uncommitted changes",`Commit or stash these files:
173
168
  ${r.join(`
174
- `)}`)}async updatePackageVersions(e){if(this.options.dryRun)return;await this.packageUpdater.updateAll(e)}async generateChangelogs(e,t){if(this.options.dryRun)return;await this.changelogGenerator.generate(e,t)}async createCommit(e,t,r){if(this.options.dryRun)return;let n=await this.getOwnedPaths(t,r),i=n.map((f)=>Fe(f)),s=oa(this.config.get("commit").message,e,t),a=ca(this.config.get("commit")),o=this.ledger?.data.baseCommit??await oe(),c=await jn(),p,m;try{if(await x(()=>Bun.$`git add -A -- ${i}`.quiet(),"Failed to stage release files"),await oe()!==o)throw new g("Release base commit changed before commit creation","Restart the release from the intended branch");p=await Ea(o,n,await this.getRepositoryRoot()),await this.ledger?.setExpectedReleaseTree(p),m=await Nn(n),await x(()=>Bun.$`git commit --only ${a} -m ${s} -- ${i}`.env(la(this.config.get("commit"))).quiet(),"Failed to create commit"),this.commitCreated=!0}catch(f){if(m){let b;try{b=await Nn(n)}catch(d){throw this.rollbackBlockedReason="release files could not be verified after commit failure",AggregateError([f,d],"Commit failed and release files could not be verified")}if(b!==m)throw this.rollbackBlockedReason="release-owned files changed while commit hooks ran",AggregateError([f],"Commit failed after a hook changed release-owned files")}try{await Tn(n)}catch(b){throw AggregateError([f,b],"Commit and index cleanup failed")}throw f}let u=await oe();if(this.createdCommit={baseCommit:o,oid:u,ref:c},!p)throw Error("Expected release tree was not recorded before commit");if(this.ledger){await gt(this.ledger.data,u);return}await Bn(u,o),await Un(u,p)}async createGitTags(e){if(this.options.dryRun)return;let t=await oe();for(let r of e){let n=`${r.name}@${r.newVersion??r.version}`;await x(()=>Bun.$`git -c tag.gpgSign=false tag -- ${n}`.quiet(),`Failed to create tag ${n}`),this.createdTags.push(n),this.createdTagTargets.set(n,t)}}async prepareNpmPublish(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key===t)return;let r=this.requireLedger("prepare npm artifacts");this.preparedNpmPublish=null;let n=await Wa(e);if(n.length===0){this.preparedNpmPublish={key:t,packages:[]};return}let i=await Og(Pi(Dg(),"sisyphus-publish-")),s=[];try{for(let[a,o]of n.entries()){if(!r.data.artifacts[o.name]){let c=Pi(i,`${String(a).padStart(4,"0")}.tgz`);await x(()=>this.prepareNpmArtifact(o,c),`Failed to prepare ${o.name}`),await r.setArtifact(o.name,c)}s.push({artifactPath:r.resolveArtifactPath(o.name),pkg:o})}}finally{await Co(i,{force:!0,recursive:!0})}this.preparedNpmPublish={key:t,packages:s}}async publishToNpm(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key!==t)await this.prepareNpmPublish(e);let r=this.preparedNpmPublish?.packages??[];if(r.length===0)return;try{for(let n of r)await this.publishPreparedPackage(n)}finally{this.preparedNpmPublish=null}}async pushRelease(){if(this.options.dryRun)return;await this.pushConfiguredRefs()}async createGitRelease(e,t){if(this.options.dryRun)return;if(t.length===0)return;await this.initCommitLinks();let r=await this.getProvider(),n=this.ledger?.data.operations.push;if(n){let i=n.refs.filter((s)=>s.destination.startsWith("refs/tags/"));if(i.length>0)await Ja(n,()=>this.getRepositoryRoot(),i)}for(let i of t){let s=Wn(e,i,this.commitUrlFn);await this.createProviderRelease(r,i.name,s)}}hasCrossedIrreversibleBoundary(){return this.irreversibleOperation!==null||this.ledger?.hasExternalProgress()===!0}createIncompleteReleaseError(e){let t=this.irreversibleOperation??"an external release operation",r=new g(`Release incomplete after ${t} began`,"Local state preserved; run sis roll --resume to reconcile and continue.");return r.cause=e,r}async rollback(e=!0){if(this.hasCrossedIrreversibleBoundary())return!1;if(await this.validateRollbackState(),this.preparedNpmPublish=null,await Ca(this.createdCommit,this.createdTags,this.createdTagTargets,()=>this.getRepositoryRoot()),this.commitCreated){if(this.ownedPaths)await Tn(this.ownedPaths);this.commitCreated=!1,this.createdCommit=null}if(this.createdTags=[],this.createdTagTargets.clear(),await this.changelogGenerator.rollback(),await this.packageUpdater.rollback(),e)await this.removeReleaseLedger();return!0}async validateRollbackState(){if(this.rollbackBlockedReason)throw new g(`Cannot roll back release because ${this.rollbackBlockedReason}`,"Local release state and the recovery ledger were preserved");if(this.commitCreated&&!this.createdCommit)throw new g("Cannot identify the release commit for rollback","Local release state and the recovery ledger were preserved");if(this.commitCreated&&this.createdCommit){let[e,t]=await Promise.all([oe(),jn()]);if(e!==this.createdCommit.oid||t!==this.createdCommit.ref)throw new g(`Cannot roll back release commit because HEAD changed from ${this.createdCommit.oid}`,"Local release state and the recovery ledger were preserved")}if(this.commitCreated&&this.ownedPaths){let e=this.ownedPaths.map((r)=>Fe(r));if((await x(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${e}`.quiet(),"Failed to inspect release files before rollback")).stdout.length>0)throw new g("Cannot roll back release because release-owned files changed after commit creation","Local release state and the recovery ledger were preserved")}for(let e of this.createdTags){let t=this.createdTagTargets.get(e),r=await Ra(`refs/tags/${e}`);if(!t||r!==t)throw new g(`Cannot roll back release because tag ${e} changed after creation`,"Local release state and the recovery ledger were preserved")}}async removeReleaseLedger(){if(!this.ledger)return;await this.ledger.remove(),this.ledger=null}needsReleaseLedger(e){return this.options.npm||this.options.push||this.options.createRelease||e&&this.options.tags}async recoverReleaseCommit(e){if(e.releaseCommit||!this.ledger)return;let t=await oe();if(!e.expectedReleaseTree&&!e.options.publishOnly)throw new g(`Release ${e.id} stopped before its expected release tree was recorded`,`No external operation was attempted; inspect the local changes and release ledger manually; delete ${this.ledger.activePath} to abort the release`);if(!e.options.publishOnly&&t===e.baseCommit)throw new g(`Release ${e.id} stopped before its release commit was created`,`No external operation was attempted; restore the release-owned files from ${e.baseCommit} and delete ${this.ledger.activePath} to abort the release`);await this.ensureExpectedReleaseTree(e,t),await gt(this.ledger.data,t),await this.ledger.setReleaseCommit(t)}async ensureLedgerPlan(e,t){if(!this.ledger)return;let r=this.ledger.data;if(await this.reconcileReleaseTags(r),r.options.npm)for(let n of e){if(!r.operations.npm[n.name]||r.operations.npmRegistries[n.name])continue;await this.ledger.setNpmRegistry(n.name,await Ha(n))}if(!r.operations.push&&(r.options.push||r.options.publishOnly&&r.options.tags))await this.configureLedgerPush(r);if(r.options.createRelease){await this.initCommitLinks();for(let n of e)await this.ledger.configureProviderRelease(n.name,Wn(t,n,this.commitUrlFn));await this.getProvider()}}async reconcileReleaseTags(e){if(!this.ledger||!e.options.tags)return;if(!e.releaseCommit)throw Error("Cannot reconcile release tags without a release commit");for(let t of e.releaseTags){let r=`refs/tags/${t}`,n=await Bun.$`git rev-parse --verify ${r}`.quiet().nothrow();if(n.exitCode!==0){await x(()=>Bun.$`git -c tag.gpgSign=false tag -- ${t} ${e.releaseCommit}`.quiet(),`Failed to create tag ${t}`);continue}let i=n.stdout.toString().trim();if(i!==e.releaseCommit)throw new g(`Release tag ${t} points to ${i}, expected ${e.releaseCommit}`,"Do not move release tags before the release completes")}if(!e.tagsReady)await this.ledger.markTagsReady()}async configureLedgerPush(e){if(!this.ledger||!e.releaseCommit)throw Error("Cannot configure release push without a recorded release commit");let t=e.releaseCommit,r=e.releaseTags.map((c)=>({destination:`refs/tags/${c}`,oid:t,source:`refs/tags/${c}`}));if(e.options.publishOnly){let c=await Xn(await Zn()),p=await Er(await Lr(c),()=>this.getRepositoryRoot());this.validateProviderDestination(p),await zn(r),await this.ledger.configurePush(c,p,r);return}let{branch:n,remote:i}=await za(),s=await Er(await Lr(i),()=>this.getRepositoryRoot());this.validateProviderDestination(s);let a=`refs/heads/${n}`,o=[{destination:a,oid:e.releaseCommit,source:a},...r];await zn(o),await this.ledger.configurePush(i,s,o)}validateProviderDestination(e){if(this.options.createRelease&&!Ir(e))throw new g("Push destination is not a supported git provider repository","Provider releases require GitHub, GitLab, or Bitbucket")}async resumeExternalOperations(e,t){let r=this.requireLedger("resume external operations");if(r.phase==="completed"){await this.completeRelease();return}if(r.data.operations.push)await this.pushConfiguredRefs();if(this.options.npm)await this.publishToNpm(e);if(this.options.createRelease)await this.createGitRelease(t,e);await this.completeRelease()}async pushConfiguredRefs(){let e=this.requireLedger("push release refs"),t=e.data.operations.push;if(!t)throw Error("Release push is not configured");if(t.state==="completed")return;if(await Ar(t,()=>this.getRepositoryRoot()),t.state==="started"){await this.reconcileStartedPush(t);return}await e.setPhase("external"),await e.markPush("started"),this.crossIrreversibleBoundary("remote push"),await Kn(t,()=>this.getRepositoryRoot()),await e.markPush("completed")}async reconcileStartedPush(e){let t=this.requireLedger("reconcile the release push"),r=await Yn(e,e.refs,()=>this.getRepositoryRoot()),n=e.refs.find((a)=>r.get(a.destination)!==a.oid);if(!n){await t.markPush("completed");return}let i=e.refs.filter((a)=>a.destination.startsWith("refs/tags/"));if(!(i.length>0&&i.every((a)=>!r.has(a.destination))))throw new g(`Cannot safely resume remote push: ${n.destination} is not at ${n.oid}`,"The previous push may not have completed; inspect the remote refs manually");await Kn(e,()=>this.getRepositoryRoot()),await t.markPush("completed")}async publishPreparedPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.operations.npm[e.pkg.name];if(!r)throw Error(`Npm operation is not configured for ${e.pkg.name}`);if(r.state==="completed")return;if(r.state==="started"){await this.reconcileStartedNpmPublish(e);return}await t.setPhase("external"),await t.markNpm(e.pkg.name,"started"),this.crossIrreversibleBoundary("npm publication"),await this.publishPackage(e),await t.markNpm(e.pkg.name,"completed")}async reconcileStartedNpmPublish(e){let t=this.requireLedger(`reconcile the npm publication for ${e.pkg.name}`),r=t.data.artifacts[e.pkg.name];if(!r)throw Error(`Release artifact is missing for ${e.pkg.name}`);let n=t.data.operations.npmRegistries[e.pkg.name];if(!n)throw Error(`Npm registry is not configured for ${e.pkg.name}`);let i=e.pkg.newVersion??e.pkg.version,s=`${e.pkg.name}@${i}`,a=Vn(e.pkg.name,n),o=await Bun.$`npm view ${s} --json --registry ${n} ${a}`.cwd(bi(e.pkg.file)).quiet().nothrow();if(o.exitCode!==0)throw new g(`Cannot safely resume npm publication for ${s}`,`The registry at ${n} does not confirm ${s}; if the version is truly absent, publish the durable artifact at ${t.resolveArtifactPath(e.pkg.name)} manually and re-run sis roll --resume`);let c;try{c=JSON.parse(o.stdout.toString())}catch{throw new g(`Cannot safely resume npm publication for ${s}`,"Registry metadata is not valid JSON")}let p=_a(c);if(!p)throw new g(`Cannot safely resume npm publication for ${s}`,"Registry metadata does not report name, version, and dist.integrity; verify the upload manually");if(p.name!==e.pkg.name||p.version!==i||p.integrity!==r.integrity)throw new g(`Cannot safely resume npm publication for ${s}: artifact integrity does not match`,"Do not republish this version; compare the registry artifact with the durable release artifact");await t.markNpm(e.pkg.name,"completed")}requireLedger(e){if(!this.ledger)throw Error(`Cannot ${e} without an active release ledger`);return this.ledger}async createProviderRelease(e,t,r){let n=this.requireLedger(`create the provider release for ${r.tag}`),i=n.data.operations.providerReleases[t];if(!i)throw Error(`Provider release is not configured for ${t}`);if(i.state==="completed")return;if(i.state==="started"){await this.reconcileStartedProviderRelease(e,t,i);return}await n.setPhase("external"),await n.markProviderRelease(t,"started"),this.crossIrreversibleBoundary(`git provider release creation for ${r.tag}`),await x(()=>e.createRelease(r),`Failed to create release for ${r.tag}`),await n.markProviderRelease(t,"completed")}async reconcileStartedProviderRelease(e,t,r){let n=await x(()=>e.getRelease(r.tag),`Failed to inspect release for ${r.tag}`);if(!n)throw new g(`Cannot safely resume provider release ${r.tag}`,"The provider does not confirm the previous creation; inspect the release manually");if(n.draft||n.tag!==r.tag||n.title!==r.title||n.notes!==r.notes)throw new g(`Cannot safely resume provider release ${r.tag}: existing release does not match`,"Do not overwrite the existing release; compare its title and notes with the release ledger");await this.ledger?.markProviderRelease(t,"completed")}async getOwnedPaths(e,t){let r=await this.getRepositoryRoot(),n=this.options.changelog?pa(this.config.get("changelog"),e):[],i=[...e.map((a)=>a.file),...n,Pi(De,rt),...this.stoneManager.getFilePaths(t)],s=[...new Set(i.map((a)=>ka(r,a)))].sort();if(this.ownedPaths&&(this.ownedPaths.length!==s.length||this.ownedPaths.some((a,o)=>a!==s[o])))throw Error("Release paths changed");return this.ownedPaths=s,s}async getRepositoryRoot(){if(this.repositoryRoot)return this.repositoryRoot;let t=(await x(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root")).stdout.toString().trim();if(!t)throw Error("Git repository root is empty");return this.repositoryRoot=Fg(t),this.repositoryRoot}async validatePublishCommitBinding(e){let t=this.requireLedger("bind npm artifacts to a release commit").data;if(!t.releaseCommit||!t.expectedReleaseTree||e!==t.releaseCommit)throw new g(`Publish source does not match the recorded release commit for ${t.id}`,t.releaseCommit?`Check out ${t.releaseCommit} before publishing`:"Resume the release before publishing");await gt(t,e)}async ensureExpectedReleaseTree(e,t){if(e.expectedReleaseTree)return;if(!this.ledger||!e.options.publishOnly||t!==e.baseCommit)throw new g(`Release ${e.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");await this.ledger.setExpectedReleaseTree(await Gn(e.baseCommit))}getPackageSetKey(e){return e.map((t)=>`${t.name}\x00${t.file}`).join("\x00")}async publishPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.options.npmTag,n=t.data.operations.npmRegistries[e.pkg.name];if(!n)throw Error(`Npm registry is not configured for ${e.pkg.name}`);let i=Vn(e.pkg.name,n);await x(()=>Bun.$`npm publish ${e.artifactPath} --tag ${r} --access public --ignore-scripts --registry ${n} ${i}`.cwd(bi(e.pkg.file)).quiet(),`Failed to publish ${e.pkg.name}`)}async prepareNpmArtifact(e,t){let r=bi(e.file),n=null;try{let i=await oe();await this.validatePublishCommitBinding(i),await kr(await this.getRepositoryRoot()),await this.validateIgnoredBuildInputs(),await Da(e,r,await this.getRepositoryRoot()),await x(()=>Bun.$`bun run build`.cwd(r).quiet(),`Failed to build ${e.name}`);let s=await oe();await this.validatePublishCommitBinding(s);let a=await $r(await this.getRepositoryRoot());if(s!==i||a.length>0)throw new g(`Package build changed repository source files for ${e.name}`,"This package was not packed and nothing was published; restore the build changes before retrying");let o=await Mg(e.file,"utf-8"),{catalogs:c,workspaceVersions:p}=await this.getPublishContext(),m=aa(o,c,p),u=JSON.parse(m),f=e.newVersion??e.version;if(u.name!==e.name||u.version!==f)throw Error(`Packed manifest identity mismatch for ${e.name}: expected ${e.name}@${f}, found ${String(u.name)}@${String(u.version)}`);n=await Ma(e,r,m);let b=await xa(n,t);if(b.name!==e.name||b.version!==f)throw new g(`Packed artifact identity mismatch for ${e.name}: found ${b.name}@${b.version}`,"This package was not recorded and nothing was published");if(!Ta(m,await Na(t)))throw new g(`Packed manifest does not match the prepared manifest for ${e.name}`,"This package was not recorded and nothing was published");let d=await oe();await this.validatePublishCommitBinding(d);let P=await $r(await this.getRepositoryRoot());if(d!==i||P.length>0)throw new g(`Package packing changed repository source files for ${e.name}`,"This package was not recorded and nothing was published; restore the changes before retrying")}finally{if(n)await Co(n,{force:!0,recursive:!0})}}async validateIgnoredBuildInputs(){if(this.ignoredBuildInputsValidated)return;await _n(await this.getRepositoryRoot(),""),this.ignoredBuildInputsValidated=!0}async getPublishContext(){if(!this.publishContext){let e=await Bun.file("package.json").json(),{packages:t}=await O.scan({single:this.config.get("single")});this.publishContext={catalogs:ia(e),workspaceVersions:sa(t.values())}}return this.publishContext}crossIrreversibleBoundary(e){this.irreversibleOperation??=e}}var _r="sisyphus/release",vi="sisyphus-release",jg="Sisyphus release PR",Ng="6f42c1",So="chore(release):",Tg=B({dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"}});class Ri extends j{name="release-pr";description="Create or update a release PR from pending stones";args=Tg;provider=null;async getProvider(){if(!this.provider)this.provider=await it();return this.provider}async execute(e){let t=await this.checkoutReleaseBranch();try{let{stones:r,packages:n}=await this.collectReleaseData(e);if(r.length===0){y.info(l.dim("No pending stones found, skipping release PR"));return}let i=this.buildPrTitle(n),s=this.buildPrBody(n,r);if(y.info(`${l.bold("Release PR:")} ${i}`),y.info(`${l.dim("Packages:")} ${n.map((a)=>a.name).join(", ")}`),e.args.dryRun){y.info(l.yellow(`
175
- [dry-run] Would create/update release PR`)),y.info(l.dim(`
176
- PR Body preview:`)),y.info(s);return}await this.commitAndPushChanges(e,r,n),await this.createOrUpdatePr(i,s)}finally{await this.restoreMainBranch(t)}}async checkoutReleaseBranch(){let t=await(await this.getProvider()).getDefaultBranch();return await Bun.$`git fetch origin ${t}`,await this.stashChanges(),await Bun.$`git checkout -B ${_r} origin/${t}`,t}async collectReleaseData(e){let t=new I(e.config),r=await this.generateStonesFromCommits(e,t,e.args.dryRun),n=await t.list(),i=e.args.dryRun?[...n,...r]:n;if(i.length===0)return{packages:[],stones:[]};let{packages:s}=await O.scan({single:e.config.get("single")}),a=A.mergeAll(i),o=Q.applyStone(a,s);if(o.length===0)throw new g("No packages to update","Stones don't reference any known packages");return{packages:o,stones:i}}async commitAndPushChanges(e,t,r){let n=ne();n.start("Applying release changes...");let i=await this.applyReleaseChanges(e,t,r);for(let a of i)await Bun.$`git add ${a}`.nothrow();if((await Bun.$`git diff --cached --quiet`.nothrow()).exitCode!==0)await Bun.$`git commit -m ${`${So} prepare release`}`;await Bun.$`git push origin ${_r} --force`,n.stop("Release branch ready")}async createOrUpdatePr(e,t){let r=ne(),n=await this.findExistingReleasePr();if(n)r.start("Updating PR..."),await this.updatePr(n.number,e,t),r.stop(`PR #${n.number} updated`),y.info(`
177
- ${l.green("Release PR updated:")} ${n.url}`);else{r.start("Creating PR...");let i=await this.createPr(e,t);r.stop(`PR #${i.number} created`),y.info(`
178
- ${l.green("Release PR created:")} ${i.url}`)}}buildPrTitle(e){let t=e.map((r)=>`${r.name}@${r.newVersion}`).join(", ");return`${So} ${t}`}buildPrBody(e,t){return[this.buildChangesSection(t),this.buildPackagesSection(e),this.buildStonesSection(t),this.buildFooter()].join(`
179
- `)}buildChangesSection(e){let t=["## Changes",""];for(let r of e){if(t.push(`### ${r.message}`,""),r.commits&&r.commits.length>0)for(let n of r.commits)t.push(`- ${n.message} (\`${n.hash}\`)`);else if(r.description)t.push(r.description);t.push("")}return t.join(`
169
+ `)}`)}async updatePackageVersions(e){if(this.options.dryRun)return;await this.packageUpdater.updateAll(e)}async generateChangelogs(e,t){if(this.options.dryRun)return;await this.changelogGenerator.generate(e,t)}async createCommit(e,t,r){if(this.options.dryRun)return;let s=await this.getOwnedPaths(t,r),n=s.map((h)=>Ge(h)),i=_a(this.config.get("commit").message,e,t),o=Ma(this.config.get("commit")),a=this.ledger?.data.baseCommit??await ie(),c=await xn(),l,d;try{if(await O(()=>Bun.$`git add -A -- ${n}`.quiet(),"Failed to stage release files"),await ie()!==a)throw new u("Release base commit changed before commit creation","Restart the release from the intended branch");l=await Ha(a,s,await this.getRepositoryRoot()),await this.ledger?.setExpectedReleaseTree(l),d=await Tn(s),await O(()=>Bun.$`git commit --only ${o} -m ${i} -- ${n}`.env(La(this.config.get("commit"))).quiet(),"Failed to create commit"),this.commitCreated=!0}catch(h){if(d){let f;try{f=await Tn(s)}catch(m){throw this.rollbackBlockedReason="release files could not be verified after commit failure",AggregateError([h,m],"Commit failed and release files could not be verified")}if(f!==d)throw this.rollbackBlockedReason="release-owned files changed while commit hooks ran",AggregateError([h],"Commit failed after a hook changed release-owned files")}try{await En(s)}catch(f){throw AggregateError([h,f],"Commit and index cleanup failed")}throw h}let g=await ie();if(this.createdCommit={baseCommit:a,oid:g,ref:c},!l)throw Error("Expected release tree was not recorded before commit");if(this.ledger){await Rt(this.ledger.data,g);return}await In(g,a),await An(g,l)}async createGitTags(e){if(this.options.dryRun)return;let t=await ie();for(let r of e){let s=`${r.name}@${r.newVersion??r.version}`;await O(()=>Bun.$`git -c tag.gpgSign=false tag -- ${s}`.quiet(),`Failed to create tag ${s}`),this.createdTags.push(s),this.createdTagTargets.set(s,t)}}async prepareNpmPublish(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key===t)return;let r=this.requireLedger("prepare npm artifacts");this.preparedNpmPublish=null;let s=await Xa(e);if(s.length===0){this.preparedNpmPublish={key:t,packages:[]};return}if(s.some((o)=>!r.data.artifacts[o.name]))await this.prepareBuildOutputs();let n=await mg(oi(fg(),"sisyphus-publish-")),i=[];try{for(let[o,a]of s.entries()){if(!r.data.artifacts[a.name]){let l=oi(n,`${String(o).padStart(4,"0")}.tgz`);await O(()=>this.prepareNpmArtifact(a,l),`Failed to prepare ${a.name}`),await r.setArtifact(a.name,l)}let c=r.resolveArtifactPath(a.name);Vr(await Yr(c)),i.push({artifactPath:c,pkg:a})}}finally{await Oc(n,{force:!0,recursive:!0})}this.preparedNpmPublish={key:t,packages:i}}async publishToNpm(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key!==t)await this.prepareNpmPublish(e);let r=this.preparedNpmPublish?.packages??[];if(r.length===0)return;try{for(let s of r)await this.publishPreparedPackage(s)}finally{this.preparedNpmPublish=null}}async pushRelease(){if(this.options.dryRun)return;await this.pushConfiguredRefs()}async createGitRelease(e,t){if(this.options.dryRun)return;if(t.length===0)return;await this.initCommitLinks();let r=await this.getProvider(),s=this.ledger?.data.operations.push;if(s){let n=s.refs.filter((i)=>i.destination.startsWith("refs/tags/"));if(n.length>0)await Qa(s,()=>this.getRepositoryRoot(),n)}for(let n of t){let i=Bn(e,n,this.commitUrlFn);await this.createProviderRelease(r,n.name,i)}}hasCrossedIrreversibleBoundary(){return this.irreversibleOperation!==null||this.ledger?.hasExternalProgress()===!0}createIncompleteReleaseError(e){let t=this.irreversibleOperation??"an external release operation",r=new u(`Release incomplete after ${t} began`,"Local state preserved; run sis roll --resume to reconcile and continue.");return r.cause=e,r}async rollback(e=!0){if(this.hasCrossedIrreversibleBoundary())return!1;if(await this.validateRollbackState(),this.preparedNpmPublish=null,await Va(this.createdCommit,this.createdTags,this.createdTagTargets,()=>this.getRepositoryRoot()),this.commitCreated){if(this.ownedPaths)await En(this.ownedPaths);this.commitCreated=!1,this.createdCommit=null}if(this.createdTags=[],this.createdTagTargets.clear(),await this.changelogGenerator.rollback(),await this.packageUpdater.rollback(),e)await this.removeReleaseLedger();return!0}async validateRollbackState(){if(this.rollbackBlockedReason)throw new u(`Cannot roll back release because ${this.rollbackBlockedReason}`,"Local release state and the recovery ledger were preserved");if(this.commitCreated&&!this.createdCommit)throw new u("Cannot identify the release commit for rollback","Local release state and the recovery ledger were preserved");if(this.commitCreated&&this.createdCommit){let[e,t]=await Promise.all([ie(),xn()]);if(e!==this.createdCommit.oid||t!==this.createdCommit.ref)throw new u(`Cannot roll back release commit because HEAD changed from ${this.createdCommit.oid}`,"Local release state and the recovery ledger were preserved")}if(this.commitCreated&&this.ownedPaths){let e=this.ownedPaths.map((r)=>Ge(r));if((await O(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${e}`.quiet(),"Failed to inspect release files before rollback")).stdout.length>0)throw new u("Cannot roll back release because release-owned files changed after commit creation","Local release state and the recovery ledger were preserved")}for(let e of this.createdTags){let t=this.createdTagTargets.get(e),r=await Ba(`refs/tags/${e}`);if(!t||r!==t)throw new u(`Cannot roll back release because tag ${e} changed after creation`,"Local release state and the recovery ledger were preserved")}}async removeReleaseLedger(){if(!this.ledger)return;await this.ledger.remove(),this.ledger=null}needsReleaseLedger(e){return this.options.npm||this.options.push||this.options.createRelease||e&&this.options.tags}async recoverReleaseCommit(e){if(e.releaseCommit||!this.ledger)return;let t=await ie();if(!e.expectedReleaseTree&&!e.options.publishOnly)throw new u(`Release ${e.id} stopped before its expected release tree was recorded`,`No external operation was attempted; inspect the local changes and release ledger manually; delete ${this.ledger.activePath} to abort the release`);if(!e.options.publishOnly&&t===e.baseCommit)throw new u(`Release ${e.id} stopped before its release commit was created`,`No external operation was attempted; restore the release-owned files from ${e.baseCommit} and delete ${this.ledger.activePath} to abort the release`);await this.ensureExpectedReleaseTree(e,t),await Rt(this.ledger.data,t),await this.ledger.setReleaseCommit(t)}async ensureLedgerPlan(e,t){if(!this.ledger)return;let r=this.ledger.data;if(await this.reconcileReleaseTags(r),r.options.npm)for(let s of e){if(!r.operations.npm[s.name]||r.operations.npmRegistries[s.name])continue;await this.ledger.setNpmRegistry(s.name,await za(s))}if(!r.operations.push&&(r.options.push||r.options.publishOnly&&r.options.tags))await this.configureLedgerPush(r);if(r.options.createRelease){await this.initCommitLinks();for(let s of e)await this.ledger.configureProviderRelease(s.name,Bn(t,s,this.commitUrlFn));await this.getProvider()}}async reconcileReleaseTags(e){if(!this.ledger||!e.options.tags)return;if(!e.releaseCommit)throw Error("Cannot reconcile release tags without a release commit");for(let t of e.releaseTags){let r=`refs/tags/${t}`,s=await Bun.$`git rev-parse --verify ${r}`.quiet().nothrow();if(s.exitCode!==0){await O(()=>Bun.$`git -c tag.gpgSign=false tag -- ${t} ${e.releaseCommit}`.quiet(),`Failed to create tag ${t}`);continue}let n=s.stdout.toString().trim();if(n!==e.releaseCommit)throw new u(`Release tag ${t} points to ${n}, expected ${e.releaseCommit}`,"Do not move release tags before the release completes")}if(!e.tagsReady)await this.ledger.markTagsReady()}async configureLedgerPush(e){if(!this.ledger||!e.releaseCommit)throw Error("Cannot configure release push without a recorded release commit");let t=e.releaseCommit,r=e.releaseTags.map((c)=>({destination:`refs/tags/${c}`,oid:t,source:`refs/tags/${c}`}));if(e.options.publishOnly){let c=await jn(await Nn()),l=await rs(await ns(c),()=>this.getRepositoryRoot());this.validateProviderDestination(l),await Ln(r),await this.ledger.configurePush(c,l,r);return}let{branch:s,remote:n}=await ec(),i=await rs(await ns(n),()=>this.getRepositoryRoot());this.validateProviderDestination(i);let o=`refs/heads/${s}`,a=[{destination:o,oid:e.releaseCommit,source:o},...r];await Ln(a),await this.ledger.configurePush(n,i,a)}validateProviderDestination(e){if(this.options.createRelease&&!ss(e))throw new u("Push destination is not a supported git provider repository","Provider releases require GitHub, GitLab, or Bitbucket")}async resumeExternalOperations(e,t){let r=this.requireLedger("resume external operations");if(r.phase==="completed"){await this.completeRelease();return}if(r.data.operations.push)await this.pushConfiguredRefs();if(this.options.npm)await this.publishToNpm(e);if(this.options.createRelease)await this.createGitRelease(t,e);await this.completeRelease()}async pushConfiguredRefs(){let e=this.requireLedger("push release refs"),t=e.data.operations.push;if(!t)throw Error("Release push is not configured");if(t.state==="completed")return;if(await St(t,()=>this.getRepositoryRoot()),t.state==="started"){await rc(e,t,()=>this.getRepositoryRoot());return}await e.setPhase("external"),await e.markPush("started"),this.crossIrreversibleBoundary("remote push"),await is(t,()=>this.getRepositoryRoot()),await e.markPush("completed")}async publishPreparedPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.operations.npm[e.pkg.name];if(!r)throw Error(`Npm operation is not configured for ${e.pkg.name}`);if(r.state==="completed")return;if(r.state==="started"){await Za(t,e.pkg);return}await t.setPhase("external"),await t.markNpm(e.pkg.name,"started"),this.crossIrreversibleBoundary("npm publication"),await this.publishPackage(e),await t.markNpm(e.pkg.name,"completed")}requireLedger(e){if(!this.ledger)throw Error(`Cannot ${e} without an active release ledger`);return this.ledger}async createProviderRelease(e,t,r){let s=this.requireLedger(`create the provider release for ${r.tag}`),n=s.data.operations.providerReleases[t];if(!n)throw Error(`Provider release is not configured for ${t}`);if(n.state==="completed")return;if(n.state==="started"){await this.reconcileStartedProviderRelease(e,t,n);return}await s.setPhase("external"),await s.markProviderRelease(t,"started"),this.crossIrreversibleBoundary(`git provider release creation for ${r.tag}`),await O(()=>e.createRelease(r),`Failed to create release for ${r.tag}`),await s.markProviderRelease(t,"completed")}async reconcileStartedProviderRelease(e,t,r){let s=await O(()=>e.getRelease(r.tag),`Failed to inspect release for ${r.tag}`);if(!s)throw new u(`Cannot safely resume provider release ${r.tag}`,"The provider does not confirm the previous creation; inspect the release manually");if(s.draft||s.tag!==r.tag||s.title!==r.title||s.notes!==r.notes)throw new u(`Cannot safely resume provider release ${r.tag}: existing release does not match`,"Do not overwrite the existing release; compare its title and notes with the release ledger");await this.ledger?.markProviderRelease(t,"completed")}async getOwnedPaths(e,t){let r=await this.getRepositoryRoot(),s=this.options.changelog?Da(this.config.get("changelog"),e):[],n=[...e.map((o)=>o.file),...s,oi(mt,Er),...this.stoneManager.getFilePaths(t)],i=[...new Set(n.map((o)=>Fa(r,o)))].sort();if(this.ownedPaths&&(this.ownedPaths.length!==i.length||this.ownedPaths.some((o,a)=>o!==i[a])))throw Error("Release paths changed");return this.ownedPaths=i,i}async getRepositoryRoot(){if(this.repositoryRoot)return this.repositoryRoot;let t=(await O(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root")).stdout.toString().trim();if(!t)throw Error("Git repository root is empty");return this.repositoryRoot=yg(t),this.repositoryRoot}async validatePublishCommitBinding(e){let t=this.requireLedger("bind npm artifacts to a release commit").data;if(!t.releaseCommit||!t.expectedReleaseTree||e!==t.releaseCommit)throw new u(`Publish source does not match the recorded release commit for ${t.id}`,t.releaseCommit?`Check out ${t.releaseCommit} before publishing`:"Resume the release before publishing");await Rt(t,e)}async ensureExpectedReleaseTree(e,t){if(e.expectedReleaseTree)return;if(!this.ledger||!e.options.publishOnly||t!==e.baseCommit)throw new u(`Release ${e.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");await this.ledger.setExpectedReleaseTree(await On(e.baseCommit))}getPackageSetKey(e){return e.map((t)=>`${t.name}\x00${t.file}`).join("\x00")}async publishPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.options.npmTag,s=Vr(await Yr(e.artifactPath)),n=t.data.operations.npmRegistries[e.pkg.name];if(!n)throw Error(`Npm registry is not configured for ${e.pkg.name}`);let i=ts(e.pkg.name,n);await O(()=>Bun.$`npm publish ${e.artifactPath} --tag ${r} --access ${s} --ignore-scripts --registry ${n} ${i}`.cwd(_c(e.pkg.file)).quiet(),`Failed to publish ${e.pkg.name}`)}async prepareNpmArtifact(e,t){let r=_c(e.file),s=null;try{let n=await ie();await this.validatePublishCommitBinding(n),await qt(await this.getRepositoryRoot()),await this.validateIgnoredBuildInputs();let i=this.getBuildConfig();if(await xa(e,r,await this.getRepositoryRoot(),i.matcher),i.command.length>0)await Cn(i.command,r,`Failed to build ${e.name}`);let o=await ie();await this.validatePublishCommitBinding(o);let a=await Wt(await this.getRepositoryRoot());if(o!==n||a.length>0)throw new u(`Package build changed repository source files for ${e.name}`,"This package was not packed and nothing was published; restore the build changes before retrying");let c=await hg(e.file,"utf-8"),{catalogs:l,workspaceVersions:d}=await this.getPublishContext(),g=ua(c,l,d);Vr(g);let h=JSON.parse(g),f=e.newVersion??e.version;if(h.name!==e.name||h.version!==f)throw Error(`Packed manifest identity mismatch for ${e.name}: expected ${e.name}@${f}, found ${String(h.name)}@${String(h.version)}`);s=await ka(e,r,g);let m=await Sa(s,t);if(m.name!==e.name||m.version!==f)throw new u(`Packed artifact identity mismatch for ${e.name}: found ${m.name}@${m.version}`,"This package was not recorded and nothing was published");if(!Ta(g,await Yr(t)))throw new u(`Packed manifest does not match the prepared manifest for ${e.name}`,"This package was not recorded and nothing was published");let y=await ie();await this.validatePublishCommitBinding(y);let R=await Wt(await this.getRepositoryRoot());if(y!==n||R.length>0)throw new u(`Package packing changed repository source files for ${e.name}`,"This package was not recorded and nothing was published; restore the changes before retrying")}finally{if(s)await Oc(s,{force:!0,recursive:!0})}}async validateIgnoredBuildInputs(){if(this.ignoredBuildInputsValidated)return;await Rn(await this.getRepositoryRoot(),"",this.getBuildConfig().matcher),this.ignoredBuildInputsValidated=!0}getLedgerSnapshot(){return this.ledger?.data??null}getBuildConfig(){return this.buildConfig??=Aa(this.config.get("release")?.build),this.buildConfig}async prepareBuildOutputs(){if(this.buildOutputsPrepared)return;let e=this.getBuildConfig(),t=await this.getRepositoryRoot(),r=await ie();await this.validatePublishCommitBinding(r),await qt(t),await Oa(t,e.matcher),await Sn(t,"",e.matcher);for(let[s,n]of e.root.entries())await Cn(n,t,`Failed to run release root build command ${s}`);if(e.root.length>0){let s=await ie();if(await this.validatePublishCommitBinding(s),s!==r||(await Wt(t)).length>0)throw new u("Root build changed repository source files","No package was packed and nothing was published; restore the build changes before retrying")}await this.validateIgnoredBuildInputs(),this.buildOutputsPrepared=!0}async getPublishContext(){if(!this.publishContext){let e=await Bun.file("package.json").json(),{packages:t}=await F.scan({single:this.config.get("single")});this.publishContext={catalogs:ca(e),workspaceVersions:la(t.values())}}return this.publishContext}crossIrreversibleBoundary(e){this.irreversibleOperation??=e}}var wg=6;function bs(e,t){let r=e.map((s)=>ln(s,t));return{skipped:[...new Set(r.flatMap((s)=>s.skipped))].sort(),stones:r.map((s)=>s.stone)}}function ar(e,t,r){let s=[...new Set(e.allPackages)].filter((n)=>!t.has(n)&&!ee(n,r)).sort();if(s.length>0)return{kind:"unknown-packages",names:s};return{kind:"ignored-only"}}function ai(e,t,r,s){let{stone:n}=ln(e,r),i=ar(n,t,r);if(i.kind==="unknown-packages")return{kind:"invalid",message:`Pending stones reference unknown packages: ${i.names.join(", ")}`};try{return{kind:"ok",packages:z.applyStone(n,t,s).flatMap((a)=>a.bump&&a.newVersion?[{bump:a.bump,name:a.name,newVersion:a.newVersion,version:a.version}]:[])}}catch(o){if(o instanceof u)return{kind:"invalid",message:o.message};throw o}}function Mc(e,t){let r=t.map((o)=>`${o.name}@${o.newVersion??o.version}`),s=r.slice(0,wg),n=r.length-s.length,i=n>0?` +${n} more`:"";return`${e} ${s.join(", ")}${i}`}var bg=1;function Lc(e){let{ledger:t}=e,r=t?vg(t):$g(e.packages),s=r.filter((i)=>i.published).map((i)=>({name:i.name,version:i.newVersion})),n={baseCommit:t?.baseCommit??null,command:"roll",mode:e.mode,operations:{npmTag:t?.options.npmTag??e.npmTag,providerReleases:Rg(t),pushed:t?.operations.push?.state==="completed"},packages:r,published:s.length>0,publishedPackages:s,releaseCommit:t?.releaseCommit??e.releaseCommit??null,releaseId:t?.id??null,schemaVersion:bg,status:e.status,stones:t?t.stones.map((i)=>i.id):e.stones.map((i)=>i.id),tags:t?t.tagsReady?[...t.releaseTags]:[]:Pg(e.packages,e.tagsEnabled),warnings:[...e.warnings??[]]};if(e.changelogFiles)n.changelogFiles=[...e.changelogFiles];if(e.error!==void 0)n.error=Sg(e.error);return n}function vg(e){return e.packages.map((t)=>({integrity:e.artifacts[t.name]?.integrity??null,name:t.name,newVersion:t.newVersion,oldVersion:t.oldVersion,private:t.isPrivate,published:e.operations.npm[t.name]?.state==="completed",registry:e.operations.npmRegistries[t.name]??null,tag:e.tagsReady?e.releaseTags.find((r)=>r===Dc(t.name,t.newVersion))??null:null}))}function Dc(e,t){return`${e}@${t}`}function $g(e){return e.map((t)=>({integrity:null,name:t.name,newVersion:t.newVersion??t.version,oldVersion:t.version,private:t.isPrivate,published:!1,registry:null,tag:null}))}function Pg(e,t){if(!t)return[];return e.map((r)=>Dc(r.name,r.newVersion??r.version)).sort()}function Rg(e){let t=Object.values(e?.operations.providerReleases??{});return t.length>0&&t.every((r)=>r.state==="completed")}function Sg(e){let t=e instanceof Error?e.message:String(e),r=e instanceof u?e.hint:void 0,s=Nc(e);return{...s.length>0?{causes:s}:{},...r?{hint:r}:{},message:t}}function Nc(e,t=new Set){if(!(e instanceof Error)||t.has(e))return[];return t.add(e),[...e instanceof AggregateError?e.errors:[],e.cause].filter((n)=>n instanceof Error).flatMap((n)=>[n.message,...Nc(n,t)])}var vs="sisyphus/release",ci="sisyphus-release",Cg="Sisyphus release PR",kg="6f42c1",jc="chore(release):",xg=B({dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"}});class li extends D{name="release-pr";description="Create or update a release PR from pending stones";args=xg;provider=null;async getProvider(){if(!this.provider)this.provider=await ht();return this.provider}async execute(e){let t=await this.checkoutReleaseBranch();try{let{stones:r,packages:s}=await this.collectReleaseData(e);if(r.length===0){v.info(p.dim("No pending stones found, skipping release PR"));return}let n=this.buildPrTitle(s),i=this.buildPrBody(s,r);if(v.info(`${p.bold("Release PR:")} ${n}`),v.info(`${p.dim("Packages:")} ${s.map((o)=>o.name).join(", ")}`),e.args.dryRun){v.info(p.yellow(`
170
+ [dry-run] Would create/update release PR`)),v.info(p.dim(`
171
+ PR Body preview:`)),v.info(i);return}await this.commitAndPushChanges(e,r,s),await this.createOrUpdatePr(n,i)}finally{await this.restoreBranch(t)}}async checkoutReleaseBranch(){if((await Bun.$`git status --porcelain=v1 --untracked-files=all`.quiet()).stdout.length>0)throw new u("Working tree must be clean before preparing a release PR","Commit or stash your changes before running sis actions release-pr");let r=(await Bun.$`git branch --show-current`.quiet()).stdout.toString().trim()||(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim(),n=await(await this.getProvider()).getDefaultBranch();return await Bun.$`git fetch origin ${n}`,await Bun.$`git checkout -B ${vs} origin/${n}`,r}async collectReleaseData(e){let t=new E(e.config),r=await this.generateStonesFromCommits(e,t,e.args.dryRun),s=await t.list(),n=e.args.dryRun?[...s,...r]:s;if(n.length===0)return{packages:[],stones:[]};let i=e.config.get("ignore")??[],{stones:o,skipped:a}=bs(n,i);if(a.length>0)v.warn(p.yellow(`Excluded by config.ignore: ${a.join(", ")}`));let{packages:c}=await F.scan({single:e.config.get("single")}),l=A.mergeAll(o),d=ar(l,c,i);if(d.kind==="unknown-packages")throw new u(`Pending stones reference unknown packages: ${d.names.join(", ")}`,"Remove or update the stale stones before creating a release PR");let{cycle:g,ordered:h}=Ut(z.applyStone(l,c,ae(e.config).kinds));if(g.length>0)v.warn(p.yellow(`Dependency cycle between ${g.join(", ")}; publish order may not satisfy every pin`));if(h.length===0)return v.warn(p.yellow("Pending stones reference no releasable packages")),{packages:[],stones:[]};return{packages:h,stones:o}}async commitAndPushChanges(e,t,r){let s=ye();s.start("Applying release changes...");let n=[...await this.updatePackages(r),...await this.generateChangelogs(e,t,r)],i=await this.archiveStones(e,t);if(await this.stageFiles(n),await this.recordCurrentRelease(e,t,r,i),await this.stageFiles([e.config.get("sisyphusDir")]),(await Bun.$`git diff --cached --quiet`.nothrow()).exitCode!==0)await Bun.$`git commit -m ${`${jc} prepare release`}`;await Bun.$`git push origin ${vs} --force`,s.stop("Release branch ready")}async createOrUpdatePr(e,t){let r=ye(),s=await this.findExistingReleasePr();if(s)r.start("Updating PR..."),await this.updatePr(s.number,e,t),r.stop(`PR #${s.number} updated`),v.info(`
172
+ ${p.green("Release PR updated:")} ${s.url}`);else{r.start("Creating PR...");let n=await this.createPr(e,t);r.stop(`PR #${n.number} created`),v.info(`
173
+ ${p.green("Release PR created:")} ${n.url}`)}}buildPrTitle(e){return Mc(jc,e)}buildPrBody(e,t){return[this.buildChangesSection(t),this.buildPackagesSection(e),this.buildStonesSection(t),this.buildFooter()].join(`
174
+ `)}buildChangesSection(e){let t=["## Changes",""];for(let r of e){if(t.push(`### ${r.message}`,""),r.commits&&r.commits.length>0)for(let s of r.commits)t.push(`- ${s.message} (\`${s.hash}\`)`);else if(r.description)t.push(r.description);t.push("")}return t.join(`
180
175
  `)}buildPackagesSection(e){let t=["## Packages",""];for(let r of e)t.push(`- \`${r.name}\` ${r.version} \u2192 ${r.newVersion}`);return t.push(""),t.join(`
181
176
  `)}buildStonesSection(e){let t=["## Stones",""];for(let r of e)t.push(`- \`${r.id}\`: ${r.message}`);return t.push(""),t.join(`
182
177
  `)}buildFooter(){return["---","*This PR was automatically created by [Sisyphus](https://github.com/r5n-labs/clis).*","*Merging this PR will trigger the release workflow.*"].join(`
183
- `)}async findExistingReleasePr(){let t=await(await this.getProvider()).findPr({head:_r,label:vi});return t?{number:t.number,url:t.url}:null}async generateStonesFromCommits(e,t,r){let i=await new Ve(e.config).analyze({single:e.config.get("single")});if(i.length===0)return[];let{packages:s}=await O.scan({single:e.config.get("single")}),a=[];for(let[o,c]of i.entries()){let p=Ve.buildStoneData(c,s);if(r)y.info(`${l.dim("[dry-run] Would generate stone:")} ${c.message}`),a.push(A.create(p,o));else{let m=await t.create(p);a.push(m),y.info(`${l.dim("Generated stone:")} ${m.id}`)}}return a}async findNewestCommitHash(e){let t=e.flatMap((n)=>n.commits??[]).map((n)=>n.hash);if(t.length===0)return null;return(await Bun.$`git log -1 --format=%H ${t}`.quiet().nothrow()).stdout.toString().trim()||null}async stashChanges(){await Bun.$`git stash --include-untracked`.nothrow()}async applyReleaseChanges(e,t,r){let n=[];return n.push(...await this.updatePackages(r)),n.push(...await this.generateChangelogs(e,t,r)),n.push(...await this.archiveStonesAndUpdateConfig(e,t,r)),n}async updatePackages(e){return await new Ct().updateAll(e),e.map((r)=>r.file)}async generateChangelogs(e,t,r){let n=e.config.get("changelog");if(!n.generate)return[];return await new _e(n).generate(t,r),[n.filename,`**/${n.filename}`]}async archiveStonesAndUpdateConfig(e,t,r){let i=await new I(e.config).archive(t),s=this.buildPackageVersions(r),a=await Pr(e.config.get("sisyphusDir")),o={packages:s,sourceHash:a,stoneIds:t.map((c)=>c.id),timestamp:i};return e.config.set("currentRelease",{...o,planHash:vr(o,t.map((c)=>c.toJson()))}),await this.updateLastStone(e,t),[e.config.get("sisyphusDir")]}buildPackageVersions(e){let t={};for(let r of e)if(r.newVersion)t[r.name]={newVersion:r.newVersion,oldVersion:r.version};return t}async updateLastStone(e,t){let r=await this.findNewestCommitHash(t);if(r)e.config.set("lastStone",{commit:r,date:new Date().toISOString()})}async createPr(e,t){let r=await this.getProvider(),n=await r.getDefaultBranch();await r.ensureLabelExists(vi,{color:Ng,description:jg});let i=await r.createPr({base:n,body:t,head:_r,labels:[vi],title:e});return{number:i.number,url:i.url}}async updatePr(e,t,r){await(await this.getProvider()).updatePr(e,{body:r,title:t})}async restoreMainBranch(e){try{await Bun.$`git checkout ${e}`.quiet()}catch(t){y.warn(l.dim(`Failed to restore branch: ${t}`))}}}class ki extends j{name="actions";description="CI/CD integration";init(){this.registerSubcommands([new vn,new Ri])}}var Bg=B({config:{alias:"c",default:!1,description:"Include config in output",type:"boolean"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class $i extends j{name="check";description="Show workspace packages and pending stones";args=Bg;async execute(e){let t=await this.gatherData(e);if(e.args.json)this.printJson(t);else this.printFormatted(t)}async gatherData(e){let t=e.config.get("single"),{packages:r,packageNames:n}=await O.scan({single:t}),s=(t?null:await O.scan({single:!0}))?.packages.values().next().value??r.values().next().value,o=await new I(e.config).list();return{config:e.args.config?e.config.getAll():void 0,packageNames:n,packages:r,root:s,stones:o}}printJson(e){let t={config:e.config,packages:e.packageNames.map((r)=>({name:r,version:e.packages.get(r)?.version??"0.0.0"})),root:{name:e.root?.name??"",version:e.root?.version??"0.0.0"},stones:e.stones.map((r)=>this.stoneToJson(r,e.packages))};console.log(JSON.stringify(t,null,2))}stoneToJson(e,t){let r=[];for(let n of He)for(let i of e.getPackages(n)){let a=t.get(i)?.version??"0.0.0";r.push({bump:n,name:i,newVersion:se.bump(a,n,e.tag),version:a})}return{id:e.id,message:e.message,packages:r,tag:e.tag}}printFormatted(e){if(this.printRootInfo(e.root),this.printPackages(e),e.stones.length>0)this.printStones(e.stones,e.packages);if(e.config)this.printConfig(e.config);q(l.green("Sisyphus check complete."))}printConfig(e){let t=l.dim(JSON.stringify(e,null,2));y.step(`${l.bold(l.green("Config:"))}
184
- ${t}`)}printRootInfo(e){if(!e)return;let t=e.version?l.dim(`@${e.version}`):"";y.step(`${l.bold(l.green("Root package:"))} ${l.cyan(e.name)}${t}`)}printPackages(e){let t=[`${l.bold(l.green("Packages:"))}`];for(let r of e.packageNames){let n=e.packages.get(r),i=n?.version?l.dim(`@${n.version}`):"";t.push(` ${l.dim("\u2022")} ${l.cyan(r)}${i}`)}y.step(t.join(`
185
- `))}printStones(e,t){let r=e.map((n)=>this.formatStone(n,t)).join(`
178
+ `)}async findExistingReleasePr(){let t=await(await this.getProvider()).findPr({head:vs,label:ci});return t?{number:t.number,url:t.url}:null}async generateStonesFromCommits(e,t,r){let n=await new et(e.config).analyze({single:e.config.get("single")});if(n.length===0)return[];let{packages:i}=await F.scan({single:e.config.get("single")}),o=[];for(let[a,c]of n.entries()){let l=et.buildStoneData(c,i,ae(e.config));if(r)v.info(`${p.dim("[dry-run] Would generate stone:")} ${c.message}`),o.push(A.create(l,a));else{let d=await t.create(l);o.push(d),v.info(`${p.dim("Generated stone:")} ${d.id}`)}}return o}async findNewestCommitHash(e){let t=e.flatMap((s)=>s.commits??[]).map((s)=>s.hash);if(t.length===0)return null;return(await Bun.$`git log -1 --format=%H ${t}`.quiet().nothrow()).stdout.toString().trim()||null}async stageFiles(e){await Bun.$`git --literal-pathspecs add -- ${e}`}async updatePackages(e){return await new Gt().updateAll(e),e.map((r)=>r.file)}async generateChangelogs(e,t,r){let s=e.config.get("changelog");if(!s.generate)return[];return await new Qe(s).generate(t,r),[s.filename,`**/${s.filename}`]}async archiveStones(e,t){return new E(e.config).archive(t)}async recordCurrentRelease(e,t,r,s){let n=this.buildPackageVersions(r),i=await qr(e.config.get("sisyphusDir")),o={packages:n,sourceHash:i,stoneIds:t.map((a)=>a.id),timestamp:s};e.config.set("currentRelease",{...o,planHash:Wr(o,t.map((a)=>a.toJson()))}),await this.updateLastStone(e,t)}buildPackageVersions(e){let t={};for(let r of e)if(r.newVersion)t[r.name]={newVersion:r.newVersion,oldVersion:r.version};return t}async updateLastStone(e,t){let r=await this.findNewestCommitHash(t);if(r)e.config.set("lastStone",{commit:r,date:new Date().toISOString()})}async createPr(e,t){let r=await this.getProvider(),s=await r.getDefaultBranch();await r.ensureLabelExists(ci,{color:kg,description:Cg});let n=await r.createPr({base:s,body:t,head:vs,labels:[ci],title:e});return{number:n.number,url:n.url}}async updatePr(e,t,r){await(await this.getProvider()).updatePr(e,{body:r,title:t})}async restoreBranch(e){try{await Bun.$`git checkout ${e}`.quiet()}catch(t){v.warn(p.dim(`Failed to restore branch: ${t}`))}}}class ui extends D{name="actions";description="CI/CD integration";init(){this.registerSubcommands([new Qs,new li])}}var Tg=B({config:{alias:"c",default:!1,description:"Include config in output",type:"boolean"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class pi extends D{name="check";description="Show workspace packages and pending stones";args=Tg;async execute(e){let t=await this.gatherData(e);if(e.args.json)this.printJson(t);else this.printFormatted(t)}async gatherData(e){let t=e.config.get("single"),r=e.config.get("ignore")??[],s=await F.scan({single:t}),n=s.packages,i=s.packageNames.filter((d)=>!ee(d,r)),a=(t?null:await F.scan({single:!0}))?.packages.values().next().value??n.values().next().value,l=await new E(e.config).list();return{config:e.args.config?e.config.getAll():void 0,ignore:r,kinds:ae(e.config).kinds,packageNames:i,packages:n,root:a,stones:l}}printJson(e){let t={config:e.config,packages:e.packageNames.map((r)=>({name:r,version:e.packages.get(r)?.version??"0.0.0"})),root:{name:e.root?.name??"",version:e.root?.version??"0.0.0"},stones:e.stones.map((r)=>this.stoneToJson(r,e))};console.log(JSON.stringify(t,null,2))}stoneToJson(e,t){let r=ai(e,t.packages,t.ignore,t.kinds);if(r.kind==="invalid")return{id:e.id,invalid:r.message,message:e.message,packages:[],tag:e.tag};return{id:e.id,message:e.message,packages:r.packages,tag:e.tag}}printFormatted(e){if(this.printRootInfo(e.root),this.printPackages(e),e.stones.length>0)this.printStones(e);if(e.config)this.printConfig(e.config);G(p.green("Sisyphus check complete."))}printConfig(e){let t=p.dim(JSON.stringify(e,null,2));v.step(`${p.bold(p.green("Config:"))}
179
+ ${t}`)}printRootInfo(e){if(!e)return;let t=e.version?p.dim(`@${e.version}`):"";v.step(`${p.bold(p.green("Root package:"))} ${p.cyan(e.name)}${t}`)}printPackages(e){let t=[`${p.bold(p.green("Packages:"))}`];for(let r of e.packageNames){let s=e.packages.get(r),n=s?.version?p.dim(`@${s.version}`):"";t.push(` ${p.dim("\u2022")} ${p.cyan(r)}${n}`)}v.step(t.join(`
180
+ `))}printStones(e){let t=e.stones.map((r)=>this.formatStone(r,e)).join(`
186
181
 
187
- `);y.step(`${l.bold(l.green("Stones:"))}
182
+ `);v.step(`${p.bold(p.green("Stones:"))}
188
183
 
189
- ${r}`)}formatStone(e,t){let r=[];if(r.push(`${l.bold("Stone:")} ${l.cyan(e.id)}`),e.tag)r.push(`${l.dim("Tag:")} ${e.tag}`);r.push(`${l.dim("Message:")} ${e.message}`),r.push(`${l.bold("Packages:")}`);for(let n of He){let i=e.getPackages(n);if(i.length===0)continue;for(let s of i){let o=t.get(s)?.version??"0.0.0",c=se.bump(o,n,e.tag),p=at[n],m=st[n];r.push(` ${m} ${l.cyan(s)}@${p(c)} ${l.dim(`(${n})`)}`)}}return r.join(`
190
- `)}}var Ug=B({changelog:{description:"Generate changelog for releases",type:"boolean"},commitAuthor:{description:"Commit author name",type:"string"},commitEmail:{description:"Commit author email",type:"string"},commitMessage:{description:"Commit message template",type:"string"},createRelease:{description:"Create a release on git provider",type:"boolean"},default:{alias:"d",default:!1,description:"Reset to default config",type:"boolean"},force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},npm:{description:"Publish to NPM on release",type:"boolean"},push:{description:"Push commits and tags to remote on release",type:"boolean"},rootChangelog:{description:"Generate combined changelog for monorepo",type:"boolean"},single:{alias:"s",description:"Setup for single package (not monorepo)",type:"boolean"},tag:{alias:"t",description:"Default release tag",type:"string"},tags:{description:"Create git tags on release",type:"boolean"}});class Ci extends j{name="init";description="Initializes Sisyphus config or edits it";args=Ug;async execute(e){let{default:t,force:r}=e.args;if(t){e.config.save(nt),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version);return}if(!e.interactive&&e.config.exists()&&!r){q(l.yellow("Config already exists. Use --force to replace."));return}let n=e.config.getAll(),{default:i,force:s,...a}=e.args,o=e.interactive?await this.runInitForm(n):a,c=this.mapValuesToConfig(o),p=qe({...n},c);e.config.save(p),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version)}mapValuesToConfig(e){let t=(a)=>Object.fromEntries(Object.entries(a).filter(([,o])=>o!==void 0)),r=(a)=>Object.keys(a).length>0,n=t({author:e.commitAuthor,email:e.commitEmail,message:e.commitMessage}),i=t({generate:e.changelog,root:e.rootChangelog}),s=t({createRelease:e.createRelease,npm:e.npm,push:e.push,tags:e.tags});return{...t({single:e.single,tag:e.tag}),...r(n)&&{commit:n},...r(i)&&{changelog:i},...r(s)&&{release:s}}}async runInitForm(e){let t=await Zt({changelog:()=>T({active:"Yes, generate changelog",inactive:"Skip changelog",initialValue:e.changelog?.generate??!0,message:"Generate changelog for release?"}),commitAuthor:({results:{configureCommit:r}})=>r?ie({initialValue:e.commit?.author??"",message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{configureCommit:r}})=>r?ie({initialValue:e.commit?.email??"",message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{configureCommit:r}})=>r?ie({initialValue:e.commit?.message??"",message:"Commit message",placeholder:"release: <packageName@version>"}):void 0,configureCommit:()=>T({active:"Yes, configure commit",inactive:"Skip commit config",initialValue:!!(e.commit?.author||e.commit?.email||e.commit?.message),message:"Configure commit for release? Default commit message is `release: <packageName@version>`"}),createRelease:()=>T({active:"Yes, create a release",inactive:"Skip release creation",initialValue:e.release?.createRelease??!1,message:"Create a release on git provider when releasing packages?"}),npm:()=>T({active:"Yes, publish packages to NPM",inactive:"Skip NPM release",initialValue:e.release?.npm??!1,message:"Publish packages to NPM when releasing packages?"}),push:()=>T({active:"Yes, push to remote",inactive:"No, keep local",initialValue:e.release?.push??!1,message:"Should `roll` command push commits and tags to remote?"}),rootChangelog:({results:{changelog:r}})=>r?T({active:"Yes, generate combined changelog",inactive:"Skip root changelog",initialValue:e.changelog?.root??!1,message:"Generate combined changelog for monorepo?"}):void 0,single:()=>T({active:"Yes, setup for root package",inactive:"No, setup for monorepo workspace packages",initialValue:e.single??!1,message:"Setup Sisyphus for only root package?"}),tag:()=>ie({initialValue:e.tag??"latest",message:"Tag used when versioning packages. Leave `latest` if you are not sure.",placeholder:"latest"}),tags:()=>T({active:"Yes, create tags for the release",inactive:"Skip tags",initialValue:e.release?.tags??!1,message:"Create tags for the release?"})},{onCancel:()=>{throw new me}});return{changelog:t.changelog,commitAuthor:t.commitAuthor,commitEmail:t.commitEmail,commitMessage:t.commitMessage,createRelease:t.createRelease,npm:t.npm,push:t.push,rootChangelog:t.rootChangelog,single:t.single,tag:t.tag,tags:t.tags}}async setLastStoneToHead(e){try{let r=(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim();if(r)e.config.set("lastStone",{commit:r,date:new Date().toISOString()})}catch{}}displaySuccessNote(e){q(`${l.magenta(`${l.bold("Sisyphus ")}${l.underline(l.italic(`v${e??"unknown"}`))}`)}${l.green(" is setup to roll stones.")}
184
+ ${t}`)}formatStone(e,t){let r=[];if(r.push(`${p.bold("Stone:")} ${p.cyan(e.id)}`),e.tag)r.push(`${p.dim("Tag:")} ${e.tag}`);r.push(`${p.dim("Message:")} ${e.message}`),r.push(`${p.bold("Packages:")}`);let s=ai(e,t.packages,t.ignore,t.kinds);if(s.kind==="invalid")return r.push(` ${p.yellow(`invalid: ${s.message}`)}`),r.join(`
185
+ `);for(let n of s.packages){let i=yt[n.bump],o=ft[n.bump];r.push(` ${o} ${p.cyan(n.name)}@${i(n.newVersion)} ${p.dim(`(${n.bump})`)}`)}return r.join(`
186
+ `)}}var Eg=B({changelog:{description:"Generate changelog for releases",type:"boolean"},commitAuthor:{description:"Commit author name",type:"string"},commitEmail:{description:"Commit author email",type:"string"},commitMessage:{description:"Commit message template",type:"string"},createRelease:{description:"Create a release on git provider",type:"boolean"},default:{alias:"d",default:!1,description:"Reset to default config",type:"boolean"},force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},npm:{description:"Publish to NPM on release",type:"boolean"},push:{description:"Push commits and tags to remote on release",type:"boolean"},rootChangelog:{description:"Generate combined changelog for monorepo",type:"boolean"},single:{alias:"s",description:"Setup for single package (not monorepo)",type:"boolean"},tag:{alias:"t",description:"Default release tag",type:"string"},tags:{description:"Create git tags on release",type:"boolean"}});class di extends D{name="init";description="Initializes Sisyphus config or edits it";args=Eg;async execute(e){let{default:t,force:r}=e.args;if(t){e.config.save(Fe),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version);return}if(!e.interactive&&e.config.exists()&&!r){G(p.yellow("Config already exists. Use --force to replace."));return}let s=e.config.getAll(),{default:n,force:i,...o}=e.args,a=e.interactive?await this.runInitForm(s):o,c=this.mapValuesToConfig(a),l=ct({...s},c);e.config.save(l),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version)}mapValuesToConfig(e){let t=(o)=>Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0)),r=(o)=>Object.keys(o).length>0,s=t({author:e.commitAuthor,email:e.commitEmail,message:e.commitMessage}),n=t({generate:e.changelog,root:e.rootChangelog}),i=t({createRelease:e.createRelease,npm:e.npm,push:e.push,tags:e.tags});return{...t({single:e.single,tag:e.tag}),...r(s)&&{commit:s},...r(n)&&{changelog:n},...r(i)&&{release:i}}}async runInitForm(e){let t=await fr({changelog:()=>j({active:"Yes, generate changelog",inactive:"Skip changelog",initialValue:e.changelog?.generate??!0,message:"Generate changelog for release?"}),configureCommit:()=>j({active:"Yes, configure commit",inactive:"Skip commit config",initialValue:!!(e.commit?.author||e.commit?.email||e.commit?.message),message:"Configure commit for release? Default commit message is `release: <packageName@version>`"}),commitAuthor:({results:{configureCommit:r}})=>r?ce({initialValue:e.commit?.author??"",message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{configureCommit:r}})=>r?ce({initialValue:e.commit?.email??"",message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{configureCommit:r}})=>r?ce({initialValue:e.commit?.message??"",message:"Commit message",placeholder:"release: <packageName@version>"}):void 0,createRelease:()=>j({active:"Yes, create a release",inactive:"Skip release creation",initialValue:e.release?.createRelease??!1,message:"Create a release on git provider when releasing packages?"}),npm:()=>j({active:"Yes, publish packages to NPM",inactive:"Skip NPM release",initialValue:e.release?.npm??!1,message:"Publish packages to NPM when releasing packages?"}),push:()=>j({active:"Yes, push to remote",inactive:"No, keep local",initialValue:e.release?.push??!1,message:"Should `roll` command push commits and tags to remote?"}),rootChangelog:({results:{changelog:r}})=>r?j({active:"Yes, generate combined changelog",inactive:"Skip root changelog",initialValue:e.changelog?.root??!1,message:"Generate combined changelog for monorepo?"}):void 0,single:()=>j({active:"Yes, setup for root package",inactive:"No, setup for monorepo workspace packages",initialValue:e.single??!1,message:"Setup Sisyphus for only root package?"}),tag:()=>ce({initialValue:e.tag??"latest",message:"Tag used when versioning packages. Leave `latest` if you are not sure.",placeholder:"latest"}),tags:()=>j({active:"Yes, create tags for the release",inactive:"Skip tags",initialValue:e.release?.tags??!1,message:"Create tags for the release?"})},{onCancel:()=>{throw new fe}});return{changelog:t.changelog,commitAuthor:t.commitAuthor,commitEmail:t.commitEmail,commitMessage:t.commitMessage,createRelease:t.createRelease,npm:t.npm,push:t.push,rootChangelog:t.rootChangelog,single:t.single,tag:t.tag,tags:t.tags}}async setLastStoneToHead(e){try{let r=(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim();if(r)e.config.set("lastStone",{commit:r,date:new Date().toISOString()})}catch{}}displaySuccessNote(e){G(`${p.magenta(`${p.bold("Sisyphus ")}${p.underline(p.italic(`v${e??"unknown"}`))}`)}${p.green(" is setup to roll stones.")}
191
187
 
192
- You can now start by creating a new stone by running ${l.green(N)}${l.blue(" version")}
188
+ You can now start by creating a new stone by running ${p.green(N)}${p.blue(" version")}
193
189
  and following the prompts.
194
190
 
195
- After you finished, you can release it by running ${l.green(N)}${l.blue(" roll")}
196
- `)}}var Gg=B({dryRun:{alias:"d",default:!1,description:"Preview migration without making changes",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class Si extends j{name="migrate";description="Migrate from changesets to sisyphus";args=Gg;parser=new Cn;async execute(e){if(!await this.parser.exists())throw new g("No .changeset directory found","This command migrates existing changesets to sisyphus stones");let{changesets:t,config:r}=await this.analyzeChangesets();if(this.displayPreview(t,r),e.args.dryRun){q("No changes made",l.yellow("Dry run"));return}if(!e.args.yes&&!await this.confirmMigration(t.length))return;let n=await this.createStones(e,t);await this.applyConfigMigration(e,r),this.displaySuccess(n)}async analyzeChangesets(){let e=ne();e.start("Analyzing changesets...");let t=await this.parser.parse();if(t.errors.length>0){e.error("Found issues while parsing");for(let r of t.errors)y.warn(l.yellow(r))}if(t.changesets.length===0)throw e.stop("No changesets found"),new g("No changeset files to migrate");return e.stop(`Found ${l.bold(String(t.changesets.length))} changeset(s)`),t}displayPreview(e,t){if(this.displayChangesets(e),t)this.displayConfigMapping(t)}async confirmMigration(e){return T({initialValue:!0,message:`Migrate ${e} changeset(s) to stones?`})}async createStones(e,t){let r=ne();r.start("Creating stones...");let n=new I(e.config),i=[];for(let s of t){let a=this.parser.toStoneData(s),o=await n.create(a);i.push(o.id)}return r.stop(`Created ${l.bold(String(i.length))} stone(s)`),i}async applyConfigMigration(e,t){if(!t)return;let r=ne();r.start("Migrating config..."),this.migrateConfig(e,t),r.stop("Config migrated")}displaySuccess(e){let t=e.map((r)=>` ${l.dim("-")} ${r}`).join(`
197
- `);q(`${t}
198
-
199
- Run ${l.green(`${N} stone list`)} to view stones
200
- Run ${l.green(`${N} preview`)} to see what will be released`,l.green("Migration complete"))}displayChangesets(e){for(let t of e){let r=Object.entries(t.packages).map(([i,s])=>{let a=s==="major"?l.red:s==="minor"?l.yellow:l.green;return`${i} ${l.dim("(")}${a(s)}${l.dim(")")}`}).join(", "),n=t.summary.length>60?`${t.summary.slice(0,60)}...`:t.summary;y.info(`${l.dim(t.filename)}
201
- ${l.dim("Packages:")} ${r}
202
- ${l.dim("Message:")} ${n||l.dim("(empty)")}`)}}displayConfigMapping(e){let t=[{category:"migrate",check:()=>(e.ignore?.length??0)>0,format:()=>`ignore: ${e.ignore?.join(", ")}`},{category:"migrate",check:()=>e.commit===!0,format:()=>"commit: enabled (will enable commit & push)"},{category:"migrate",check:()=>e.access==="public",format:()=>"access: public (will enable npm publishing)"},{category:"migrate",check:()=>e.changelog===!1,format:()=>"changelog: disabled"},{category:"info",check:()=>!!e.baseBranch&&e.baseBranch!=="master",format:()=>`baseBranch: ${e.baseBranch}`},{category:"info",check:()=>!!e.updateInternalDependencies,format:()=>`updateInternalDependencies: ${e.updateInternalDependencies}`},{category:"info",check:()=>Array.isArray(e.changelog)||typeof e.changelog==="string",format:()=>`changelog: ${Array.isArray(e.changelog)?e.changelog[0]:e.changelog}`},{category:"info",check:()=>Array.isArray(e.commit)||typeof e.commit==="string",format:()=>`commit: ${Array.isArray(e.commit)?e.commit[0]:e.commit}`},{category:"unsupported",check:()=>(e.linked?.length??0)>0,format:()=>`linked: ${e.linked?.length} group(s)`},{category:"unsupported",check:()=>(e.fixed?.length??0)>0,format:()=>`fixed: ${e.fixed?.length} group(s)`}],r={info:{color:l.blue,items:[],title:"Info (not migrated)"},migrate:{color:l.green,items:[],title:"Will migrate"},unsupported:{color:l.yellow,items:[],title:"Not yet supported"}};for(let n of t)if(n.check())r[n.category].items.push(l.dim(n.format()));for(let n of[r.migrate,r.info,r.unsupported])if(n.items.length>0)q(n.items.join(`
203
- `),n.color(n.title))}migrateConfig(e,t){if(t.ignore?.length){let r=e.config.get("ignore")??[],n=[...new Set([...r,...t.ignore])];e.config.set("ignore",n)}if(t.commit===!0){let r=e.config.get("commit")??{},n=e.config.get("release")??{};e.config.set("commit",{...r,author:r.author??"Sisyphus"}),e.config.set("release",{...n,push:!0})}if(t.access==="public"){let r=e.config.get("release")??{};e.config.set("release",{...r,npm:!0})}if(t.changelog===!1){let r=e.config.get("changelog")??{};e.config.set("changelog",{...r,generate:!1})}}}var Eo=100,qg=B({bump:{alias:"b",description:"Explicit bump type (major/minor/patch)",type:"string"},dryRun:{alias:"d",default:!1,description:"Preview without writing",type:"boolean"},message:{alias:"m",description:"Override stone message",type:"string"},packages:{alias:"p",description:"Filter packages (comma-separated)",type:"string"},url:{alias:"u",description:"PR URL",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmations",type:"boolean"}});class Ei extends j{name="pr";description="Create a stone from a Pull Request";args=qg;prompts=!0;async execute(e){let r=await new Ln(e.config).analyze(e.args.url);this.displayPrSummary(r.pr);let n=this.shouldSkipPr(e,r.pr);if(n){y.info(l.dim(`Skipping: ${n}`));return}if(r.packages.size===0)throw new g("No packages affected by this PR","The PR only modifies root files or files outside packages");let i=await this.determineBumpType(e,r.suggestedBump,r.pr.labels),s=await this.determinePackages(e,r.packages);if(s.length===0)throw new g("No packages selected");let{packages:a}=await O.scan({single:e.config.get("single")}),o=`[#${r.pr.number}](${r.pr.url})`,c=e.args.message??`${r.pr.title} (${o})`,p=r.pr.body||void 0,m=this.buildStoneData({allPackages:a,bump:i,commits:r.commits,description:p,message:c,packages:s});if(this.logPreview(m,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive){if(!await T({initialValue:!0,message:"Create this stone?"}))return}let f=await new I(e.config).create(m);q(`Run ${l.green(`${N} roll`)} to release packages
204
- or create another stone with ${l.green(`${N} version`)}`,`Stone ${l.bold(f.id)} ${l.green("created")}`)}displayPrSummary(e){if(y.info(`PR #${l.bold(String(e.number))}: ${e.title}`),y.info(`${l.dim("Author:")} ${e.author}`),y.info(`${l.dim("Branch:")} ${e.branch}`),e.labels.length>0)y.info(`${l.dim("Labels:")} ${e.labels.map((t)=>l.cyan(t)).join(", ")}`)}shouldSkipPr(e,t){let r=e.config.get("pr").skip;for(let n of t.labels)if(r.labels.some((i)=>i.toLowerCase()===n.toLowerCase()))return`label "${n}" is in skip list`;if(r.authors.some((n)=>n.toLowerCase()===t.author.toLowerCase()))return`author "${t.author}" is in skip list`;for(let n of r.titlePatterns)try{if(new RegExp(n,"i").test(t.title))return`title matches skip pattern "${n}"`}catch{y.warn(l.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${n}"`))}return null}async determineBumpType(e,t,r){if(e.args.bump){if(!Vs(e.args.bump))throw new g(`Invalid bump type: ${e.args.bump}`,"Use major, minor, or patch");return e.args.bump}if(t)return y.info(`${l.dim("Detected bump:")} ${l.bold(t)} (from ${this.getBumpSource(t,r,e)})`),t;if(e.args.yes)throw new g("Cannot determine bump type automatically","Add a label to the PR or use --bump to specify explicitly");if(!e.interactive)throw new g("Cannot determine bump type","Use --bump to specify explicitly");return Ge({message:"What type of change is this?",options:[{label:"patch - Bug fixes, minor changes",value:"patch"},{label:"minor - New features (backwards compatible)",value:"minor"},{label:"major - Breaking changes",value:"major"}]})}getBumpSource(e,t,r){let n=r.config.get("pr").labelMapping;for(let i of t){let s=i.toLowerCase();for(let[a,o]of Object.entries(n))if(s===a.toLowerCase()&&o===e)return`label: ${i}`}return"title"}async determinePackages(e,t){let r=Array.from(t);if(e.args.packages){let n=e.args.packages.split(",").map((s)=>s.trim()).filter(Boolean),i=n.filter((s)=>!t.has(s));if(i.length>0)throw new g(`Packages not affected by this PR: ${i.join(", ")}`,`Affected packages: ${r.join(", ")}`);return n}if(r.length===1||e.args.yes||!e.interactive)return y.info(`${l.dim("Affected packages:")} ${r.map((n)=>l.bold(n)).join(", ")}`),r;return ke({initialValues:r,message:"Select packages to include",options:r.map((n)=>({label:n,value:n})),required:!0})}buildStoneData(e){let{allPackages:t,bump:r,commits:n,description:i,message:s,packages:a}=e,o={commits:n,description:i,message:s};if(r==="major")o.major=a;else if(r==="minor")o.minor=a;else o.patch=a;return o.dependency=z(ot(a,t)),o}logPreview(e,t){let r=[];if(t)r.push(l.bold(l.yellow("[dry-run]")));if(r.push(`${l.dim("Stone:")} ${l.bold(e.message)}`),e.major?.length)r.push(` ${l.red("major")}: ${e.major.join(", ")}`);if(e.minor?.length)r.push(` ${l.yellow("minor")}: ${e.minor.join(", ")}`);if(e.patch?.length)r.push(` ${l.green("patch")}: ${e.patch.join(", ")}`);if(e.commits?.length)r.push(` ${l.dim(`${e.commits.length} commit(s)`)}`);if(e.description){let n=e.description.length>Eo?`${e.description.slice(0,Eo)}...`:e.description;r.push(` ${l.dim("Description:")} ${n}`)}y.step(r.join(`
205
- `))}}import{rm as Hg}from"fs/promises";import{dirname as _g,join as Io}from"path";var Lo=/\d{14}$/,Vg=B({abort:{default:!1,description:"Abandon the incomplete release if nothing external has started",type:"boolean"},changelog:{alias:"c",description:"Generate changelogs",type:"boolean"},createRelease:{alias:"r",description:"Create a release on git provider",type:"boolean"},dryRun:{alias:"d",description:"Preview without making changes",type:"boolean"},noCommit:{default:!1,description:"Skip creating release commit",type:"boolean"},npm:{alias:"n",description:"Publish to NPM",type:"boolean"},preview:{default:!1,description:"Preview changelogs then prompt to delete",type:"boolean"},publishOnly:{default:!1,description:"Publish from currentRelease (no file changes)",type:"boolean"},push:{alias:"p",description:"Push commits and tags to remote",type:"boolean"},resume:{default:!1,description:"Resume an incomplete release",type:"boolean"},tags:{alias:"t",description:"Create git tags",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class Ii extends j{name="roll";description="Execute a release from pending stones";args=Vg;async execute(e){if(this.validateModeFlags(e),e.args.abort){await this.executeAbort();return}if(e.args.resume){await this.executeResume(e);return}if(e.args.publishOnly){await this.executePublishOnly(e);return}await Ie.assertNoActiveRelease();let t=this.resolveOptions(e),n=await new I(e.config).list();if(n.length===0)throw new g("No pending stones found",`Create a stone with ${l.green(`${N} version`)} first`);let{packages:i}=await O.scan({single:e.config.get("single")}),s=A.mergeAll(n),a=Q.applyStone(s,i);if(a.length===0)throw new g("No packages to update","Stones don't reference any known packages");if(e.args.preview){await this.previewChangelogs(e,n,a);return}if(this.printPreview(s,a,t),!t.dryRun&&!e.args.yes&&process.stdout.isTTY){if(!await T({initialValue:!0,message:"Proceed with release?"}))return}if(t.dryRun){y.info(l.yellow("Dry run complete - no changes made"));return}await this.executeRelease(e,s,a,n,t)}async previewChangelogs(e,t,r){let n=e.config.get("changelog"),i=new _e(n),s=ne();s.start("Generating changelog preview..."),await i.generate(t,r),s.stop("Changelog preview generated");let a=r.map((c)=>l.dim(` ${Io(_g(c.file),n.filename)}`)).join(`
206
- `);if(y.info(`
191
+ After you finished, you can release it by running ${p.green(N)}${p.blue(" roll")}
192
+ `)}}var Ig=B({dryRun:{alias:"d",default:!1,description:"Preview migration without making changes",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class gi extends D{name="migrate";description="Migrate from changesets to sisyphus";args=Ig;parser=new an;async execute(e){if(!await this.parser.exists())throw new u("No .changeset directory found","This command migrates existing changesets to sisyphus stones");let{changesets:t,config:r}=await this.analyzeChangesets();if(this.displayPreview(t,r),e.args.dryRun){G("No changes made",p.yellow("Dry run"));return}let s=this.collectStoneData(t);if(!e.args.yes&&!await this.confirmMigration(t.length))return;let n=await this.createStones(e,s);await this.applyConfigMigration(e,r),this.displaySuccess(n)}async analyzeChangesets(){let e=ye();e.start("Analyzing changesets...");let t=await this.parser.parse();if(t.errors.length>0){e.error("Found issues while parsing");for(let r of t.errors)v.warn(p.yellow(r))}if(t.changesets.length===0)throw e.stop("No changesets found"),new u("No changeset files to migrate");return e.stop(`Found ${p.bold(String(t.changesets.length))} changeset(s)`),t}displayPreview(e,t){if(this.displayChangesets(e),t)this.displayConfigMapping(t)}async confirmMigration(e){return j({initialValue:!0,message:`Migrate ${e} changeset(s) to stones?`})}collectStoneData(e){let t=[],r=[];for(let s of e)try{t.push(this.parser.toStoneData(s))}catch(n){if(!(n instanceof u))throw n;r.push(n.message)}if(r.length>0)throw new u(`Cannot migrate changesets:
193
+ ${r.join(`
194
+ `)}`,"Rewrite them as major, minor, or patch before migrating; no stones were created");return t}async createStones(e,t){let r=ye();r.start("Creating stones...");let s=new E(e.config),n=[];for(let i of t){let o=await s.create(i);n.push(o.id)}return r.stop(`Created ${p.bold(String(n.length))} stone(s)`),n}async applyConfigMigration(e,t){if(!t)return;let r=ye();r.start("Migrating config..."),this.migrateConfig(e,t),r.stop("Config migrated")}displaySuccess(e){let t=e.map((r)=>` ${p.dim("-")} ${r}`).join(`
195
+ `);G(`${t}
196
+
197
+ Run ${p.green(`${N} stone list`)} to view stones
198
+ Run ${p.green(`${N} preview`)} to see what will be released`,p.green("Migration complete"))}displayChangesets(e){for(let t of e){let r=Object.entries(t.packages).map(([n,i])=>{let o=i==="major"?p.red:i==="minor"?p.yellow:p.green;return`${n} ${p.dim("(")}${o(i)}${p.dim(")")}`}).join(", "),s=t.summary.length>60?`${t.summary.slice(0,60)}...`:t.summary;v.info(`${p.dim(t.filename)}
199
+ ${p.dim("Packages:")} ${r}
200
+ ${p.dim("Message:")} ${s||p.dim("(empty)")}`)}}displayConfigMapping(e){let t=[{category:"migrate",check:()=>(e.ignore?.length??0)>0,format:()=>`ignore: ${e.ignore?.join(", ")}`},{category:"migrate",check:()=>e.commit===!0,format:()=>"commit: enabled (will enable commit & push)"},{category:"migrate",check:()=>e.access==="public",format:()=>"access: public (will enable npm publishing)"},{category:"migrate",check:()=>e.changelog===!1,format:()=>"changelog: disabled"},{category:"info",check:()=>!!e.baseBranch&&e.baseBranch!=="master",format:()=>`baseBranch: ${e.baseBranch}`},{category:"info",check:()=>!!e.updateInternalDependencies,format:()=>`updateInternalDependencies: ${e.updateInternalDependencies}`},{category:"info",check:()=>Array.isArray(e.changelog)||typeof e.changelog==="string",format:()=>`changelog: ${Array.isArray(e.changelog)?e.changelog[0]:e.changelog}`},{category:"info",check:()=>Array.isArray(e.commit)||typeof e.commit==="string",format:()=>`commit: ${Array.isArray(e.commit)?e.commit[0]:e.commit}`},{category:"unsupported",check:()=>(e.linked?.length??0)>0,format:()=>`linked: ${e.linked?.length} group(s)`},{category:"unsupported",check:()=>(e.fixed?.length??0)>0,format:()=>`fixed: ${e.fixed?.length} group(s)`}],r={info:{color:p.blue,items:[],title:"Info (not migrated)"},migrate:{color:p.green,items:[],title:"Will migrate"},unsupported:{color:p.yellow,items:[],title:"Not yet supported"}};for(let s of t)if(s.check())r[s.category].items.push(p.dim(s.format()));for(let s of[r.migrate,r.info,r.unsupported])if(s.items.length>0)G(s.items.join(`
201
+ `),s.color(s.title))}migrateConfig(e,t){if(t.ignore?.length){let r=e.config.get("ignore")??[],s=[...new Set([...r,...t.ignore])];e.config.set("ignore",s)}if(t.commit===!0){let r=e.config.get("commit")??{},s=e.config.get("release")??{};e.config.set("commit",{...r,author:r.author??"Sisyphus"}),e.config.set("release",{...s,push:!0})}if(t.access==="public"){let r=e.config.get("release")??{};e.config.set("release",{...r,npm:!0})}if(t.changelog===!1){let r=e.config.get("changelog")??{};e.config.set("changelog",{...r,generate:!1})}}}var Bc=100;function Ag(e,t){if(!e)return;let r=new Set(t),s=e.map((n)=>({...n,packages:n.packages.filter((i)=>r.has(i))})).filter((n)=>n.packages.length>0);return s.length>0?s:void 0}var Og=B({bump:{alias:"b",description:"Explicit bump type (major/minor/patch)",type:"string"},dryRun:{alias:"d",default:!1,description:"Preview without writing",type:"boolean"},message:{alias:"m",description:"Override stone message",type:"string"},packages:{alias:"p",description:"Filter packages (comma-separated)",type:"string"},url:{alias:"u",description:"PR URL",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmations",type:"boolean"}});class mi extends D{name="pr";description="Create a stone from a Pull Request";args=Og;prompts=!0;async execute(e){let r=await new gn(e.config).analyze(e.args.url);this.displayPrSummary(r.pr);let s=this.shouldSkipPr(e,r.pr);if(s){v.info(p.dim(`Skipping: ${s}`));return}if(r.packages.size===0)throw new u("No packages affected by this PR","The PR only modifies root files or files outside packages");let n=await this.determineBumpType(e,r.suggestedBump,r.pr.labels),i=await this.determinePackages(e,r.packages);if(i.length===0)throw new u("No packages selected");let o=e.config.get("ignore")??[];if(e.args.packages){let y=i.filter((R)=>ee(R,o));if(y.length>0)throw new u(`Packages are excluded by config.ignore: ${y.join(", ")}`,"Remove them from ignore before releasing them")}let a=i.filter((y)=>!ee(y,o));if(a.length===0){v.info(p.dim("Skipping: every affected package is excluded by config.ignore"));return}let{packages:c}=await F.scan({single:e.config.get("single")}),l=`[#${r.pr.number}](${r.pr.url})`,d=e.args.message??`${r.pr.title} (${l})`,g=r.pr.body||void 0,h=this.buildStoneData({allPackages:c,bump:n,commits:r.commits,dependents:ae(e.config),description:g,message:d,packages:a});if(this.logPreview(h,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive){if(!await j({initialValue:!0,message:"Create this stone?"}))return}let m=await new E(e.config).create(h);G(`Run ${p.green(`${N} roll`)} to release packages
202
+ or create another stone with ${p.green(`${N} version`)}`,`Stone ${p.bold(m.id)} ${p.green("created")}`)}displayPrSummary(e){if(v.info(`PR #${p.bold(String(e.number))}: ${e.title}`),v.info(`${p.dim("Author:")} ${e.author}`),v.info(`${p.dim("Branch:")} ${e.branch}`),e.labels.length>0)v.info(`${p.dim("Labels:")} ${e.labels.map((t)=>p.cyan(t)).join(", ")}`)}shouldSkipPr(e,t){let r=e.config.get("pr").skip;for(let s of t.labels)if(r.labels.some((n)=>n.toLowerCase()===s.toLowerCase()))return`label "${s}" is in skip list`;if(r.authors.some((s)=>s.toLowerCase()===t.author.toLowerCase()))return`author "${t.author}" is in skip list`;for(let s of r.titlePatterns)try{if(new RegExp(s,"i").test(t.title))return`title matches skip pattern "${s}"`}catch{v.warn(p.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${s}"`))}return null}async determineBumpType(e,t,r){if(e.args.bump){if(!_o(e.args.bump))throw new u(`Invalid bump type: ${e.args.bump}`,"Use major, minor, or patch");return e.args.bump}if(t)return v.info(`${p.dim("Detected bump:")} ${p.bold(t)} (from ${this.getBumpSource(t,r,e)})`),t;if(e.args.yes)throw new u("Cannot determine bump type automatically","Add a label to the PR or use --bump to specify explicitly");if(!e.interactive)throw new u("Cannot determine bump type","Use --bump to specify explicitly");return Ke({message:"What type of change is this?",options:[{label:"patch - Bug fixes, minor changes",value:"patch"},{label:"minor - New features (backwards compatible)",value:"minor"},{label:"major - Breaking changes",value:"major"}]})}getBumpSource(e,t,r){let s=r.config.get("pr").labelMapping;for(let n of t){let i=n.toLowerCase();for(let[o,a]of Object.entries(s))if(i===o.toLowerCase()&&a===e)return`label: ${n}`}return"title"}async determinePackages(e,t){let r=Array.from(t);if(e.args.packages){let s=e.args.packages.split(",").map((i)=>i.trim()).filter(Boolean),n=s.filter((i)=>!t.has(i));if(n.length>0)throw new u(`Packages not affected by this PR: ${n.join(", ")}`,`Affected packages: ${r.join(", ")}`);return s}if(r.length===1||e.args.yes||!e.interactive)return v.info(`${p.dim("Affected packages:")} ${r.map((s)=>p.bold(s)).join(", ")}`),r;return ke({initialValues:r,message:"Select packages to include",options:r.map((s)=>({label:s,value:s})),required:!0})}buildStoneData(e){let{allPackages:t,bump:r,commits:s,dependents:n,description:i,message:o,packages:a}=e,c={commits:Ag(s,a),description:i,message:o};if(r==="major")c.major=a;else if(r==="minor")c.minor=a;else c.patch=a;return c.dependency=Y(bt(a.map((l)=>({bump:r,name:l})),t,n)),c}logPreview(e,t){let r=[];if(t)r.push(p.bold(p.yellow("[dry-run]")));if(r.push(`${p.dim("Stone:")} ${p.bold(e.message)}`),e.major?.length)r.push(` ${p.red("major")}: ${e.major.join(", ")}`);if(e.minor?.length)r.push(` ${p.yellow("minor")}: ${e.minor.join(", ")}`);if(e.patch?.length)r.push(` ${p.green("patch")}: ${e.patch.join(", ")}`);if(e.commits?.length)r.push(` ${p.dim(`${e.commits.length} commit(s)`)}`);if(e.description){let s=e.description.length>Bc?`${e.description.slice(0,Bc)}...`:e.description;r.push(` ${p.dim("Description:")} ${s}`)}v.step(r.join(`
203
+ `))}}import{rm as Mg}from"fs/promises";import{dirname as Lg,join as Dg}from"path";var _g=1;function Fc(){let e=process.stdout.write.bind(process.stdout),t=console.log;return process.stdout.write=(r,...s)=>process.stderr.write(r,...s),console.log=(...r)=>console.error(...r),()=>{process.stdout.write=e,console.log=t}}function $s(e){if(e){let r=()=>{return};return{info:r,json:e,note:r,start:r,step:r,stop:r,warn:r}}let t=ye();return{info:(r)=>v.info(r),json:e,note:(r,s)=>G(r,s),start:(r)=>t.start(r),step:(r)=>v.step(r),stop:(r)=>t.stop(r),warn:(r)=>v.warn(r)}}function hi(e,t){t?.(),console.log(JSON.stringify(e,null,2))}function Uc(e,t,r){if(hi(e,r),console.error(t instanceof Error?t.message:String(t)),t instanceof u&&t.hint)console.error(t.hint);for(let s of e.error?.causes??[])console.error(s);process.exit(t instanceof u?t.exitCode:_g)}var Vc=/\d{14}$/,Ng="Pending stones reference only ignored packages",jg="--json requires --yes in an interactive terminal",Bg="Pass --yes to consent to the release, or use --dryRun to preview it",Gc=B({abort:{default:!1,description:"Abandon the incomplete release if nothing external has started",type:"boolean"},changelog:{alias:"c",description:"Generate changelogs",type:"boolean"},createRelease:{alias:"r",description:"Create a release on git provider",type:"boolean"},dryRun:{alias:"d",description:"Preview without making changes",type:"boolean"},json:{alias:"j",default:!1,description:"Output the release result as JSON",type:"boolean"},noCommit:{default:!1,description:"Skip creating release commit",type:"boolean"},npm:{alias:"n",description:"Publish to NPM",type:"boolean"},preview:{default:!1,description:"Preview changelogs then prompt to delete",type:"boolean"},publishOnly:{default:!1,description:"Publish from currentRelease (no file changes)",type:"boolean"},push:{alias:"p",description:"Push commits and tags to remote",type:"boolean"},resume:{default:!1,description:"Resume an incomplete release",type:"boolean"},tags:{alias:"t",description:"Create git tags",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class fi extends D{name="roll";description="Execute a release from pending stones";args=Gc;reportContext={mode:"release",npmTag:de,packages:[],stones:[]};restoreStdout;stdoutWasTTY=!1;warnings=[];async execute(e){if(this.stdoutWasTTY=process.stdout.isTTY===!0,!e.args.json){await this.run(e);return}let t=Fc();this.restoreStdout=t;try{await this.run(e),t()}catch(r){this.reportContext.ledger??=(await $e.loadActive().catch(()=>null))?.data,Uc(this.buildReport(e,"failed",{error:r}),r,t)}}buildReport(e,t,r={}){return Lc({ledger:this.reportContext.ledger??null,mode:this.reportContext.mode,npmTag:this.reportContext.npmTag,packages:this.reportContext.packages,releaseCommit:this.reportContext.releaseCommit,status:t,stones:this.reportContext.stones,tagsEnabled:this.reportContext.tagsEnabled??e.args.tags??e.config.get("release").tags,warnings:this.warnings,...r})}emit(e,t,r={}){if(!e.args.json)return;hi(this.buildReport(e,t,r),this.restoreStdout)}async run(e){if(Rr(e.args,Gc,"Run 'sis roll --help' for supported options"),this.validateModeFlags(e),e.args.abort){this.reportContext.mode="abort",await this.executeAbort(e);return}if(e.args.resume){this.reportContext.mode="resume",await this.executeResume(e);return}if(e.args.publishOnly){this.reportContext.mode="publish-only",await this.executePublishOnly(e);return}await Me.assertNoActiveRelease();let t=this.resolveOptions(e),s=await new E(e.config).list();if(s.length===0)throw new u("No pending stones found",`Create a stone with ${p.green(`${N} version`)} first`);let{packages:n}=await F.scan({single:e.config.get("single")}),i=e.config.get("ignore")??[],{skipped:o,stones:a}=bs(s,i);if(o.length>0)this.recordWarning(e,`Excluded by config.ignore: ${o.join(", ")}`);let c=A.mergeAll(a),l=ar(c,n,i);if(l.kind==="unknown-packages")throw new u(`Pending stones reference unknown packages: ${l.names.join(", ")}`,"Remove the stale stones or restore the packages before rolling");let d=this.planPackages(e,z.applyStone(c,n,ae(e.config).kinds)),g=t.dryRun?"dry-run":e.args.preview?"preview":"release";if(d.length===0){this.recordWarning(e,Ng),this.reportContext={mode:g,npmTag:de,packages:[],stones:s,tagsEnabled:t.tags},this.emit(e,"planned");return}if(this.reportContext={mode:g,npmTag:de,packages:d,stones:s,tagsEnabled:t.tags},this.reportContext.npmTag=this.resolveReportNpmTag(e,d,t.npm),e.args.preview){await this.previewChangelogs(e,s,d);return}let h=$s(e.args.json);if(this.printPreview(h,c,d,t),!t.dryRun&&!e.args.yes&&this.stdoutWasTTY){if(this.assertJsonConsent(e),!await j({initialValue:!0,message:"Proceed with release?"}))return}if(t.dryRun){h.info(p.yellow("Dry run complete - no changes made")),this.emit(e,"planned");return}await this.executeRelease(e,h,c,d,s,t)}planPackages(e,t){let{kept:r,skipped:s}=Yo(t,e.config.get("ignore")??[]);if(s.length>0)this.recordWarning(e,`Excluded by config.ignore: ${s.join(", ")}`);let{cycle:n,ordered:i}=Ut(r);if(n.length>0)this.recordWarning(e,`Dependency cycle between ${n.join(", ")}; publish order may not satisfy every pin`);return i}recordWarning(e,t){if(this.warnings.push(t),!e.args.json)v.warn(p.yellow(t))}assertJsonConsent(e){if(!e.args.json)return;throw new u(jg,Bg)}resolveReportNpmTag(e,t,r){if(!r)return de;try{return Jt(t,e.config.get("tag"))}catch(s){let n=es(e.config.get("tag"));return this.recordWarning(e,`Npm publication would fail: ${s instanceof Error?s.message:String(s)}`),n}}async previewChangelogs(e,t,r){let s=e.config.get("changelog"),n=new Qe(s),i=$s(e.args.json);i.start("Generating changelog preview..."),await n.generate(t,r),i.stop("Changelog preview generated");let o=r.map((c)=>Dg(Lg(c.file),s.filename));if(s.root)o.push(s.filename);if(i.info(`
207
204
  Preview files created:
208
- ${a}`),n.root)y.info(l.dim(` ${n.filename} (root)`));y.info("");let o;try{o=await T({initialValue:!0,message:"Revert changes?"})}catch(c){throw await i.rollback(),y.info(l.dim("Changes reverted")),c}if(o)await i.rollback(),y.info(l.dim("Changes reverted"));else y.info(l.yellow("Changes kept"))}resolveOptions(e){let t=e.config.get("release"),r=e.config.get("changelog"),n=!e.args.noCommit;if(!n){let s=[e.args.createRelease?"--createRelease":void 0,e.args.push?"--push":void 0,e.args.tags?"--tags":void 0].filter((a)=>a!==void 0);if(s.length>0)throw new g(`--noCommit cannot be combined with ${s.join(", ")}`,"Tags, pushes, and provider releases require the release commit")}let i={changelog:e.args.changelog??r.generate,commit:n,createRelease:n?e.args.createRelease??t.createRelease:!1,dryRun:e.args.dryRun??!1,npm:e.args.npm??t.npm,push:n?e.args.push??t.push:!1,tags:n?e.args.tags??t.tags:!1};if(i.createRelease&&(!i.tags||!i.push))throw new g("Provider releases require both git tags and a remote push","Enable --tags and --push so the provider cannot create an implicit tag");if(!i.commit&&i.npm)throw new g("Npm publication requires a release commit","Remove --noCommit so package artifacts are bound to committed source");return i}printPreview(e,t,r){let n=[];if(r.dryRun)n.push(l.bold(l.yellow("[dry-run]")));if(n.push(`${l.bold("Release:")} ${e.message}`),e.tag)n.push(`${l.dim("Tag:")} ${e.tag}`);n.push(""),n.push(l.bold("Packages:"));for(let i of t)n.push(` ${i.label}`);n.push(""),n.push(l.dim(`Changelog: ${r.changelog?"yes":"no"}`)),n.push(l.dim(`Git tags: ${r.tags?"yes":"no"}`)),n.push(l.dim(`NPM publish: ${r.npm?"yes":"no"}`)),n.push(l.dim(`Push to remote: ${r.push?"yes":"no"}`)),n.push(l.dim(`Create release: ${r.createRelease?"yes":"no"}`)),y.step(n.join(`
209
- `))}async executeRelease(e,t,r,n,i){let s=new Ie(e.config,i),a={...e.config.get("lastStone")},o=Io(De,rt),c=await Bun.file(o).exists()?await Bun.file(o).text():null,p=new I(e.config),m=new Map;for(let b of n){let d=p.getFilePath(b.id);if(await Bun.file(d).exists())m.set(d,await Bun.file(d).text())}let u=await this.getCurrentCommit();await s.preflight(r,n);let f=ne();try{if(await s.initializeExternalRelease(r,n,!1),f.start("Updating package versions..."),await s.updatePackageVersions(r),f.stop("Package versions updated"),i.changelog)f.start("Generating changelogs..."),await s.generateChangelogs(n,r),f.stop("Changelogs generated");if(await this.deleteStones(e,n),i.commit)f.start("Creating release commit..."),e.config.set("lastStone",{commit:u,date:new Date().toISOString()}),await s.createCommit(t,r,n),f.stop("Release commit created");if(i.tags)f.start("Creating git tags..."),await s.createGitTags(r),f.stop("Git tags created");if(await s.finalizeExternalRelease(r,n),i.npm)f.start("Preparing NPM packages..."),await s.prepareNpmPublish(r),f.stop("NPM packages prepared");if(await s.markExternalReleaseReady(),i.push)f.start("Pushing to remote..."),await s.pushRelease(),f.stop("Pushed to remote");if(i.npm)f.start("Publishing to NPM..."),await s.publishToNpm(r),f.stop("Published to NPM");if(i.createRelease)f.start("Creating release..."),await s.createGitRelease(n,r),f.stop("Release created");await s.completeRelease(),q(`Released ${l.bold(String(r.length))} package(s)
210
- Run ${l.green(`${N} check`)} to verify`,l.green("Release complete"))}catch(b){if(s.hasCrossedIrreversibleBoundary())throw f.stop("Release incomplete, local state preserved"),s.createIncompleteReleaseError(b);f.stop("Release failed, rolling back...");try{await s.rollback(!1)}catch(d){throw AggregateError([b,d],"Release failed and rollback could not be completed; local release state was preserved")}try{e.config.set("lastStone",a),await this.restoreStones(e,n);for(let[d,P]of m)await Bun.write(d,P);if(c===null)await Hg(o,{force:!0});else await Bun.write(o,c)}catch(d){throw AggregateError([b,d],"Release failed and local metadata could not be restored; local release state was preserved")}try{await s.removeReleaseLedger()}catch(d){throw AggregateError([b,d],"Release failed and the recovery ledger could not be removed; remove it before the next roll")}throw b}}async deleteStones(e,t){let r=new I(e.config);for(let n of t)await r.delete(n.id)}async restoreStones(e,t){let r=new I(e.config);for(let n of t)await r.save(n)}async getCurrentCommit(){try{return(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim()}catch{return""}}validateModeFlags(e){if(e.args.abort){let r=[e.args.changelog!==void 0?"--changelog":void 0,e.args.createRelease!==void 0?"--createRelease":void 0,e.args.dryRun!==void 0?"--dryRun":void 0,e.args.noCommit?"--noCommit":void 0,e.args.npm!==void 0?"--npm":void 0,e.args.preview?"--preview":void 0,e.args.publishOnly?"--publishOnly":void 0,e.args.push!==void 0?"--push":void 0,e.args.resume?"--resume":void 0,e.args.tags!==void 0?"--tags":void 0].filter((n)=>n!==void 0);if(r.length>0)throw new g(`--abort cannot be combined with ${r.join(", ")}`,"Abort only removes the recovery ledger of an incomplete release");return}if(e.args.resume){let r=[e.args.changelog!==void 0?"--changelog":void 0,e.args.createRelease!==void 0?"--createRelease":void 0,e.args.dryRun!==void 0?"--dryRun":void 0,e.args.noCommit?"--noCommit":void 0,e.args.npm!==void 0?"--npm":void 0,e.args.preview?"--preview":void 0,e.args.publishOnly?"--publishOnly":void 0,e.args.push!==void 0?"--push":void 0,e.args.tags!==void 0?"--tags":void 0].filter((n)=>n!==void 0);if(r.length>0)throw new g(`--resume cannot be combined with ${r.join(", ")}`,"Resume uses the operation settings recorded in the active release ledger");return}if(e.args.preview&&e.args.dryRun)throw new g("--preview cannot be combined with --dryRun","Preview writes changelog files and then offers to revert them");if(!e.args.publishOnly)return;let t=[e.args.changelog!==void 0?"--changelog":void 0,e.args.noCommit?"--noCommit":void 0,e.args.preview?"--preview":void 0,e.args.push!==void 0?"--push":void 0].filter((r)=>r!==void 0);if(t.length>0)throw new g(`--publishOnly cannot be combined with ${t.join(", ")}`,"Publish-only supports --createRelease, --dryRun, --npm, --tags, and --yes")}async executePublishOnly(e){await Ie.assertNoActiveRelease();let t=e.config.get("currentRelease");if(!t)throw new g("No currentRelease found in config","Run `sis actions release-pr` first to prepare a release");if(await Pr(e.config.get("sisyphusDir"))!==t.sourceHash)throw new g("Current checkout does not match the prepared release source","Recreate the release PR before publishing");let i=await new I(e.config).getReleasedStones(t.timestamp,t.stoneIds).catch((u)=>{throw new g(u instanceof Error?u.message:String(u),"Recreate the release PR before publishing")});if(i.length===0)throw new g("No archived stones found for currentRelease","Recreate the release PR before publishing");if(vr({packages:t.packages,sourceHash:t.sourceHash,stoneIds:t.stoneIds,timestamp:t.timestamp},i.map((u)=>u.toJson()))!==t.planHash)throw new g("Prepared release plan has changed","Recreate the release PR before publishing");let a=Object.entries(t.packages);if(a.length===0)throw new g("No packages in currentRelease","The release config appears to be empty");let{packages:o}=await O.scan({single:e.config.get("single")}),c=[];for(let[u,{oldVersion:f,newVersion:b}]of a){let d=o.get(u);if(!d)throw new g(`Package ${u} from currentRelease is missing from the workspace`);if(d.version!==b)throw new g(`Package ${u} is at ${d.version}, but currentRelease expects ${b}`,"Check out the exact release commit before publishing");c.push(d.withVersions(f,b))}this.validateArchivedPackagePlan(i,t.packages),y.info(l.bold("Publish-only mode")),y.info(l.dim(`Timestamp: ${t.timestamp}`)),y.info(l.dim(`Stones: ${t.stoneIds.join(", ")}`)),y.info(""),y.info(l.bold("Packages to publish:"));for(let u of c)y.info(` ${u.name}@${u.newVersion??u.version}`);y.info("");let p=e.config.get("release"),m={createRelease:e.args.createRelease??p.createRelease,dryRun:e.args.dryRun??!1,npm:e.args.npm??p.npm,tags:e.args.tags??p.tags};if(y.info(l.dim(`Operations: npm=${m.npm} tags=${m.tags} createRelease=${m.createRelease}`)),m.createRelease&&!m.tags)throw new g("Provider releases require pushed git tags","Enable --tags so the provider cannot create an implicit tag");if(!m.npm&&!m.tags&&!m.createRelease)throw new g("Nothing to publish: npm, tags, and provider release are all disabled","Enable --npm, --tags, or --createRelease");if(m.dryRun){y.info(l.yellow("[dry-run] Would publish packages"));return}if(!e.args.yes&&process.stdout.isTTY){if(!await T({initialValue:!0,message:"Proceed with publishing?"}))return}await this.executePublish(e,c,i,m)}async executePublish(e,t,r,n){let i=new Ie(e.config,{changelog:!1,createRelease:n.createRelease,dryRun:n.dryRun,npm:n.npm,push:!1,tags:n.tags}),s=ne();try{if(await i.initializeExternalRelease(t,r,!0),n.tags)s.start("Creating git tags..."),await i.createGitTags(t),s.stop("Git tags created");if(await i.finalizeExternalRelease(t,r),n.npm)s.start("Preparing NPM packages..."),await i.prepareNpmPublish(t),s.stop("NPM packages prepared");if(await i.markExternalReleaseReady(),n.tags)s.start("Pushing git tags..."),await i.pushRelease(),s.stop("Git tags pushed");if(n.npm)s.start("Publishing to NPM..."),await i.publishToNpm(t),s.stop("Published to NPM");if(n.createRelease)s.start("Creating release..."),await i.createGitRelease(r,t),s.stop("Release created");await i.completeRelease(),q(`Published ${l.bold(String(t.length))} package(s)
211
- Run ${l.green(`${N} check`)} to verify`,l.green("Publish complete"))}catch(a){if(i.hasCrossedIrreversibleBoundary())throw s.stop("Publish incomplete, local state preserved"),i.createIncompleteReleaseError(a);s.stop("Publish failed");try{await i.rollback()}catch(o){throw AggregateError([a,o],"Publish failed and rollback could not be completed; local release state was preserved")}throw a}}async executeAbort(){let e=await ye.loadActive();if(!e)throw new g("No incomplete release found","Nothing to abort");if(e.hasExternalProgress())throw new g(`Release ${e.id} already performed external operations`,`Run ${N} roll --resume to reconcile; aborting after a push or publish is not supported`);await e.remove(),y.warn("Release abandoned; version bumps, changelogs, the release commit, and local tags were kept")}async executeResume(e){let{packages:t}=await Ie.resume(e.config);q(`Released ${l.bold(String(t.length))} package(s)
212
- Run ${l.green(`${N} check`)} to verify`,l.green("Release resumed"))}validateArchivedPackagePlan(e,t){let r=A.mergeAll(e),n=Object.keys(t).sort(),i=[...new Set(r.allPackages)].sort();if(JSON.stringify(n)!==JSON.stringify(i))throw new g("Archived stones do not match currentRelease packages","Recreate the release PR before publishing");let s=new Map(Object.entries(t).map(([o,c])=>[o,new Q({file:`${o}/package.json`,name:o,version:c.oldVersion})])),a=Q.applyStone(r,s);for(let o of a){let c=t[o.name]?.newVersion,p=o.bump==="snapshot"?o.newVersion?.replace(Lo,""):o.newVersion,m=o.bump==="snapshot"?c?.replace(Lo,""):c;if(p!==m)throw new g(`Archived stones do not produce ${o.name}@${c??"missing"}`,"Recreate the release PR before publishing")}}}class Ze extends j{async resolveStone(e,t,r){if(r)return this.promptStone(t);if(!e)throw new g("Stone ID is required",`Usage: ${N} stone ${this.name} <id>`);let n=await t.get(e);if(!n)throw new g(`Stone '${e}' not found`,`Run '${N} stone list' to see available stones`);return n}async promptStone(e){let t=await e.list();if(t.length===0)throw new g("No pending stones found");let r=t.map((n)=>({label:`${n.id} - ${n.message}`,value:n}));return Ge({message:`Select a stone to ${this.name}`,options:r})}}var Wg=pe({id:{description:"Stone ID to delete"}});class Li extends Ze{name="delete";description="Delete a pending stone";positionals=Wg;prompts=!0;async execute(e){let t=new I(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive);if(e.interactive){if(!await T({initialValue:!1,message:`Delete stone '${r.id}'?`}))return}await t.delete(r.id),y.success(`Stone '${l.bold(r.id)}' deleted`)}}var Jg=pe({id:{description:"Stone ID to edit"}}),zg=B({message:{alias:"m",description:"New commit message",type:"string"}});class Ai extends Ze{name="edit";description="Edit a pending stone";positionals=Jg;args=zg;prompts=!0;async execute(e){let t=new I(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive),n=await this.resolveMessage(e,r.message),i=r.withMessage(n);await t.save(i),y.success(`Updated commit message for stone '${l.bold(r.id)}'`)}async resolveMessage(e,t){if(e.args.message)return e.args.message;if(!e.interactive)throw new g("--message is required in non-interactive mode");return ie({initialValue:t,message:"Commit message",placeholder:t})}}var Kg=B({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"},verbose:{alias:"v",default:!1,description:"Show detailed info",type:"boolean"}});class xi extends j{name="list";description="List all pending stones";args=Kg;async execute(e){let t=new I(e.config),r=await t.list();if(r.length===0){this.printEmpty(e.args.json);return}if(e.args.json)this.printJson(r,t);else this.printFormatted(r,e.args.verbose)}printEmpty(e){if(e)console.log(JSON.stringify([]));else y.info("No pending stones found")}printJson(e,t){let r=e.map((n)=>({path:t.getFilePath(n.id),...n.toJson()}));console.log(JSON.stringify(r,null,2))}printFormatted(e,t){let r=`Found ${l.bold(String(e.length))} pending stone${e.length>1?"s":""}`,n=e.map((i)=>this.formatStone(i,t)).join(`
213
-
214
- `);y.info(`${r}
215
-
216
- ${n}`)}formatStone(e,t){let r=[];if(r.push(`${l.dim("-")} ${l.bold(e.id)}`),r.push(` ${l.dim("Message:")} ${e.message}`),e.tag)r.push(` ${l.dim("Tag:")} ${l.cyan(e.tag)}`);if(e.major.length)r.push(` ${l.red("Major:")} ${e.major.join(", ")}`);if(e.minor.length)r.push(` ${l.yellow("Minor:")} ${e.minor.join(", ")}`);if(e.patch.length)r.push(` ${l.green("Patch:")} ${e.patch.join(", ")}`);if(t&&e.description){r.push(` ${l.dim("Description:")}`);for(let n of e.description.split(`
217
- `))r.push(` ${l.dim(n)}`)}return r.join(`
218
- `)}}var Yg=pe({ids:{description:"Stone IDs to merge (at least 2)",variadic:!0}}),Zg=B({delete:{alias:"d",default:!1,description:"Delete original stones after merge",type:"boolean"},message:{alias:"m",description:"Commit message for merged stone",type:"string"}});class Oi extends j{name="merge";description="Merge multiple stones into one";positionals=Yg;args=Zg;prompts=!0;async execute(e){let t=new I(e.config),r=await this.resolveStones(e,t),n=await this.resolveMessage(e),{stone:i,conflicts:s}=A.merge(r,n);if(await t.save(i),await this.resolveDelete(e))await t.deleteMany(r.map((o)=>o.id));this.printResult(i.id,s)}async resolveStones(e,t){let r=await t.list();if(r.length<2)throw new g("Need at least 2 stones to merge");if(e.interactive)return this.promptStones(r);let n=e.positionals.ids;if(n.length<2)throw new g("Need at least 2 stone IDs",`Usage: ${N} stone merge <id1> <id2> [...] -m "message"`);let i=r.filter((s)=>n.includes(s.id));if(i.length!==n.length){let s=i.map((o)=>o.id),a=n.filter((o)=>!s.includes(o));throw new g(`Stone(s) not found: ${a.join(", ")}`)}return i}async resolveMessage(e){if(e.args.message)return e.args.message;if(!e.interactive)throw new g("--message is required in non-interactive mode");return ie({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async resolveDelete(e){if(e.args.delete)return!0;if(e.interactive)return T({initialValue:!1,message:"Delete original stones?"});return!1}async promptStones(e){let t=e.map((n)=>({label:`${n.id} - ${n.message}`,value:n})),r=await ke({message:"Select stones to merge (at least 2)",options:t,required:!0});if(r.length<2)throw new g("Need to select at least 2 stones");return r}printResult(e,t){if(y.success(`Created merged stone: ${l.bold(e)}`),t.length>0)q(`Resolved ${t.length} package conflict(s) using highest bump type:
219
- `+t.map((r)=>` ${l.dim("-")} ${r}`).join(`
220
- `),l.yellow("Conflicts resolved"))}}var Xg=40,Qg=pe({id:{description:"Stone ID to display"}}),em=B({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class Mi extends Ze{name="show";description="Show details of a specific stone";positionals=Qg;args=em;prompts=!0;async execute(e){let t=new I(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive);this.printStone(r,t,e.args.json)}printStone(e,t,r){if(r)console.log(JSON.stringify({path:t.getFilePath(e.id),...e.toJson()},null,2));else this.printFormatted(e,t)}printFormatted(e,t){let r=[];if(r.push(l.bold(`Stone: ${e.id}`)),r.push(l.dim(`Path: ${t.getFilePath(e.id)}`)),r.push(l.dim("-".repeat(Xg))),r.push(""),r.push(`${l.dim("Message:")} ${e.message}`),e.tag)r.push(`${l.dim("Tag:")} ${l.cyan(e.tag)}`);if(e.description)r.push(`${l.dim("Description:")} ${e.description}`);r.push("");let n=[{bump:"major",packages:e.major},{bump:"minor",packages:e.minor},{bump:"patch",packages:e.patch},{bump:"dependency",packages:e.dependency},{bump:"snapshot",packages:e.snapshot}];for(let{bump:i,packages:s}of n)if(s.length>0){let a=at[i];r.push(`${a(i)}: ${s.join(", ")}`)}y.info(r.join(`
221
- `))}}class Di extends j{name="stone";description="Manage version stones";init(){this.registerSubcommands([new xi,new Mi,new Li,new Ai,new Oi])}}var tm=/^[A-Za-z][0-9A-Za-z]*$/,rm=pe({message:{description:"Stone message (commit message)"},description:{description:"Stone description (optional details)"}}),nm=B({all:{alias:"a",default:!1,description:"Select all (filtered) packages without prompting",type:"boolean"},bump:{alias:"b",description:"Bump type applied to all selected packages (major|minor|patch)",type:"string"},dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},filter:{alias:"f",description:"Filter packages by name",type:"string"},fromCommits:{default:!1,description:"Generate stones from conventional commits",type:"boolean"},major:{alias:"M",description:"Packages for major bump (comma-separated)",type:"string"},message:{description:"Stone message (skips the message prompt)",type:"string"},minor:{alias:"m",description:"Packages for minor bump (comma-separated)",type:"string"},patch:{alias:"p",description:"Packages for patch bump (comma-separated)",type:"string"},tag:{alias:"t",description:"Prerelease tag (e.g. beta, alpha)",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class Fi extends j{name="version";description="Create a new version stone";positionals=rm;args=nm;prompts=!0;async execute(e){let t=this.normalizeInput(e);if(this.validateFromCommitsInput(e,t),!e.args.fromCommits)this.validateManualSelectionInput(e,t);if(e.args.fromCommits)await this.executeFromCommits(e,t);else if(e.interactive&&!t.hasManualSelection)await this.executeInteractive(e,t);else await this.executeDirect(e,t)}normalizeInput(e){let t=e.args.major!==void 0||e.args.minor!==void 0||e.args.patch!==void 0,r={major:this.parsePackageList(e.args.major,"--major"),minor:this.parsePackageList(e.args.minor,"--minor"),patch:this.parsePackageList(e.args.patch,"--patch")};this.validateExclusiveBumpGroups(r);let n=e.positionals.message!==void 0,i=e.args.message!==void 0;if(n&&i)throw new g("Message cannot be provided both positionally and with --message");let s=n?e.positionals.message:e.args.message,a=this.normalizeNonEmptyValue(e.args.bump,"--bump"),o=this.normalizeNonEmptyValue(e.args.filter,"--filter");return{bump:a,description:e.positionals.description?.trim()||void 0,filter:o,hasManualSelection:a!==void 0||t||e.args.all,message:this.normalizeNonEmptyValue(s,"Message"),packageSelection:r,packageSelectionSupplied:t,tag:this.normalizeTag(e.args.tag)}}normalizeNonEmptyValue(e,t){if(e===void 0)return;let r=e.trim();if(!r)throw new g(`${t} cannot be empty`);return r}normalizeTag(e){let t=this.normalizeNonEmptyValue(e,"--tag");if(t===void 0)return;if(!tm.test(t))throw new g("--tag must be a supported prerelease identifier","Start with a letter and use only letters or numbers");return t}parsePackageList(e,t){if(e===void 0)return[];let r=e.split(",").map((n)=>n.trim());if(r.some((n)=>!n))throw new g(`${t} must contain one or more non-empty package names`);return[...new Set(r)]}validateExclusiveBumpGroups(e){let t=new Map,r=[["major",e.major],["minor",e.minor],["patch",e.patch]];for(let[n,i]of r)for(let s of i){let a=t.get(s);if(a)throw new g(`Package "${s}" cannot be assigned to both --${a} and --${n}`);t.set(s,n)}}validateFromCommitsInput(e,t){if(!e.args.fromCommits)return;if(!t.hasManualSelection&&t.message===void 0)return;throw new g("--from-commits cannot be combined with --bump, --all, --major, --minor, --patch, or a message")}validateManualSelectionInput(e,t){if(e.args.all&&t.bump===void 0)throw new g("--all requires a valid --bump","Use --bump major, --bump minor, or --bump patch");if(t.bump!==void 0&&t.packageSelectionSupplied)throw new g("--bump cannot be combined with --major, --minor, or --patch");if(t.bump!==void 0&&t.bump!=="major"&&t.bump!=="minor"&&t.bump!=="patch")throw new g(`Invalid bump type "${t.bump}"`,"Use major, minor, or patch")}async scanPackages(e,t){let r=await O.scan({filter:t,single:e.config.get("single")});if(r.packageNames.length===0)throw new g("No packages found matching the criteria");return r}async executeInteractive(e,t){let{packages:r,packageNames:n}=await this.scanPackages(e,t.filter),i=await this.selectPackagesInteractive(r,n),s=t.message??await this.promptMessage(),a=t.description??await this.promptDescription(),o=this.buildStoneData({description:a,message:s,packages:r,selection:i,tag:t.tag});await this.createStone(e,o,r)}async executeDirect(e,t){let r=t.message;if(!r)throw new g("Message is required in non-interactive mode",'Pass it as a positional or with --message "..."');let{packages:n,packageNames:i}=await this.scanPackages(e,t.filter),s=this.resolveSelection(e,t,i);this.validatePackages(s,n,i,t.filter);let a=this.buildStoneData({description:t.description,message:r,packages:n,selection:s,tag:t.tag});await this.createStone(e,a,n)}resolveSelection(e,t,r){let n=t.bump;if(!n)return this.requirePackageSelection(t.packageSelection);if(!e.args.all&&!e.args.yes)throw new g("--bump selects every (filtered) package","Confirm the selection with --all or --yes");let i=[...r];if(n==="major")return{major:i,minor:[],patch:[]};if(n==="minor")return{major:[],minor:i,patch:[]};return{major:[],minor:[],patch:i}}requirePackageSelection(e){if(!(e.major.length>0||e.minor.length>0||e.patch.length>0))throw new g("At least one of --major (-M), --minor (-m), or --patch (-p) is required","Or use --bump <type> with --all to select every package");return e}validatePackages(e,t,r,n){let i=[...e.major,...e.minor,...e.patch],s=i.filter((c)=>!t.has(c));if(s.length>0)throw new g(`Unknown packages: ${s.join(", ")}`);let a=new Set(r),o=i.filter((c)=>!a.has(c));if(o.length>0)throw new g(`Packages do not match --filter "${n}": ${o.join(", ")}`)}async executeFromCommits(e,t){if(!e.config.get("lastStone")?.commit)throw new g("No release baseline recorded",`Set lastStone.commit (run ${N} init in an existing repo, or complete one release) before using --fromCommits`);let n=await new Ve(e.config).analyze({filter:t.filter,single:e.config.get("single")});if(n.length===0){y.info("No conventional commits found since last release");return}let{packages:i}=await this.scanPackages(e,t.filter);y.info(`Found ${l.bold(String(n.length))} commit group(s) to process`);let s=new I(e.config),a=0;for(let o of n){let c=Ve.buildStoneData(o,i,t.tag);if(e.args.dryRun)this.logPreview(c,i,!0);else{let p=await s.create(c);a++,y.success(`Created stone: ${l.bold(p.id)}`)}}if(!e.args.dryRun&&a>0)q(`Created ${l.bold(String(a))} stone(s) from commits.
222
- Run ${l.green(`${N} check`)} to see what will be released.`,l.green("Success"))}async selectPackagesInteractive(e,t){let r=[],n={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let s=t.filter((o)=>!r.includes(o));if(s.length===0)break;let a=await this.promptPackages(i,s,e);if(r.push(...a),i==="major")n.major=a;else if(i==="minor")n.minor=a;else n.patch=a}if(r.length===0)throw new g("No packages selected");return n}async promptPackages(e,t,r){let n=at[e],i=t.map((s)=>{let a=r.get(s);return{label:a?a.withBump(e).label:s,value:s}});return ke({message:`Select packages for ${l.bold(n(e))} bump`,options:i,required:!1})}async promptMessage(){return(await ie({message:"Stone message (used as commit message)",placeholder:"feat: add new feature",validate:(t)=>t?.trim()?void 0:"Message is required"})).trim()}async promptDescription(){return(await ie({message:"Description (optional, press enter to skip)",placeholder:"Additional details about this change..."}))?.trim()||void 0}buildStoneData(e){let{selection:t,message:r,packages:n,tag:i,description:s}=e,a=[...t.major,...t.minor,...t.patch],o=ot(a,n);return{dependency:z(o),description:s,major:z(t.major),message:r,minor:z(t.minor),patch:z(t.patch),tag:i}}async createStone(e,t,r){let n=new I(e.config);if(this.logPreview(t,r,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive&&process.stdout.isTTY){if(!await T({initialValue:!0,message:"Create this stone?"}))return}let i=await n.create(t);q(`Run ${l.green(`${N} roll`)} to release packages
223
- or create another stone with ${l.green(`${N} version`)}`,`Stone ${l.bold(i.id)} ${l.green("created")}`)}logPreview(e,t,r){let n=[];if(r)n.push(l.bold(l.yellow("[dry-run]")));if(n.push(`${l.dim("Stone:")} ${l.bold(e.message)}`),e.tag)n.push(`${l.dim("Tag:")} ${e.tag}`);let i=[{bump:"major",names:e.major},{bump:"minor",names:e.minor},{bump:"patch",names:e.patch},{bump:"dependency",names:e.dependency}];for(let{bump:s,names:a}of i){if(!a?.length)continue;for(let o of a){let c=t.get(o);if(c)n.push(` ${c.withBump(s,e.tag).label}`)}}y.step(n.join(`
224
- `))}}class Ao extends dn{constructor(){super(new fn(`${De}/${rt}`,nt),{bin:N,clearOnStart:!0,exitLabel:"Give Up",goodbyeMessage:"The boulder rolls back down...",name:"SISYPHUS",promptMessage:"Choose your boulder:",version:xs})}init(){this.registerCommands([new ki,new $i,new Ci,new Si,new Ei,new Ii,new Di,new Fi])}}var im=new Ao;im.run();
205
+ ${o.map((c)=>p.dim(` ${c}`)).join(`
206
+ `)}`),i.info(""),await this.resolvePreviewRevert(e,n,i))await n.rollback(),i.info(p.dim("Changes reverted"));else i.info(p.yellow("Changes kept"));this.emit(e,"previewed",{changelogFiles:o})}async resolvePreviewRevert(e,t,r){if(e.args.json)return!0;try{return await j({initialValue:!0,message:"Revert changes?"})}catch(s){throw await t.rollback(),r.info(p.dim("Changes reverted")),s}}resolveOptions(e){let t=e.config.get("release"),r=e.config.get("changelog"),s=!e.args.noCommit;if(!s){let i=[e.args.createRelease?"--createRelease":void 0,e.args.push?"--push":void 0,e.args.tags?"--tags":void 0].filter((o)=>o!==void 0);if(i.length>0)throw new u(`--noCommit cannot be combined with ${i.join(", ")}`,"Tags, pushes, and provider releases require the release commit")}let n={changelog:e.args.changelog??r.generate,commit:s,createRelease:s?e.args.createRelease??t.createRelease:!1,dryRun:e.args.dryRun??!1,npm:e.args.npm??t.npm,push:s?e.args.push??t.push:!1,tags:s?e.args.tags??t.tags:!1};if(n.createRelease&&(!n.tags||!n.push))throw new u("Provider releases require both git tags and a remote push","Enable --tags and --push so the provider cannot create an implicit tag");if(!n.commit&&n.npm)throw new u("Npm publication requires a release commit","Remove --noCommit so package artifacts are bound to committed source");return n}printPreview(e,t,r,s){let n=[];if(s.dryRun)n.push(p.bold(p.yellow("[dry-run]")));if(n.push(`${p.bold("Release:")} ${t.message}`),t.tag)n.push(`${p.dim("Tag:")} ${t.tag}`);n.push(""),n.push(p.bold("Packages:"));for(let i of r)n.push(` ${i.label}`);n.push(""),n.push(p.dim(`Changelog: ${s.changelog?"yes":"no"}`)),n.push(p.dim(`Git tags: ${s.tags?"yes":"no"}`)),n.push(p.dim(`NPM publish: ${s.npm?"yes":"no"}`)),n.push(p.dim(`Push to remote: ${s.push?"yes":"no"}`)),n.push(p.dim(`Create release: ${s.createRelease?"yes":"no"}`)),e.step(n.join(`
207
+ `))}async executeRelease(e,t,r,s,n,i){let o=new Me(e.config,i),a={...e.config.get("lastStone")},c=e.config.path,l=await Bun.file(c).exists()?await Bun.file(c).text():null,d=new E(e.config),g=new Map;for(let m of n){let y=d.getFilePath(m.id);if(await Bun.file(y).exists())g.set(y,await Bun.file(y).text())}let h=await this.getCurrentCommit();await o.preflight(s,n);let f=t;try{if(await o.initializeExternalRelease(s,n,!1),this.reportContext.ledger=o.getLedgerSnapshot()??void 0,f.start("Updating package versions..."),await o.updatePackageVersions(s),f.stop("Package versions updated"),i.changelog)f.start("Generating changelogs..."),await o.generateChangelogs(n,s),f.stop("Changelogs generated");if(await this.deleteStones(e,n),i.commit)f.start("Creating release commit..."),e.config.set("lastStone",{commit:h,date:new Date().toISOString()}),await o.createCommit(r,s,n),this.reportContext.releaseCommit=await this.getCurrentCommit(),f.stop("Release commit created");if(i.tags)f.start("Creating git tags..."),await o.createGitTags(s),f.stop("Git tags created");if(await o.finalizeExternalRelease(s,n),i.npm)f.start("Preparing NPM packages..."),await o.prepareNpmPublish(s),f.stop("NPM packages prepared");if(await o.markExternalReleaseReady(),i.push)f.start("Pushing to remote..."),await o.pushRelease(),f.stop("Pushed to remote");if(i.npm)f.start("Publishing to NPM..."),await o.publishToNpm(s),f.stop("Published to NPM");if(i.createRelease)f.start("Creating release..."),await o.createGitRelease(n,s),f.stop("Release created");await o.completeRelease(),this.reportContext.ledger=o.getLedgerSnapshot()??this.reportContext.ledger,f.note(`Released ${p.bold(String(s.length))} package(s)
208
+ Run ${p.green(`${N} check`)} to verify`,p.green("Release complete")),this.emit(e,"completed")}catch(m){if(this.reportContext.ledger=o.getLedgerSnapshot()??this.reportContext.ledger,o.hasCrossedIrreversibleBoundary())throw f.stop("Release incomplete, local state preserved"),o.createIncompleteReleaseError(m);f.stop("Release failed, rolling back...");try{await o.rollback(!1)}catch(y){throw AggregateError([m,y],"Release failed and rollback could not be completed; local release state was preserved")}try{e.config.set("lastStone",a),await this.restoreStones(e,n);for(let[y,R]of g)await Bun.write(y,R);if(l===null)await Mg(c,{force:!0});else await Bun.write(c,l)}catch(y){throw AggregateError([m,y],"Release failed and local metadata could not be restored; local release state was preserved")}try{await o.removeReleaseLedger()}catch(y){throw AggregateError([m,y],"Release failed and the recovery ledger could not be removed; remove it before the next roll")}throw m}}async deleteStones(e,t){let r=new E(e.config);for(let s of t)await r.delete(s.id)}async restoreStones(e,t){let r=new E(e.config);for(let s of t)await r.save(s)}async getCurrentCommit(){try{return(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim()}catch{return""}}validateModeFlags(e){if(e.args.abort){let r=[e.args.changelog!==void 0?"--changelog":void 0,e.args.createRelease!==void 0?"--createRelease":void 0,e.args.dryRun!==void 0?"--dryRun":void 0,e.args.noCommit?"--noCommit":void 0,e.args.npm!==void 0?"--npm":void 0,e.args.preview?"--preview":void 0,e.args.publishOnly?"--publishOnly":void 0,e.args.push!==void 0?"--push":void 0,e.args.resume?"--resume":void 0,e.args.tags!==void 0?"--tags":void 0].filter((s)=>s!==void 0);if(r.length>0)throw new u(`--abort cannot be combined with ${r.join(", ")}`,"Abort only removes the recovery ledger of an incomplete release");return}if(e.args.resume){let r=[e.args.changelog!==void 0?"--changelog":void 0,e.args.createRelease!==void 0?"--createRelease":void 0,e.args.dryRun!==void 0?"--dryRun":void 0,e.args.noCommit?"--noCommit":void 0,e.args.npm!==void 0?"--npm":void 0,e.args.preview?"--preview":void 0,e.args.publishOnly?"--publishOnly":void 0,e.args.push!==void 0?"--push":void 0,e.args.tags!==void 0?"--tags":void 0].filter((s)=>s!==void 0);if(r.length>0)throw new u(`--resume cannot be combined with ${r.join(", ")}`,"Resume uses the operation settings recorded in the active release ledger");return}if(e.args.preview&&e.args.dryRun)throw new u("--preview cannot be combined with --dryRun","Preview writes changelog files and then offers to revert them");if(!e.args.publishOnly)return;let t=[e.args.changelog!==void 0?"--changelog":void 0,e.args.noCommit?"--noCommit":void 0,e.args.preview?"--preview":void 0,e.args.push!==void 0?"--push":void 0].filter((r)=>r!==void 0);if(t.length>0)throw new u(`--publishOnly cannot be combined with ${t.join(", ")}`,"Publish-only supports --createRelease, --dryRun, --npm, --tags, and --yes")}async executePublishOnly(e){await Me.assertNoActiveRelease();let t=e.config.get("currentRelease");if(!t)throw new u("No currentRelease found in config","Run `sis actions release-pr` first to prepare a release");if(await qr(e.config.get("sisyphusDir"))!==t.sourceHash)throw new u("Current checkout does not match the prepared release source","Recreate the release PR before publishing");let n=await new E(e.config).getReleasedStones(t.timestamp,t.stoneIds).catch((m)=>{throw new u(m instanceof Error?m.message:String(m),"Recreate the release PR before publishing")});if(n.length===0)throw new u("No archived stones found for currentRelease","Recreate the release PR before publishing");if(Wr({packages:t.packages,sourceHash:t.sourceHash,stoneIds:t.stoneIds,timestamp:t.timestamp},n.map((m)=>m.toJson()))!==t.planHash)throw new u("Prepared release plan has changed","Recreate the release PR before publishing");let o=Object.entries(t.packages);if(o.length===0)throw new u("No packages in currentRelease","The release config appears to be empty");let{packages:a}=await F.scan({single:e.config.get("single")}),c=[];for(let[m,{oldVersion:y,newVersion:R}]of o){let S=a.get(m);if(!S)throw new u(`Package ${m} from currentRelease is missing from the workspace`);if(S.version!==R)throw new u(`Package ${m} is at ${S.version}, but currentRelease expects ${R}`,"Check out the exact release commit before publishing");c.push(S.withVersions(y,R))}this.validateArchivedPackagePlan(e,n,t.packages,c);let l=$s(e.args.json),{cycle:d,ordered:g}=Ut(c);if(d.length>0)this.recordWarning(e,`Dependency cycle between ${d.join(", ")}; publish order may not satisfy every pin`);l.info(p.bold("Publish-only mode")),l.info(p.dim(`Timestamp: ${t.timestamp}`)),l.info(p.dim(`Stones: ${t.stoneIds.join(", ")}`)),l.info(""),l.info(p.bold("Packages to publish:"));for(let m of g)l.info(` ${m.name}@${m.newVersion??m.version}`);l.info("");let h=e.config.get("release"),f={createRelease:e.args.createRelease??h.createRelease,dryRun:e.args.dryRun??!1,npm:e.args.npm??h.npm,tags:e.args.tags??h.tags};if(l.info(p.dim(`Operations: npm=${f.npm} tags=${f.tags} createRelease=${f.createRelease}`)),this.reportContext={mode:"publish-only",npmTag:de,packages:g,stones:n,tagsEnabled:f.tags},this.reportContext.npmTag=this.resolveReportNpmTag(e,g,f.npm),f.createRelease&&!f.tags)throw new u("Provider releases require pushed git tags","Enable --tags so the provider cannot create an implicit tag");if(!f.npm&&!f.tags&&!f.createRelease)throw new u("Nothing to publish: npm, tags, and provider release are all disabled","Enable --npm, --tags, or --createRelease");if(f.dryRun){l.info(p.yellow("[dry-run] Would publish packages")),this.emit(e,"planned");return}if(!e.args.yes&&this.stdoutWasTTY){if(this.assertJsonConsent(e),!await j({initialValue:!0,message:"Proceed with publishing?"}))return}await this.executePublish(e,l,g,n,f)}async executePublish(e,t,r,s,n){let i=new Me(e.config,{changelog:!1,createRelease:n.createRelease,dryRun:n.dryRun,npm:n.npm,push:!1,tags:n.tags}),o=t;try{if(await i.initializeExternalRelease(r,s,!0),this.reportContext.ledger=i.getLedgerSnapshot()??void 0,n.tags)o.start("Creating git tags..."),await i.createGitTags(r),o.stop("Git tags created");if(await i.finalizeExternalRelease(r,s),n.npm)o.start("Preparing NPM packages..."),await i.prepareNpmPublish(r),o.stop("NPM packages prepared");if(await i.markExternalReleaseReady(),n.tags)o.start("Pushing git tags..."),await i.pushRelease(),o.stop("Git tags pushed");if(n.npm)o.start("Publishing to NPM..."),await i.publishToNpm(r),o.stop("Published to NPM");if(n.createRelease)o.start("Creating release..."),await i.createGitRelease(s,r),o.stop("Release created");await i.completeRelease(),this.reportContext.ledger=i.getLedgerSnapshot()??this.reportContext.ledger,o.note(`Published ${p.bold(String(r.length))} package(s)
209
+ Run ${p.green(`${N} check`)} to verify`,p.green("Publish complete")),this.emit(e,"completed")}catch(a){if(this.reportContext.ledger=i.getLedgerSnapshot()??this.reportContext.ledger,i.hasCrossedIrreversibleBoundary())throw o.stop("Publish incomplete, local state preserved"),i.createIncompleteReleaseError(a);o.stop("Publish failed");try{await i.rollback()}catch(c){throw AggregateError([a,c],"Publish failed and rollback could not be completed; local release state was preserved")}throw a}}async executeAbort(e){let t=await $e.loadActive();if(!t)throw new u("No incomplete release found","Nothing to abort");if(t.hasExternalProgress())throw new u(`Release ${t.id} already performed external operations`,`Run ${N} roll --resume to reconcile; aborting after a push or publish is not supported`);if(this.reportContext={ledger:t.data,mode:"abort",npmTag:de,packages:[],stones:[]},await t.remove(),!e.args.json)v.warn("Release abandoned; version bumps, changelogs, the release commit, and local tags were kept");this.emit(e,"aborted")}async executeResume(e){let{ledger:t,packages:r,stones:s}=await Me.resume(e.config);if(this.reportContext={ledger:t??void 0,mode:"resume",npmTag:t?.options.npmTag??de,packages:r,stones:s,tagsEnabled:t?.options.tags??!1},!e.args.json)G(`Released ${p.bold(String(r.length))} package(s)
210
+ Run ${p.green(`${N} check`)} to verify`,p.green("Release resumed"));this.emit(e,"completed")}validateArchivedPackagePlan(e,t,r,s){let n=A.mergeAll(t),i=Object.keys(r).sort(),o=[...new Set(n.allPackages)].sort();if(JSON.stringify(i)!==JSON.stringify(o))throw new u("Archived stones do not match currentRelease packages","Recreate the release PR before publishing");let a=z.applyStone(n,new Map(s.map((c)=>[c.name,c])),ae(e.config).kinds);for(let c of a){let l=r[c.name]?.newVersion,d=c.bump==="snapshot"?c.newVersion?.replace(Vc,""):c.newVersion,g=c.bump==="snapshot"?l?.replace(Vc,""):l;if(d!==g)throw new u(`Archived stones do not produce ${c.name}@${l??"missing"}`,"Recreate the release PR before publishing")}}}class it extends D{async resolveStone(e,t,r){if(r)return this.promptStone(t);if(!e)throw new u("Stone ID is required",`Usage: ${N} stone ${this.name} <id>`);let s=await t.get(e);if(!s)throw new u(`Stone '${e}' not found`,`Run '${N} stone list' to see available stones`);return s}async promptStone(e){let t=await e.list();if(t.length===0)throw new u("No pending stones found");let r=t.map((s)=>({label:`${s.id} - ${s.message}`,value:s}));return Ke({message:`Select a stone to ${this.name}`,options:r})}}var Fg=pe({id:{description:"Stone ID to delete"}});class yi extends it{name="delete";description="Delete a pending stone";positionals=Fg;prompts=!0;async execute(e){let t=new E(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive);if(e.interactive){if(!await j({initialValue:!1,message:`Delete stone '${r.id}'?`}))return}await t.delete(r.id),v.success(`Stone '${p.bold(r.id)}' deleted`)}}var Ug=pe({id:{description:"Stone ID to edit"}}),Vg=B({message:{alias:"m",description:"New commit message",type:"string"}});class wi extends it{name="edit";description="Edit a pending stone";positionals=Ug;args=Vg;prompts=!0;async execute(e){let t=new E(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive),s=await this.resolveMessage(e,r.message),n=r.withMessage(s);await t.save(n),v.success(`Updated commit message for stone '${p.bold(r.id)}'`)}async resolveMessage(e,t){if(e.args.message)return e.args.message;if(!e.interactive)throw new u("--message is required in non-interactive mode");return ce({initialValue:t,message:"Commit message",placeholder:t})}}var Gg=B({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"},verbose:{alias:"v",default:!1,description:"Show detailed info",type:"boolean"}});class bi extends D{name="list";description="List all pending stones";args=Gg;async execute(e){let t=new E(e.config),r=await t.list();if(r.length===0){this.printEmpty(e.args.json);return}if(e.args.json)this.printJson(r,t);else this.printFormatted(r,e.args.verbose)}printEmpty(e){if(e)console.log(JSON.stringify([]));else v.info("No pending stones found")}printJson(e,t){let r=e.map((s)=>({path:t.getFilePath(s.id),...s.toJson()}));console.log(JSON.stringify(r,null,2))}printFormatted(e,t){let r=`Found ${p.bold(String(e.length))} pending stone${e.length>1?"s":""}`,s=e.map((n)=>this.formatStone(n,t)).join(`
211
+
212
+ `);v.info(`${r}
213
+
214
+ ${s}`)}formatStone(e,t){let r=[];if(r.push(`${p.dim("-")} ${p.bold(e.id)}`),r.push(` ${p.dim("Message:")} ${e.message}`),e.tag)r.push(` ${p.dim("Tag:")} ${p.cyan(e.tag)}`);if(e.major.length)r.push(` ${p.red("Major:")} ${e.major.join(", ")}`);if(e.minor.length)r.push(` ${p.yellow("Minor:")} ${e.minor.join(", ")}`);if(e.patch.length)r.push(` ${p.green("Patch:")} ${e.patch.join(", ")}`);if(t&&e.description){r.push(` ${p.dim("Description:")}`);for(let s of e.description.split(`
215
+ `))r.push(` ${p.dim(s)}`)}return r.join(`
216
+ `)}}var Hg=pe({ids:{description:"Stone IDs to merge (at least 2)",variadic:!0}}),qg=B({delete:{alias:"d",default:!1,description:"Delete original stones after merge",type:"boolean"},message:{alias:"m",description:"Commit message for merged stone",type:"string"}});class vi extends D{name="merge";description="Merge multiple stones into one";positionals=Hg;args=qg;prompts=!0;async execute(e){let t=new E(e.config),r=await this.resolveStones(e,t),s=await this.resolveMessage(e),{stone:n,conflicts:i,errors:o}=A.merge(r,s);if(o.length>0)throw new u("Selected stones cannot be merged",o.join(`
217
+ `));if(await t.save(n),await this.resolveDelete(e))await t.deleteMany(r.map((c)=>c.id));this.printResult(n.id,i)}async resolveStones(e,t){let r=await t.list();if(r.length<2)throw new u("Need at least 2 stones to merge");if(e.interactive)return this.promptStones(r);let s=e.positionals.ids;if(s.length<2)throw new u("Need at least 2 stone IDs",`Usage: ${N} stone merge <id1> <id2> [...] -m "message"`);let n=r.filter((i)=>s.includes(i.id));if(n.length!==s.length){let i=n.map((a)=>a.id),o=s.filter((a)=>!i.includes(a));throw new u(`Stone(s) not found: ${o.join(", ")}`)}return n}async resolveMessage(e){if(e.args.message)return e.args.message;if(!e.interactive)throw new u("--message is required in non-interactive mode");return ce({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async resolveDelete(e){if(e.args.delete)return!0;if(e.interactive)return j({initialValue:!1,message:"Delete original stones?"});return!1}async promptStones(e){let t=e.map((s)=>({label:`${s.id} - ${s.message}`,value:s})),r=await ke({message:"Select stones to merge (at least 2)",options:t,required:!0});if(r.length<2)throw new u("Need to select at least 2 stones");return r}printResult(e,t){if(v.success(`Created merged stone: ${p.bold(e)}`),t.length>0)G(`Resolved ${t.length} package conflict(s) using highest bump type:
218
+ `+t.map((r)=>` ${p.dim("-")} ${r}`).join(`
219
+ `),p.yellow("Conflicts resolved"))}}var Wg=40,Jg=pe({id:{description:"Stone ID to display"}}),zg=B({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class $i extends it{name="show";description="Show details of a specific stone";positionals=Jg;args=zg;prompts=!0;async execute(e){let t=new E(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive);this.printStone(r,t,e.args.json)}printStone(e,t,r){if(r)console.log(JSON.stringify({path:t.getFilePath(e.id),...e.toJson()},null,2));else this.printFormatted(e,t)}printFormatted(e,t){let r=[];if(r.push(p.bold(`Stone: ${e.id}`)),r.push(p.dim(`Path: ${t.getFilePath(e.id)}`)),r.push(p.dim("-".repeat(Wg))),r.push(""),r.push(`${p.dim("Message:")} ${e.message}`),e.tag)r.push(`${p.dim("Tag:")} ${p.cyan(e.tag)}`);if(e.description)r.push(`${p.dim("Description:")} ${e.description}`);r.push("");let s=[{bump:"major",packages:e.major},{bump:"minor",packages:e.minor},{bump:"patch",packages:e.patch},{bump:"dependency",packages:e.dependency},{bump:"snapshot",packages:e.snapshot}];for(let{bump:n,packages:i}of s)if(i.length>0){let o=yt[n];r.push(`${o(n)}: ${i.join(", ")}`)}v.info(r.join(`
220
+ `))}}class Pi extends D{name="stone";description="Manage version stones";init(){this.registerSubcommands([new bi,new $i,new yi,new wi,new vi])}}var Kg=pe({message:{description:"Stone message (commit message)"},description:{description:"Stone description (optional details)"}}),Yg=B({all:{alias:"a",default:!1,description:"Select all (filtered) packages without prompting",type:"boolean"},bump:{alias:"b",description:"Bump type applied to all selected packages (major|minor|patch)",type:"string"},dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},filter:{alias:"f",description:"Filter packages by name",type:"string"},fromCommits:{default:!1,description:"Generate stones from conventional commits",type:"boolean"},major:{alias:"M",description:"Packages for major bump (comma-separated)",type:"string"},message:{description:"Stone message (skips the message prompt)",type:"string"},minor:{alias:"m",description:"Packages for minor bump (comma-separated)",type:"string"},patch:{alias:"p",description:"Packages for patch bump (comma-separated)",type:"string"},tag:{alias:"t",description:"Prerelease tag (e.g. beta, alpha)",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class Ri extends D{name="version";description="Create a new version stone";positionals=Kg;args=Yg;prompts=!0;async execute(e){let t=this.normalizeInput(e);if(this.validateFromCommitsInput(e,t),!e.args.fromCommits)this.validateManualSelectionInput(e,t);if(e.args.fromCommits)await this.executeFromCommits(e,t);else if(this.isInteractiveSession(e)&&!t.hasManualSelection)await this.executeInteractive(e,t);else await this.executeDirect(e,t)}isInteractiveSession(e){return e.interactive&&process.stdout.isTTY===!0}normalizeInput(e){let t=e.args.major!==void 0||e.args.minor!==void 0||e.args.patch!==void 0,r={major:this.parsePackageList(e.args.major,"--major"),minor:this.parsePackageList(e.args.minor,"--minor"),patch:this.parsePackageList(e.args.patch,"--patch")};this.validateExclusiveBumpGroups(r);let s=e.positionals.message!==void 0,n=e.args.message!==void 0;if(s&&n)throw new u("Message cannot be provided both positionally and with --message");let i=s?e.positionals.message:e.args.message,o=this.normalizeNonEmptyValue(e.args.bump,"--bump"),a=this.normalizeNonEmptyValue(e.args.filter,"--filter");return{bump:o,description:e.positionals.description?.trim()||void 0,filter:a,hasManualSelection:o!==void 0||t||e.args.all,message:this.normalizeNonEmptyValue(i,"Message"),packageSelection:r,packageSelectionSupplied:t,tag:this.normalizeTag(e.args.tag)}}normalizeNonEmptyValue(e,t){if(e===void 0)return;let r=e.trim();if(!r)throw new u(`${t} cannot be empty`);return r}normalizeTag(e){let t=this.normalizeNonEmptyValue(e,"--tag");if(t===void 0)return;return Ze(t,"--tag must be a supported prerelease identifier")}parsePackageList(e,t){if(e===void 0)return[];let r=e.split(",").map((s)=>s.trim());if(r.some((s)=>!s))throw new u(`${t} must contain one or more non-empty package names`);return[...new Set(r)]}validateExclusiveBumpGroups(e){let t=new Map,r=[["major",e.major],["minor",e.minor],["patch",e.patch]];for(let[s,n]of r)for(let i of n){let o=t.get(i);if(o)throw new u(`Package "${i}" cannot be assigned to both --${o} and --${s}`);t.set(i,s)}}validateFromCommitsInput(e,t){if(!e.args.fromCommits)return;if(!t.hasManualSelection&&t.message===void 0)return;throw new u("--fromCommits cannot be combined with --bump, --all, --major, --minor, --patch, or a message")}validateManualSelectionInput(e,t){if(e.args.all&&t.bump===void 0)throw new u("--all requires a valid --bump","Use --bump major, --bump minor, or --bump patch");if(t.bump!==void 0&&t.packageSelectionSupplied)throw new u("--bump cannot be combined with --major, --minor, or --patch");if(t.bump!==void 0&&t.bump!=="major"&&t.bump!=="minor"&&t.bump!=="patch")throw new u(`Invalid bump type "${t.bump}"`,"Use major, minor, or patch")}async scanPackages(e,t){let r=await F.scan({filter:t,single:e.config.get("single")}),s=e.config.get("ignore")??[],n=r.packageNames.filter((i)=>!ee(i,s));if(n.length===0)throw new u("No packages found matching the criteria");return{packageNames:n,packages:r.packages}}async executeInteractive(e,t){let{packages:r,packageNames:s}=await this.scanPackages(e,t.filter),n=await this.selectPackagesInteractive(r,s,t.tag),i=t.message??await this.promptMessage(),o=t.description??await this.promptDescription(),a=this.buildStoneData({ctx:e,description:o,message:i,packages:r,selection:n,tag:t.tag});await this.createStone(e,a,r)}async executeDirect(e,t){let r=t.message??(this.isInteractiveSession(e)?await this.promptMessage():void 0);if(!r)throw new u("Message is required",'Pass --message "..." or a positional message');let{packages:s,packageNames:n}=await this.scanPackages(e,t.filter),i=this.resolveSelection(e,t,n);this.validatePackages(i,s,n,e.config.get("ignore")??[],t.filter);let o=this.buildStoneData({ctx:e,description:t.description,message:r,packages:s,selection:i,tag:t.tag});await this.createStone(e,o,s)}resolveSelection(e,t,r){let s=t.bump;if(!s)return this.requirePackageSelection(t.packageSelection);if(!e.args.all&&!e.args.yes)throw new u("--bump selects every (filtered) package","Confirm the selection with --all or --yes");let n=[...r];if(s==="major")return{major:n,minor:[],patch:[]};if(s==="minor")return{major:[],minor:n,patch:[]};return{major:[],minor:[],patch:n}}requirePackageSelection(e){if(!(e.major.length>0||e.minor.length>0||e.patch.length>0))throw new u("At least one of --major (-M), --minor (-m), or --patch (-p) is required","Or use --bump <type> with --all to select every package");return e}validatePackages(e,t,r,s,n){let i=[...e.major,...e.minor,...e.patch],o=i.filter((d)=>!t.has(d));if(o.length>0)throw new u(`Unknown packages: ${o.join(", ")}`);let a=i.filter((d)=>ee(d,s));if(a.length>0)throw new u(`Packages are excluded by config.ignore: ${a.join(", ")}`,"Remove them from ignore before releasing them");let c=new Set(r),l=i.filter((d)=>!c.has(d));if(l.length>0)throw new u(`Packages do not match --filter "${n}": ${l.join(", ")}`)}async executeFromCommits(e,t){if(!e.config.get("lastStone")?.commit)throw new u("No release baseline recorded",`Set lastStone.commit (run ${N} init in an existing repo, or complete one release) before using --fromCommits`);let s=await new et(e.config).analyze({filter:t.filter,single:e.config.get("single")});if(s.length===0){v.info("No conventional commits found since last release");return}let{packages:n}=await this.scanPackages(e,t.filter);v.info(`Found ${p.bold(String(s.length))} commit group(s) to process`);let i=new E(e.config),o=0;for(let a of s){let c=et.buildStoneData(a,n,ae(e.config,t.tag));if(e.args.dryRun)this.logPreview(e,c,n);else{let l=await i.create(c);o++,v.success(`Created stone: ${p.bold(l.id)}`)}}if(!e.args.dryRun&&o>0)G(`Created ${p.bold(String(o))} stone(s) from commits.
221
+ Run ${p.green(`${N} check`)} to see what will be released.`,p.green("Success"))}async selectPackagesInteractive(e,t,r){let s=[],n={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let o=t.filter((c)=>!s.includes(c));if(o.length===0)break;let a=await this.promptPackages(i,o,e,r);if(s.push(...a),i==="major")n.major=a;else if(i==="minor")n.minor=a;else n.patch=a}if(s.length===0)throw new u("No packages selected");return n}async promptPackages(e,t,r,s){let n=yt[e],i=t.map((o)=>{let a=r.get(o);return{label:a?this.safeLabel(a,e,s):o,value:o}});return ke({message:`Select packages for ${p.bold(n(e))} bump`,options:i,required:!1})}safeLabel(e,t,r){try{return e.withBump(t,r).label}catch(s){if(s instanceof u)return e.name;throw s}}async promptMessage(){return(await ce({message:"Stone message (used as commit message)",placeholder:"feat: add new feature",validate:(t)=>t?.trim()?void 0:"Message is required"})).trim()}async promptDescription(){return(await ce({message:"Description (optional, press enter to skip)",placeholder:"Additional details about this change..."}))?.trim()||void 0}buildStoneData(e){let{ctx:t,selection:r,message:s,packages:n,tag:i,description:o}=e,a=[...r.major.map((l)=>({bump:"major",name:l})),...r.minor.map((l)=>({bump:"minor",name:l})),...r.patch.map((l)=>({bump:"patch",name:l}))],c=bt(a,n,ae(t.config,i));return{dependency:Y(c),description:o,major:Y(r.major),message:s,minor:Y(r.minor),patch:Y(r.patch),tag:i}}async createStone(e,t,r){let s=new E(e.config);if(this.logPreview(e,t,r),e.args.dryRun)return;if(!e.args.yes&&this.isInteractiveSession(e)){if(!await j({initialValue:!0,message:"Create this stone?"}))return}let n=await s.create(t);G(`Run ${p.green(`${N} roll`)} to release packages
222
+ or create another stone with ${p.green(`${N} version`)}`,`Stone ${p.bold(n.id)} ${p.green("created")}`)}logPreview(e,t,r){let s=[];if(e.args.dryRun)s.push(p.bold(p.yellow("[dry-run]")));if(s.push(`${p.dim("Stone:")} ${p.bold(t.message)}`),t.tag)s.push(`${p.dim("Tag:")} ${t.tag}`);for(let n of this.previewLabels(e,t,r))s.push(` ${n}`);v.step(s.join(`
223
+ `))}previewLabels(e,t,r){let s=A.create(t);try{return z.applyStone(s,r,ae(e.config).kinds).map((n)=>n.label)}catch(n){if(n instanceof u)return s.allPackages.filter((i)=>r.has(i));throw n}}}class Hc extends Hs{constructor(){super(new zs(`${mt}/${Er}`,Fe),{bin:N,clearOnStart:!0,exitLabel:"Give Up",goodbyeMessage:"The boulder rolls back down...",name:"SISYPHUS",promptMessage:"Choose your boulder:",version:wo})}init(){this.registerCommands([new ui,new pi,new di,new gi,new mi,new fi,new Pi,new Ri])}}var Xg=new Hc;Xg.run();