@getsolaris/oh-my-worktree 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/omw.js +55 -55
  2. package/package.json +1 -1
package/dist/omw.js CHANGED
@@ -1,34 +1,34 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var Oa=Object.defineProperty;var Wa=(t)=>t;function Da(t,e){this[t]=Wa.bind(null,e)}var xt=(t,e)=>{for(var o in e)Oa(t,o,{get:e[o],enumerable:!0,configurable:!0,set:Da.bind(e,o)})};var H=(t,e)=>()=>(t&&(e=t(t=0)),e);var ie=import.meta.require;function zi(t){if(t instanceof Error)return t;return Error(typeof t==="string"?t:"Unknown error",{cause:t})}function vi(t,e=bt){let o=e&&e.context&&e.context[yf],n=zi(t);if(!o)throw n;try{for(let r of o)r(n)}catch(r){vi(r,e&&e.owner||null)}}function Pf(){let t={owner:bt,context:bt?bt.context:null,owned:null,cleanups:null};if(bt)if(!bt.owned)bt.owned=[t];else bt.owned.push(t);return t}function k(t,e){return[()=>t,(o)=>{return t=typeof o==="function"?o(t):o}]}function ae(t,e){}function Yt(t,e){bt=Pf();let o;try{o=t(e)}catch(n){vi(n)}finally{bt=bt.owner}return()=>o}function ke(t,e,o={}){let n=Array.isArray(t),r=o.defer;return()=>{if(r)return;let i;if(n){i=[];for(let s=0;s<t.length;s++)i.push(t[s]())}else i=t();return e(i)}}function tn(t){if(bt)if(!bt.cleanups)bt.cleanups=[t];else bt.cleanups.push(t);return t}function Ue(t){let e=Symbol("context");return{id:e,Provider:Rf(e),defaultValue:t}}function Ke(t){return bt&&bt.context&&bt.context[t.id]!==void 0?bt.context[t.id]:t.defaultValue}function Ef(t){let e=Yt(()=>or(t()));return e.toArray=()=>{let o=e();return Array.isArray(o)?o:o!=null?[o]:[]},e}function or(t){if(typeof t==="function"&&!t.length)return or(t());if(Array.isArray(t)){let e=[];for(let o=0;o<t.length;o++){let n=or(t[o]);Array.isArray(n)?e.push.apply(e,n):e.push(n)}return e}return t}function Rf(t){return function(o){return Yt(()=>{return bt.context={...bt.context,[t]:o.value},Ef(()=>o.children)})}}function Hi(t){let e=String(t),o=e.length-1;return ce.context.id+(o?String.fromCharCode(96+o):"")+e}function Mf(t,e){let o=t.each||[],n=o.length,r=t.children;if(n){let i=Array(n);for(let s=0;s<n;s++)i[s]=e(r,o[s],s);return i}return t.fallback}function St(t){return Mf(t,(e,o,n)=>e(o,()=>n))}function O(t){let e;return t.when?typeof(e=t.children)==="function"?e(t.keyed?t.when:()=>t.when):e:t.fallback||""}function ki(t,e,o={}){if(typeof e!=="function")o=e||{},e=t,t=!0;let n=new Set,r=ce.getNextContextId(),i={},s=o.storage?o.storage(o.initialValue)[0]():o.initialValue,c,f;if(ce.context.async&&o.ssrLoadFrom!=="initial"){if(i=ce.context.resources[r]||(ce.context.resources[r]={}),i.ref){if(!i.data&&!i.ref[0]._loading&&!i.ref[0].error)i.ref[1].refetch();return i.ref}}let a=()=>{if(f)throw f;let x=o.ssrLoadFrom!=="initial"&&ce.context.async&&"data"in ce.context.resources[r];if(!x&&Ro)Ro.push(r);if(!x&&u._loading){let m=Ke(Of);if(m)m.resources.set(r,u),n.add(m)}return x},u=()=>{return a()?ce.context.resources[r].data:s},h=()=>{return a(),u._loading};u._loading=!1,u.error=void 0,u.state="initialValue"in o?"ready":"unresolved",Object.defineProperties(u,{latest:{get(){return u()}},loading:{get(){return h()}}});function d(){let x=ce.context;if(!x.async)return u._loading=!!(typeof t==="function"?t():t);if(x.resources&&r in x.resources&&"data"in x.resources[r]){s=x.resources[r].data;return}let m;try{if(Ro=[],m=typeof t==="function"?t():t,Ro.length)return}finally{Ro=null}if(!c){if(m==null||m===!1)return;c=e(m,{value:s})}if(c!=null&&typeof c==="object"&&"then"in c){if(u._loading=!0,u.state="pending",c=c.then((b)=>{return u._loading=!1,u.state="ready",x.resources[r].data=b,c=null,Ji(n),b}).catch((b)=>{throw u._loading=!1,u.state="errored",u.error=f=zi(b),c=null,Ji(n),f}),x.serialize)x.serialize(r,c,o.deferStream);return c}if(x.resources[r].data=c,x.serialize)x.serialize(r,c);return c=null,x.resources[r].data}if(o.ssrLoadFrom!=="initial")d();let w=[u,{refetch:d,mutate:(x)=>s=x}];if(c)i.ref=w;return w}function Wf(t){for(let e of t.resources.values())if(e._loading)return!1;return!0}function Ji(t){for(let e of t){if(!Wf(e))continue;e.completed(),t.delete(e)}}var Em,Rm,Mm,yf,bt=null,ce,Of,Ro=null;var Rt=H(()=>{Em=Symbol("solid-proxy"),Rm=Symbol("solid-track"),Mm=Symbol("solid-dev-component"),yf=Symbol("error");ce={context:void 0,getContextId(){if(!this.context)throw Error("getContextId cannot be used under non-hydrating context");return Hi(this.context.count)},getNextContextId(){if(!this.context)throw Error("getNextContextId cannot be used under non-hydrating context");return Hi(this.context.count++)}};Of=Ue()});function Ui(t){return typeof t==="object"&&t!==null&&"frames"in t&&"interval"in t&&Array.isArray(t.frames)}function Ki(t){return typeof t==="object"&&t!==null&&"label"in t&&"onClick"in t}function nr(t,e){switch(t){case"success":return e.success;case"error":return e.error;case"warning":return e.warning;case"info":return e.info;case"loading":return rr(e.loading);default:return""}}function rr(t){if(Ui(t))return t.frames[0]??"\u25CC";return t}function ir(t){return Ui(t)?t:null}var Df,qi;var Vi=H(()=>{Df={frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"],interval:100},qi={success:"\u2713",error:"\u2717",warning:"!",info:"\u2139",loading:Df,close:"\xD7"}});import{BoxRenderable as on,TextAttributes as Ff,TextRenderable as Mo,parseColor as Bf}from"@opentui/core";function Gf(t){return t!==null&&typeof t==="object"&&"ok"in t&&typeof t.ok==="boolean"&&"status"in t&&typeof t.status==="number"}function Jf(t,e={}){let[o,n]=t.split("-"),r={position:"absolute"};if(o==="top")r.top=e.top??en.top;else r.bottom=e.bottom??en.bottom;if(n==="left")r.left=e.left??en.left,r.alignItems="flex-start";else if(n==="center")r.left=0,r.width="100%",r.alignItems="center";else r.right=e.right??en.right,r.alignItems="flex-end";return r}function zf(t){return t.includes("center")}function vf(t){return t.startsWith("top")}function kf(t,e={top:0,right:0,bottom:0,left:0}){if(!t)return{...e};let{padding:o,paddingX:n,paddingY:r}=t;return{top:t.paddingTop??r??o??e.top,right:t.paddingRight??n??o??e.right,bottom:t.paddingBottom??r??o??e.bottom,left:t.paddingLeft??n??o??e.left}}function Uf(...t){let e={};for(let o of t){if(!o)continue;Object.assign(e,o)}return e}function Xi(t,e,o){let n=sr.style,r=sr[t]?.style,i=e?.style,s=e?.[t]?.style,c=Uf(n,r,i,s,o);if(c.border===!1)delete c.borderStyle,delete c.borderColor;return c}function Zi(t,e,o){if(o!==void 0)return o;let n=e?.[t]?.duration;if(n!==void 0)return n;if(e?.duration!==void 0)return e.duration;return sr.duration}var Lf,Af=200,Qi=60,en,If,sr,jf=1,Tf=class{subscribers=[];toasts=[];dismissedToasts=new Set;_activeToasts=[];_updateActiveToastsCache=()=>{let t=this.toasts.filter((e)=>!this.dismissedToasts.has(e.id));if(t.length!==this._activeToasts.length||t.some((e,o)=>e!==this._activeToasts[o]))this._activeToasts=t};subscribe=(t)=>{return this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);if(e>-1)this.subscribers.splice(e,1)}};publish=(t)=>{for(let e of this.subscribers)e(t)};addToast=(t)=>{this.toasts=[...this.toasts,t],this._updateActiveToastsCache(),this.publish(t)};create=(t)=>{let{message:e,...o}=t,n=typeof t.id==="number"||t.id&&t.id.length>0?t.id:jf++,r=this.toasts.find((s)=>s.id===n),i=t.dismissible===void 0?!0:t.dismissible;if(this.dismissedToasts.has(n))this.dismissedToasts.delete(n);if(r)this.toasts=this.toasts.map((s)=>{if(s.id===n)return this.publish({...s,...t,id:n,title:e}),{...s,...t,id:n,dismissible:i,title:e};return s}),this._updateActiveToastsCache();else this.addToast({title:e,...o,dismissible:i,id:n,type:t.type??"default"});return n};dismiss=(t)=>{if(t!==void 0)this.dismissedToasts.add(t),this._updateActiveToastsCache(),setTimeout(()=>{for(let e of this.subscribers)e({id:t,dismiss:!0})},0);else{for(let e of this.toasts){this.dismissedToasts.add(e.id);for(let o of this.subscribers)o({id:e.id,dismiss:!0})}this._updateActiveToastsCache()}return t};message=(t,e)=>{return this.create({...e,message:t,type:"default"})};error=(t,e)=>{return this.create({...e,message:t,type:"error"})};success=(t,e)=>{return this.create({...e,message:t,type:"success"})};info=(t,e)=>{return this.create({...e,message:t,type:"info"})};warning=(t,e)=>{return this.create({...e,message:t,type:"warning"})};loading=(t,e)=>{return this.create({...e,message:t,type:"loading"})};promise=(t,e)=>{if(!e)return;let o;if(e.loading!==void 0)o=this.create({...e,type:"loading",message:e.loading,description:typeof e.description!=="function"?e.description:void 0});let n=t instanceof Function?t():t,r=o!==void 0,i,s=n.then(async(f)=>{if(i=["resolve",f],Gf(f)&&!f.ok){r=!1;let a=typeof e.error==="function"?await e.error(`HTTP error! status: ${f.status}`):e.error,u=typeof e.description==="function"?await e.description(`HTTP error! status: ${f.status}`):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:u,...h})}else if(f instanceof Error){r=!1;let a=typeof e.error==="function"?await e.error(f):e.error,u=typeof e.description==="function"?await e.description(f):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:u,...h})}else if(e.success!==void 0){r=!1;let a=typeof e.success==="function"?await e.success(f):e.success,u=typeof e.description==="function"?await e.description(f):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"success",description:u,...h})}}).catch(async(f)=>{if(i=["reject",f],e.error!==void 0){r=!1;let a=typeof e.error==="function"?await e.error(f):e.error,u=typeof e.description==="function"?await e.description(f):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:u,...h})}}).finally(()=>{if(r)this.dismiss(o),o=void 0;e.finally?.()}),c=()=>new Promise((f,a)=>s.then(()=>i[0]==="reject"?a(i[1]):f(i[1])).catch(a));if(typeof o!=="string"&&typeof o!=="number")return{unwrap:c};return Object.assign(o,{unwrap:c})};getActiveToasts=()=>{return this._activeToasts}},Lt,_f=(t,e)=>Lt.message(t,e),Nf=()=>Lt.toasts,Hf=()=>Lt.getActiveToasts(),qe,Kf,Yi;var ts=H(()=>{Vi();Lf={SHORT:2000,DEFAULT:4000,LONG:6000,EXTENDED:1e4,PERSISTENT:1/0},en={top:1,right:2,bottom:1,left:2},If={border:!0,borderStyle:"single",borderColor:"#333333",minHeight:3,backgroundColor:"#1a1a1a",foregroundColor:"#ffffff",mutedColor:"#6b7280"},sr={style:If,duration:Lf.DEFAULT,default:{style:{borderColor:"#333333"}},success:{style:{borderColor:"#22c55e"}},error:{style:{borderColor:"#ef4444"}},warning:{style:{borderColor:"#f59e0b"}},info:{style:{borderColor:"#3b82f6"}},loading:{style:{borderColor:"#6b7280"}}};Lt=new Tf,qe=Object.assign(_f,{success:Lt.success,info:Lt.info,warning:Lt.warning,error:Lt.error,message:Lt.message,promise:Lt.promise,dismiss:Lt.dismiss,loading:Lt.loading},{getHistory:Nf,getToasts:Hf});Kf=class extends on{_toast;_icons;_toastOptions;_computedStyle;_closeButton;_onRemove;_remainingTime;_closeTimerStartTime=0;_lastCloseTimerStartTime=0;_timerHandle=null;_paused=!1;_dismissed=!1;_spinnerHandle=null;_spinnerFrameIndex=0;_spinnerConfig=null;_iconText=null;_contentBox=null;_titleText=null;_descriptionText=null;_actionsBox=null;constructor(t,e){let o=Xi(e.toast.type,e.toastOptions,e.toast.style),n=Zi(e.toast.type,e.toastOptions,e.toast.duration),r=kf(o,{top:0,right:1,bottom:0,left:1});super(t,{id:`toast-${e.toast.id}`,flexDirection:"row",gap:1,border:o.border,borderStyle:o.borderStyle,borderColor:o.borderColor,customBorderChars:o.customBorderChars,backgroundColor:o.backgroundColor,minHeight:o.minHeight,maxWidth:o.maxWidth??Qi,minWidth:o.minWidth,paddingTop:r.top,paddingRight:r.right,paddingBottom:r.bottom,paddingLeft:r.left,onMouseOver:()=>this.pause(),onMouseOut:()=>this.resume()});if(this._toast=e.toast,this._icons=e.icons===!1?!1:{...qi,...e.icons},this._toastOptions=e.toastOptions,this._computedStyle=o,this._closeButton=e.closeButton,this._onRemove=e.onRemove,this._remainingTime=n,this.setupContent(),this._remainingTime!==1/0&&this._toast.type!=="loading")this.startTimer();if(this._toast.type==="loading")this.startSpinner()}setupContent(){let t=this.ctx,e=this._toast,o=this._computedStyle,n=this._icons,r=o.iconColor??o.borderColor,i=e.type==="loading";if(i&&n!==!1)this._spinnerConfig=ir(n.loading);let s=e.icon??(n===!1?void 0:i?rr(n.loading):nr(e.type,n));if(s)this._iconText=new Mo(t,{id:`${this.id}-icon`,content:s,fg:r,flexShrink:0,paddingTop:0,paddingBottom:0}),this.add(this._iconText);this._contentBox=new on(t,{id:`${this.id}-content`,flexDirection:"column",flexGrow:1,flexShrink:1,gap:0});let c=typeof e.title==="function"?e.title():e.title;if(c)this._titleText=new Mo(t,{id:`${this.id}-title`,content:c,fg:o.foregroundColor,attributes:Ff.BOLD,wrapMode:"word"}),this._contentBox.add(this._titleText);let f=typeof e.description==="function"?e.description():e.description;if(f)this._descriptionText=new Mo(t,{id:`${this.id}-description`,content:f,fg:o.mutedColor,wrapMode:"word"}),this._contentBox.add(this._descriptionText);if(this.add(this._contentBox),e.action){if(this._actionsBox=new on(t,{id:`${this.id}-actions`,flexDirection:"row",gap:1,flexShrink:0,alignItems:"center"}),e.action&&Ki(e.action)){let a=new Mo(t,{id:`${this.id}-action`,content:`[${e.action.label}]`,fg:o.foregroundColor,onMouseUp:()=>e.action?.onClick?.()});this._actionsBox.add(a)}this.add(this._actionsBox)}if((e.closeButton??this._closeButton)&&e.dismissible!==!1){let a=n===!1?"\xD7":n.close,u=new Mo(t,{id:`${this.id}-close`,content:a,fg:o.mutedColor,flexShrink:0,onMouseUp:()=>this.dismiss()});this.add(u)}}startTimer(){if(this._remainingTime===1/0)return;this._closeTimerStartTime=Date.now(),this._timerHandle=setTimeout(()=>{this._toast.onAutoClose?.(this._toast),this.dismiss()},this._remainingTime)}pause(){if(this._paused||this._remainingTime===1/0)return;if(this._paused=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;if(this._lastCloseTimerStartTime<this._closeTimerStartTime){let t=Date.now()-this._closeTimerStartTime;this._remainingTime=Math.max(0,this._remainingTime-t)}this._lastCloseTimerStartTime=Date.now()}resume(){if(!this._paused||this._remainingTime===1/0)return;this._paused=!1,this.startTimer()}startSpinner(){if(this._spinnerHandle||!this._spinnerConfig)return;let{frames:t,interval:e}=this._spinnerConfig;this._spinnerHandle=setInterval(()=>{this._spinnerFrameIndex=(this._spinnerFrameIndex+1)%t.length;let o=t[this._spinnerFrameIndex];if(this._iconText&&o)this._iconText.content=o,this.requestRender()},e)}stopSpinner(){if(this._spinnerHandle)clearInterval(this._spinnerHandle),this._spinnerHandle=null}dismiss(){if(this._dismissed)return;if(this._dismissed=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),this._toast.onDismiss?.(this._toast),Lt.dismiss(this._toast.id),setTimeout(()=>{this._onRemove?.(this._toast)},Af)}updateToast(t){this._toast=t;let e=Xi(t.type,this._toastOptions,t.style);if(this._computedStyle=e,e.borderColor)this.borderColor=e.borderColor;if(e.customBorderChars)this.customBorderChars=e.customBorderChars;let o=e.iconColor??e.borderColor;if(this._iconText){let i=t.icon??(this._icons===!1?void 0:nr(t.type,this._icons));if(i)this._iconText.content=i;if(o)this._iconText.fg=Bf(o)}if(this._titleText){let i=typeof t.title==="function"?t.title():t.title;if(i)this._titleText.content=i}if(this._descriptionText){let i=typeof t.description==="function"?t.description():t.description;if(i)this._descriptionText.content=i}let n=this._spinnerHandle!==null,r=t.type==="loading";if(n&&!r)this.stopSpinner(),this._spinnerConfig=null;else if(!n&&r){if(this._icons!==!1)this._spinnerConfig=ir(this._icons.loading);this.startSpinner()}if(t.type!=="loading"){if(this._timerHandle)clearTimeout(this._timerHandle);if(this._remainingTime=Zi(t.type,this._toastOptions,t.duration),this._remainingTime!==1/0)this.startTimer()}this.requestRender()}get toast(){return this._toast}get isDismissed(){return this._dismissed}destroy(){if(this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),super.destroy()}},Yi=class extends on{_options={};_toastRenderables=new Map;_unsubscribe=null;constructor(t,e={}){super(t,{id:"toaster",flexDirection:"column",gap:1,zIndex:9999});this._options=e,this.applyLayoutOptions(),this.subscribe()}applyLayoutOptions(){let t=this._options.position??"bottom-right",e=Jf(t,this._options.offset??{}),o=zf(t);if(Object.assign(this,e),super.gap=this._options.gap??1,!o)super.maxWidth=this._options.maxWidth??Qi}isToastPosition(t){return t==="top-left"||t==="top-center"||t==="top-right"||t==="bottom-left"||t==="bottom-center"||t==="bottom-right"}set position(t){if(this.isToastPosition(t))this._options.position=t,this.applyLayoutOptions();else super.position=t}set offset(t){this._options.offset=t,this.applyLayoutOptions()}set gap(t){this._options.gap=t,super.gap=t}set visibleToasts(t){this._options.visibleToasts=t}set closeButton(t){this._options.closeButton=t}set icons(t){this._options.icons=t}set stackingMode(t){this._options.stackingMode=t}set maxWidth(t){this._options.maxWidth=t,super.maxWidth=t}set toastOptions(t){this._options.toastOptions=t}subscribe(){this._unsubscribe=Lt.subscribe((t)=>{if("dismiss"in t&&t.dismiss)this.removeToast(t.id);else this.addOrUpdateToast(t)})}addOrUpdateToast(t){let e=this._toastRenderables.get(t.id);if(e){e.updateToast(t);return}if((this._options.stackingMode??"single")==="single")for(let[n]of this._toastRenderables)this.removeToast(n);else{let n=this._options.visibleToasts??3,r=this._toastRenderables.size;if(r>=n){let i=r-n+1,s=Array.from(this._toastRenderables.keys());for(let c=0;c<i;c++){let f=s[c];if(f!==void 0)this.removeToast(f)}}}let o=new Kf(this.ctx,{toast:t,icons:this._options.icons,toastOptions:this._options.toastOptions,closeButton:this._options.closeButton,onRemove:(n)=>this.handleToastRemoved(n)});if(this._toastRenderables.set(t.id,o),vf(this._options.position??"bottom-right"))this.add(o);else this.add(o,0);this.requestRender()}removeToast(t){let e=this._toastRenderables.get(t);if(e)e.dismiss()}handleToastRemoved(t){let e=this._toastRenderables.get(t.id);if(e)this._toastRenderables.delete(t.id),this.remove(e.id),e.destroy(),this.requestRender()}get toastCount(){return this._toastRenderables.size}dismissAll(){for(let[t]of this._toastRenderables)this.removeToast(t)}destroy(){this._unsubscribe?.();for(let[,t]of this._toastRenderables)t.destroy();this._toastRenderables.clear(),super.destroy()}}});import{createElement as Tm,extend as qf,spread as _m}from"@opentui/solid";var cr=H(()=>{ts();qf({toaster:Yi})});function os(t){let[e,o]=k("list"),[n,r]=k(0),[i,s]=k(null),[c,f]=k(!1),[a,u]=k(!1),[h,d]=k(!1),[w,x]=k(new Set),[m,b]=k(!1),S=(st)=>{let ct=new Set(w());if(ct.has(st))ct.delete(st);else ct.add(st);x(ct)},R=(st)=>{x(new Set(st))},P=(st)=>{let ct=new Set(st),_=w(),ot=new Set;for(let et of _)if(ct.has(et))ot.add(et);if(ot.size!==_.size)x(ot)},M=()=>{x(new Set)};return React.createElement(es.Provider,{value:{activeTab:e,setActiveTab:o,selectedWorktreeIndex:n,setSelectedWorktreeIndex:r,selectedWorktreePath:i,setSelectedWorktreePath:s,showRemove:c,setShowRemove:f,showCommandPalette:a,setShowCommandPalette:u,showDetailView:h,setShowDetailView:d,repoPath:()=>t.repoPath,repoPaths:()=>t.repoPaths,selectedWorktrees:w,toggleWorktreeSelection:S,selectAllNonMain:R,pruneSelectedWorktrees:P,clearSelection:M,showBulkActions:m,setShowBulkActions:b}},t.children)}function Et(){let t=Ke(es);if(!t)throw Error("useApp must be used within AppProvider");return t}var es;var te=H(()=>{Rt();es=Ue()});var it,Oo,ar,Wo;var Ct=H(()=>{it=class it extends Error{exitCode;stderr;command;constructor(t,e,o,n){super(t);this.exitCode=e;this.stderr=o;this.command=n;this.name="GitError"}};Oo=class Oo extends Error{installed;required;constructor(t,e){super(`git version ${t} is below minimum required ${e}`);this.installed=t;this.required=e;this.name="GitVersionError"}};ar=class ar extends Error{branch;reason;constructor(t,e,o){super(t);this.branch=e;this.reason=o;this.name="ArchiveError"}};Wo=class Wo extends Error{path;reason;constructor(t,e,o){super(t);this.path=e;this.reason=o;this.name="ImportError"}}});import{resolve as ns,dirname as Vf}from"path";import{mkdirSync as Xf,existsSync as Zf}from"fs";function Do(t){let e=nn.get(t);if(!e)return;if(Date.now()>e.expires){nn.delete(t);return}return e.data}function ee(t,e,o=Qf){return nn.set(t,{data:e,expires:Date.now()+o}),e}function Mt(){nn.clear()}class E{static gitVersionChecked=!1;static async run(t,e){let o=Bun.spawn(["git",...t],{cwd:e??Bun.cwd,stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[n,r,i]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(i!==0)throw new it(`git ${t[0]} failed: ${r.trim()}`,i,r.trim(),`git ${t.join(" ")}`);return n.trim()}static async checkVersion(){if(this.gitVersionChecked)return;let e=(await this.run(["--version"])).match(/git version (\d+)\.(\d+)\.?((\d+)?)/);if(!e)throw Error("Cannot parse git version");let[,o,n]=e.map(Number);if(o<2||o===2&&n<17)throw new Oo(`${o}.${n}`,"2.17");this.gitVersionChecked=!0}static async list(t){await this.checkVersion();let e=t??Bun.cwd,o=await this.getMainRepoPath(e).catch(()=>e),n=`list:${o}`,r=Do(n);if(r)return r;let i=o.split("/").pop()??"",s=await this.run(["worktree","list","--porcelain"],e),c=this.parsePorcelain(s,i,o),f=await Promise.all(c.map(async(a)=>({...a,isDirty:await this.isDirty(a.path).catch(()=>!1)})));return ee(n,f)}static async listAll(t){await this.checkVersion();let e=new Set,o=[];for(let r of t){let i=ns(r);if(!e.has(i))e.add(i),o.push(i)}return(await Promise.all(o.map(async(r)=>{try{return await this.list(r)}catch{return[]}}))).flat()}static parsePorcelain(t,e,o){let n=t.trim();if(!n)return[];return n.split(/\n\n+/).filter(Boolean).map((i,s)=>{let c=i.split(`
4
- `),f=c.find((b)=>b.startsWith("worktree ")),a=c.find((b)=>b.startsWith("HEAD ")),u=c.find((b)=>b.startsWith("branch ")),h=c.find((b)=>b.startsWith("locked")),d=f?.slice(9)??"",w=a?.slice(5)??"",x=null;if(u)x=u.slice(7).replace(/^refs\/heads\//,"");let m=h&&h.startsWith("locked ")?h.slice(7):void 0;return{path:d,branch:x,head:w,isMain:s===0,isDirty:!1,isLocked:Boolean(h),lockReason:m,repoName:e,repoPath:o}})}static async add(t,e,o,n){await this.checkVersion();let r=Vf(e);if(!Zf(r))Xf(r,{recursive:!0});let s=!await this.localBranchExists(t,n),c=["worktree","add",e,t];if(s)c=["worktree","add","-b",t,e,o?.base??"HEAD"];await this.run(c,n),Mt()}static async localBranchExists(t,e){try{return await this.run(["rev-parse","--verify",`refs/heads/${t}`],e??Bun.cwd),!0}catch{return!1}}static async remove(t,e,o){await this.checkVersion();let n=["worktree","remove",t];if(e?.force)n.push("--force");await this.run(n,o),Mt()}static async move(t,e,o){await this.checkVersion(),await this.run(["worktree","move",t,e],o),Mt()}static async prune(t){await this.checkVersion(),await this.run(["worktree","prune"],t),Mt()}static async isWorktree(t){let e=t??Bun.cwd;try{let o=await this.run(["rev-parse","--git-dir"],e),n=await this.run(["rev-parse","--git-common-dir"],e);return o!==n&&!o.endsWith("/.git")&&!o.endsWith("\\.git")}catch{return!1}}static async getMainRepoPath(t){let e=t??Bun.cwd,o=await this.run(["rev-parse","--git-common-dir"],e),n=ns(e,o);return n.endsWith("/.git")?n.slice(0,-5):n}static async getBranchForWorktree(t){try{let e=await this.run(["rev-parse","--abbrev-ref","HEAD"],t);return e==="HEAD"?null:e}catch{return null}}static async isDirty(t){try{return(await this.run(["status","--porcelain"],t??Bun.cwd)).length>0}catch{return!1}}static async getAheadBehind(t,e){let o=e??Bun.cwd,n=`ahead-behind:${o}:${t}`,r=Do(n);if(r)return r;try{let i=await this.run(["rev-parse","--abbrev-ref",`${t}@{upstream}`],o),s=await this.run(["rev-list","--left-right","--count",`${i}...${t}`],o),[c,f]=s.split(/\s+/).map(Number);return ee(n,{ahead:f??0,behind:c??0})}catch{return ee(n,{ahead:0,behind:0})}}static async getLastCommit(t){let e=t??Bun.cwd,o=`last-commit:${e}`,n=Do(o);if(n!==void 0)return n;try{let r=await this.run(["log","-1","--format=%h\x1F%s\x1F%cr"],e);if(!r)return ee(o,null);let[i,s,c]=r.split("\x1F");return ee(o,{hash:i??"",message:s??"",relativeDate:c??""})}catch{return ee(o,null)}}static async getDirtyCount(t){let e=t??Bun.cwd,o=`dirty-count:${e}`,n=Do(o);if(n!==void 0)return n;try{let r=await this.run(["status","--porcelain"],e);if(!r)return ee(o,0);return ee(o,r.split(`
5
- `).filter(Boolean).length)}catch{return ee(o,0)}}static async unlock(t,e){await this.checkVersion(),await this.run(["worktree","unlock",t],e),Mt()}static async isMergedInto(t,e,o){try{return(await this.run(["branch","--merged",e],o??Bun.cwd)).split(`
6
- `).some((r)=>r.trim().replace(/^[*+] /,"")===t)}catch{return!1}}static async getDefaultRemote(t){try{return await this.run(["config","checkout.defaultRemote"],t??Bun.cwd)||"origin"}catch{return"origin"}}static async remoteBranchExists(t,e,o){let n=e??await this.getDefaultRemote(o);try{return await this.run(["rev-parse","--verify",`refs/remotes/${n}/${t}`],o??Bun.cwd),!0}catch{return!1}}static async listBranches(t){let e=t??Bun.cwd,o=`branches:${e}`,n=Do(o);if(n)return n;let[r,i]=await Promise.all([this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/heads/"],e).catch(()=>""),this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/remotes/"],e).catch(()=>"")]),s=[];for(let c of r.split(`
7
- `).filter(Boolean)){let[f,a]=c.split("\x1F");s.push({name:f??"",isRemote:!1,lastCommitDate:a??""})}for(let c of i.split(`
8
- `).filter(Boolean)){let[f,a]=c.split("\x1F");if(!f||f.endsWith("/HEAD"))continue;let u=f.replace(/^[^/]+\//,"");if(s.some((h)=>h.name===u))continue;s.push({name:u,isRemote:!0,lastCommitDate:a??""})}return ee(o,s)}static async diffBetween(t,e,o,n){let r=["diff"];if(o?.stat)r.push("--stat");if(o?.nameOnly)r.push("--name-only");return r.push(t,e),this.run(r,n)}static async getWorktreeLastActivity(t){try{let e=await this.run(["log","-1","--format=%ci"],t);return e?new Date(e):null}catch{return null}}static async setUpstream(t,e,o){let n=e??await this.getDefaultRemote(o),r=o??Bun.cwd;try{if(await this.run(["config",`branch.${t}.remote`],r))return}catch{}await this.run(["branch",`--set-upstream-to=${n}/${t}`,t],r)}}var Qf=3000,nn;var at=H(()=>{Ct();nn=new Map});function is(t){let[e,{refetch:o}]=ki(async()=>{try{if(t.repoPaths.length<=1)return await E.list(t.repoPaths[0]);return await E.listAll(t.repoPaths)}catch(s){throw s}}),n=()=>{Mt(),o()},r=Yt(()=>{let s=e()??[],c=new Set,f=[];for(let a of s)if(!c.has(a.repoName))c.add(a.repoName),f.push(a.repoName);return f}),i=Yt(()=>r().length>1);return React.createElement(rs.Provider,{value:{worktrees:()=>e(),refetch:n,loading:()=>e.loading,error:()=>e.error,repoNames:r,isMultiRepo:i}},t.children)}function Ot(){let t=Ke(rs);if(!t)throw Error("useGit must be used within GitProvider");return t}var rs;var fe=H(()=>{Rt();at();rs=Ue()});var Yf,rn,ss,tl,sn,l;var Tt=H(()=>{Rt();Yf={opencode:{bg:{base:"#090909",surface:"#111111",elevated:"#1a1a1a",overlay:"#000000"},border:{default:"#2a2a2a",active:"#4fc3f7",subtle:"#1e1e1e"},text:{primary:"#e8e8e8",secondary:"#666666",accent:"#4fc3f7",success:"#4ade80",warning:"#fbbf24",error:"#f87171",selected:"#ffffff"},tab:{active:"#4fc3f7",activeBg:"#1a1a1a",inactive:"#555555",inactiveBg:"#000000"},select:{focusedBg:"#1a2a3a",focusedFg:"#4fc3f7",selectedBg:"#161616",selectedFg:"#e8e8e8",normalFg:"#e8e8e8",descFg:"#666666"}},"tokyo-night":{bg:{base:"#1a1b26",surface:"#1f2335",elevated:"#24283b",overlay:"#0d1117"},border:{default:"#3b4261",active:"#7aa2f7",subtle:"#292e42"},text:{primary:"#c0caf5",secondary:"#565f89",accent:"#7aa2f7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",selected:"#ffffff"},tab:{active:"#7aa2f7",activeBg:"#24283b",inactive:"#565f89",inactiveBg:"#1a1b26"},select:{focusedBg:"#283457",focusedFg:"#7aa2f7",selectedBg:"#2a2f44",selectedFg:"#c0caf5",normalFg:"#c0caf5",descFg:"#565f89"}},dracula:{bg:{base:"#282a36",surface:"#21222c",elevated:"#343746",overlay:"#191a21"},border:{default:"#6272a4",active:"#bd93f9",subtle:"#44475a"},text:{primary:"#f8f8f2",secondary:"#6272a4",accent:"#bd93f9",success:"#50fa7b",warning:"#ffb86c",error:"#ff5555",selected:"#ffffff"},tab:{active:"#bd93f9",activeBg:"#343746",inactive:"#6272a4",inactiveBg:"#282a36"},select:{focusedBg:"#44475a",focusedFg:"#bd93f9",selectedBg:"#383a4a",selectedFg:"#f8f8f2",normalFg:"#f8f8f2",descFg:"#6272a4"}},nord:{bg:{base:"#2e3440",surface:"#3b4252",elevated:"#434c5e",overlay:"#242933"},border:{default:"#4c566a",active:"#81a1c1",subtle:"#3b4252"},text:{primary:"#eceff4",secondary:"#4c566a",accent:"#81a1c1",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",selected:"#ffffff"},tab:{active:"#88c0d0",activeBg:"#434c5e",inactive:"#4c566a",inactiveBg:"#2e3440"},select:{focusedBg:"#3b4252",focusedFg:"#88c0d0",selectedBg:"#3b4252",selectedFg:"#eceff4",normalFg:"#eceff4",descFg:"#4c566a"}},catppuccin:{bg:{base:"#1e1e2e",surface:"#181825",elevated:"#313244",overlay:"#11111b"},border:{default:"#45475a",active:"#cba6f7",subtle:"#313244"},text:{primary:"#cdd6f4",secondary:"#585b70",accent:"#cba6f7",success:"#a6e3a1",warning:"#fab387",error:"#f38ba8",selected:"#ffffff"},tab:{active:"#cba6f7",activeBg:"#313244",inactive:"#585b70",inactiveBg:"#1e1e2e"},select:{focusedBg:"#313244",focusedFg:"#cba6f7",selectedBg:"#313244",selectedFg:"#cdd6f4",normalFg:"#cdd6f4",descFg:"#585b70"}},"github-dark":{bg:{base:"#0d1117",surface:"#161b22",elevated:"#21262d",overlay:"#010409"},border:{default:"#30363d",active:"#58a6ff",subtle:"#21262d"},text:{primary:"#e6edf3",secondary:"#484f58",accent:"#58a6ff",success:"#3fb950",warning:"#d29922",error:"#f85149",selected:"#ffffff"},tab:{active:"#58a6ff",activeBg:"#21262d",inactive:"#484f58",inactiveBg:"#0d1117"},select:{focusedBg:"#1f2937",focusedFg:"#58a6ff",selectedBg:"#1f2937",selectedFg:"#e6edf3",normalFg:"#e6edf3",descFg:"#484f58"}}},rn=["opencode","tokyo-night","dracula","nord","catppuccin","github-dark"],ss={opencode:"OpenCode","tokyo-night":"Tokyo Night",dracula:"Dracula",nord:"Nord",catppuccin:"Catppuccin Mocha","github-dark":"GitHub Dark"},[tl,sn]=k("opencode"),l=new Proxy({},{get(t,e){return new Proxy({},{get(o,n){return Yf[tl()][e]?.[n]}})}})});import{existsSync as el,mkdirSync as ol,readFileSync as cs,statSync as nl,writeFileSync as rl}from"fs";import{dirname as il,join as cn,resolve as sl}from"path";function as(t){let e=cn(t,".git"),o=nl(e,{throwIfNoEntry:!1});if(!o)return cn(e,"omw-focus");if(o.isDirectory())return cn(e,"omw-focus");let r=cs(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim(),i=sl(t,r);return cn(i,"omw-focus")}function so(t,e){let o=as(t);ol(il(o),{recursive:!0}),rl(o,e.join(`
9
- `),{encoding:"utf-8",mode:384})}function qt(t){let e=as(t);if(!el(e))return null;return cs(e,"utf-8").split(/\r?\n/).filter(Boolean)}var le=()=>{};import{existsSync as lr,mkdirSync as cl,readFileSync as fs,statSync as al,writeFileSync as fl,unlinkSync as ll}from"fs";import{dirname as hl,join as an,resolve as ul}from"path";function fr(t){return t.replace(/\//g,"-").replace(/[^a-zA-Z0-9._-]/g,"_")}async function he(t){let e=Bun.spawn(["tmux",...t],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C"}}),[o,n,r]=await Promise.all([new Response(e.stdout).text(),new Response(e.stderr).text(),e.exited]);if(r!==0)throw new co(`tmux ${t[0]} failed: ${n.trim()}`,n.trim());return o.trim()}function ye(t,e){let o=fr(e??ls),n=fr(t);return`${o}_${n}`}function hr(t){let e=an(t,".git"),o=al(e,{throwIfNoEntry:!1});if(!o)return an(e,"omw-session");if(o.isDirectory())return an(e,"omw-session");let r=fs(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim(),i=ul(t,r);return an(i,"omw-session")}function pl(t,e){let o=hr(t);cl(hl(o),{recursive:!0}),fl(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}function kt(t){let e=hr(t);if(!lr(e))return null;try{return JSON.parse(fs(e,"utf-8"))}catch{return null}}function ur(t){let e=hr(t);if(lr(e))ll(e)}async function ao(){try{return await Bun.spawn(["tmux","-V"],{stdout:"pipe",stderr:"pipe"}).exited===0}catch{return!1}}function pr(){return Boolean(Bun.env.TMUX)}async function ue(t){try{return await he(["has-session","-t",t]),!0}catch{return!1}}async function dl(t,e,o){if(await ue(t))throw new co(`Session '${t}' already exists`,"session_exists");if(!lr(e))throw new co(`Worktree path does not exist: ${e}`,"path_not_found");let n=o?.windows??[],r=n[0],i=["new-session","-d","-s",t,"-c",e];if(r)i.push("-n",r.name);if(await he(i),r?.command)await he(["send-keys","-t",`${t}:${r.name}`,r.command,"Enter"]);for(let s=1;s<n.length;s++){let c=n[s];if(await he(["new-window","-t",t,"-n",c.name,"-c",e]),c.command)await he(["send-keys","-t",`${t}:${c.name}`,c.command,"Enter"])}if(n.length>0)await he(["select-window","-t",`${t}:${n[0].name}`])}async function dr(t){if(!await ue(t))return;await he(["kill-session","-t",t])}async function fn(t){if(!await ue(t))throw new co(`Session '${t}' does not exist`,"session_not_found");if(pr())await he(["switch-client","-t",t]);else if(await Bun.spawn(["tmux","attach-session","-t",t],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0)throw new co(`Failed to attach to session '${t}'`,"attach_failed")}async function mr(t){let e=fr(t??ls);try{let o=await he(["list-sessions","-F","#{session_name}|#{session_windows}|#{session_attached}|#{session_created}"]);if(!o)return[];return o.split(`
10
- `).filter(Boolean).filter((n)=>n.startsWith(`${e}_`)||n.startsWith(`${e}:`)).map((n)=>{let[r,i,s,c]=n.split("|");return{name:r??"",windows:parseInt(i??"0",10),attached:s==="1",created:c??""}})}catch{return[]}}async function ln(t,e,o){let n=ye(t,o?.prefix),r=o?.attach??!0;if(await ue(n)){if(r)await fn(n);return n}if(await dl(n,e,o?.layout),pl(e,{name:n,branch:t,worktreePath:e,createdAt:new Date().toISOString(),layout:o?.layoutName}),r)await fn(n);return n}async function hn(t,e,o){let n=ye(t,o),r=await ue(n);if(r)await dr(n);return ur(e),r}var co,ls="omw";var Pe=H(()=>{co=class co extends Error{reason;constructor(t,e){super(t);this.reason=e;this.name="SessionError"}}});import{useTerminalDimensions as ml}from"@opentui/solid";function hs(t){let e=Ot(),o=ml(),n=()=>o().width,r=()=>o().height,[i,s]=k(null),[c,f]=k(!0),[a,u]=k(""),h;tn(()=>{if(h)clearTimeout(h)});let d=()=>{return(e.worktrees()??[]).find((st)=>st.isMain)?.branch??"main"};ae(ke(()=>t.worktree.path,(P)=>{if(h)clearTimeout(h);if(!P){s(null),u(""),f(!1);return}s(null),u(""),f(!0),h=setTimeout(async()=>{if(t.worktree.path!==P)return;try{let[M,st,ct]=await Promise.all([wl(P),t.worktree.branch&&!t.worktree.isMain?E.diffBetween(d(),t.worktree.branch,{stat:!0},P).catch(()=>""):Promise.resolve(""),t.worktree.branch?E.getAheadBehind(t.worktree.branch,P):Promise.resolve({ahead:0,behind:0})]);if(t.worktree.path!==P)return;let _=null;try{_=qt(P)}catch{}let ot=null,et=kt(P);if(et){let re=await ue(et.name).catch(()=>!1);ot={meta:et,active:re}}if(t.worktree.path!==P)return;s({commits:M,diffStat:st,aheadBehind:ct,focus:_,session:ot}),u("")}catch(M){if(t.worktree.path!==P)return;s(null),u(M.message)}finally{if(t.worktree.path===P)f(!1)}},xl)}));let w=()=>{let P=t.worktree;if(P.isLocked)return"\uD83D\uDD12 locked";if(P.isDirty)return"\u25CF dirty";return"\u2713 clean"},x=()=>{let P=t.worktree;if(P.isLocked)return l.text.warning;if(P.isDirty)return l.text.error;return l.text.success},m=()=>{let P=i();if(!P)return"";let M=[];if(P.aheadBehind.ahead>0)M.push(`\u2191${P.aheadBehind.ahead}`);if(P.aheadBehind.behind>0)M.push(`\u2193${P.aheadBehind.behind}`);return M.length>0?M.join(" "):"\u2713 up to date"},b=()=>{let P=i();if(!P)return l.text.secondary;return P.aheadBehind.ahead||P.aheadBehind.behind?l.text.warning:l.text.success},S=()=>{let P=i();if(!P||!P.diffStat)return[];return P.diffStat.split(`
11
- `).filter(Boolean)},R=()=>"\u2500".repeat(Math.max(n()-7,10));return React.createElement("box",{x:0,y:0,width:n(),height:r(),backgroundColor:l.bg.base},React.createElement("scrollbox",{x:2,y:1,width:n()-3,height:r()-3},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Worktree Detail"),React.createElement("text",{x:17,y:0,fg:l.text.secondary},"(Esc to close)")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},R())),React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},t.worktree.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},t.worktree.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Status")),React.createElement("text",{fg:x()},w())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"HEAD")),React.createElement("text",{fg:l.text.secondary},t.worktree.head?.slice(0,8))),React.createElement(O,{when:c()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Loading details..."))),React.createElement(O,{when:!c()&&!!a()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.error},`Failed to load details: ${a()}`))),React.createElement(O,{when:!c()&&!a()&&!!i()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Upstream")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},R())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Sync")),React.createElement("text",{fg:b()},m())),React.createElement(O,{when:i().aheadBehind.ahead>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Ahead")),React.createElement("text",{fg:l.text.warning},`${i().aheadBehind.ahead} commit(s)`))),React.createElement(O,{when:i().aheadBehind.behind>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Behind")),React.createElement("text",{fg:l.text.warning},`${i().aheadBehind.behind} commit(s)`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Recent Commits")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},R())),React.createElement(O,{when:i().commits.length>0,fallback:React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"No commits found"))},React.createElement(St,{each:i().commits},(P)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.primary},P)))),React.createElement(O,{when:!t.worktree.isMain&&S().length>0},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},`Diff vs ${d()}`)),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},R())),React.createElement(St,{each:S()},(P)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.primary},P)))),React.createElement(O,{when:i().focus&&i().focus.length>0},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Focus Paths")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},R())),React.createElement(St,{each:i().focus},(P)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.primary},` \u2022 ${P}`)))),React.createElement(O,{when:i().session},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Session")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},R())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Name")),React.createElement("text",{fg:l.text.primary},i().session.meta.name)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Status")),React.createElement("text",{fg:i().session.active?l.text.success:l.text.error},i().session.active?"\u25CF active":"\u25CB inactive")),React.createElement(O,{when:i().session.meta.layout},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Layout")),React.createElement("text",{fg:l.text.primary},i().session.meta.layout)))),React.createElement(O,{when:t.worktree.isMain},React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Vt,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Type")),React.createElement("text",{fg:l.text.accent},"main worktree")))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},R())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Esc:back d:delete o:open r:refresh"))))}async function wl(t){try{let e=Bun.spawn(["git","log","--oneline","-10"],{cwd:t,stdout:"pipe",stderr:"pipe",env:{...process.env,LC_ALL:"C"}}),o=await new Response(e.stdout).text();if(await e.exited,e.exitCode!==0)return[];return o.trim().split(`
12
- `).filter(Boolean)}catch{return[]}}var xl=150,Vt=16;var us=H(()=>{Rt();fe();Tt();le();Pe();at()});import{useKeyboard as gl,useTerminalDimensions as bl}from"@opentui/solid";function ps(){let t=Et(),e=Ot(),o=bl(),n=()=>{let b=e.worktrees()??[],S=t.selectedWorktreePath();if(S){let R=b.find((P)=>P.path===S);if(R)return R}return b[t.selectedWorktreeIndex()]},r=()=>o().width,i=()=>o().height,s=14,[c,f]=k(null),[a,u]=k(!1),[h,d]=k(""),w;tn(()=>{if(w)clearTimeout(w)}),ae(ke(()=>n()?.path,(b)=>{if(w)clearTimeout(w);if(!b){f(null),u(!1),d("");return}f(null),u(!0),d(""),w=setTimeout(async()=>{let S=n();if(!S||S.path!==b)return;try{let[R,P,M]=await Promise.all([S.branch?E.getAheadBehind(S.branch,S.path):Promise.resolve({ahead:0,behind:0}),E.getLastCommit(S.path),E.getDirtyCount(S.path)]);if(n()?.path===b)f({aheadBehind:R,lastCommit:P,dirtyCount:M}),d("")}catch(R){if(n()?.path===b)f(null),d(R.message)}finally{if(n()?.path===b)u(!1)}},Cl)}));let x=()=>{if(a())return"Loading...";if(h())return"Unavailable";let b=c();if(!b)return"";let S=[];if(b.aheadBehind.ahead>0)S.push(`\u2191${b.aheadBehind.ahead}`);if(b.aheadBehind.behind>0)S.push(`\u2193${b.aheadBehind.behind}`);return S.length>0?S.join(" "):"\u2713 up to date"},m=()=>{let b=n();if(!b)return"";if(b.isLocked)return"\uD83D\uDD12 locked";let S=c();if(S&&S.dirtyCount>0)return`\u25CF ${S.dirtyCount} file(s) dirty`;if(b.isDirty)return"\u25CF dirty";return"\u2713 clean"};return gl((b)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;let S=b.name;if(S==="x"&&t.selectedWorktrees().size>0){t.setShowBulkActions(!0);return}if(S==="return"&&!t.showDetailView()&&n()){t.setShowDetailView(!0);return}if(S==="escape"&&t.showDetailView()){t.setShowDetailView(!1);return}}),React.createElement("box",{width:"100%",height:"100%",backgroundColor:l.bg.base},React.createElement(O,{when:t.showDetailView()&&!!n()},React.createElement(hs,{worktree:n()})),React.createElement(O,{when:!t.showDetailView()},React.createElement(O,{when:e.loading()},React.createElement("text",{x:2,y:2,fg:l.text.secondary},"Loading worktrees...")),React.createElement(O,{when:!e.loading()&&!!e.error()},React.createElement("text",{x:2,y:2,fg:l.text.error},"Error: ",e.error()?.message),React.createElement("text",{x:2,y:3,fg:l.text.secondary},"Not in a git repository?")),React.createElement(O,{when:!e.loading()&&!e.error()&&!!n()},React.createElement("box",{width:"100%",height:"100%",border:!0,borderStyle:"rounded",borderColor:l.border.default,flexDirection:"column",backgroundColor:l.bg.surface,paddingX:1,paddingY:1},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("text",{fg:l.text.accent},"Worktree Details")),React.createElement("box",{height:1},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement(O,{when:e.isMultiRepo()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Repo")),React.createElement("text",{fg:l.text.warning},n()?.repoName))),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},n()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},n()?.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Status")),React.createElement("text",{fg:n()?.isDirty?l.text.error:n()?.isLocked?l.text.warning:l.text.success},m())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Sync")),React.createElement("text",{fg:h()?l.text.error:a()?l.text.secondary:c()?.aheadBehind?.ahead||c()?.aheadBehind?.behind?l.text.warning:l.text.success},x())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"HEAD")),React.createElement("text",{fg:l.text.secondary},n()?.head?.slice(0,8))),React.createElement(O,{when:c()?.lastCommit},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Last Commit")),React.createElement("text",{fg:l.text.primary},c().lastCommit.relativeDate)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"")),React.createElement("text",{fg:l.text.secondary},c().lastCommit.message.length>50?c().lastCommit.message.slice(0,47)+"...":c().lastCommit.message))),React.createElement(O,{when:(()=>{let b=qt(n()?.path??"");return b&&b.length>0})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Focus")),React.createElement("text",{fg:l.text.accent},qt(n()?.path??"")?.join(", ")??""))),React.createElement(O,{when:(()=>{return!!kt(n()?.path??"")})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Session")),React.createElement("text",{fg:l.text.accent},(()=>{let b=kt(n()?.path??"");if(!b)return"";return b.layout?`${b.name} [${b.layout}]`:b.name})()))),React.createElement(O,{when:n()?.isMain},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Type")),React.createElement("text",{fg:l.text.accent},"main worktree"))),React.createElement("box",{height:1},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Enter:detail"),React.createElement("text",{fg:l.text.secondary},"d:delete"),React.createElement("text",{fg:l.text.secondary},"a:add"),React.createElement("text",{fg:l.text.secondary},"o:open"),React.createElement("text",{fg:l.text.secondary},"r:refresh"),React.createElement("text",{fg:l.text.secondary},"^P:commands")))),React.createElement(O,{when:!e.loading()&&!e.error()&&!n()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.secondary},"No worktree selected."),React.createElement("text",{fg:l.text.accent},"Press 'a' to create one.")))))}var Cl=150;var ds=H(()=>{Rt();te();fe();Tt();le();Pe();at();us()});import{join as xr,resolve as un}from"path";import*as Ee from"fs";function oe(t,e,o){if(!Array.isArray(t)||t.some((n)=>typeof n!=="string"))o.push({field:e,message:"Must be an array of strings"})}function gs(){let e=Bun.env.XDG_CONFIG_HOME??xr(Bun.env.HOME??"~",".config");return xr(e,"oh-my-worktree")}function _t(){return xr(gs(),"config.json")}function Bo(t){let e=[];if(typeof t!=="object"||t===null)return e.push({field:"root",message:"Config must be a JSON object"}),e;let o=t;if(!("version"in o))e.push({field:"version",message:"Required field 'version' is missing"});else if(o.version!==1)e.push({field:"version",message:`Expected version 1, got ${JSON.stringify(o.version)}`});let n=new Set(["version","defaults","repos","$schema","theme","templates","lifecycle","sessions","profiles","activeProfile"]);for(let r of Object.keys(o))if(!n.has(r))e.push({field:r,message:`Unknown field '${r}'`});if("defaults"in o&&o.defaults!==void 0)if(typeof o.defaults!=="object"||o.defaults===null)e.push({field:"defaults",message:"Must be an object"});else{let r=o.defaults,i=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","sharedDeps"]);for(let s of Object.keys(r))if(!i.has(s))e.push({field:`defaults.${s}`,message:`Unknown field '${s}'`});if("worktreeDir"in r&&typeof r.worktreeDir!=="string")e.push({field:"defaults.worktreeDir",message:"Must be a string"});if("autoUpstream"in r&&typeof r.autoUpstream!=="boolean")e.push({field:"defaults.autoUpstream",message:"Must be a boolean"});for(let s of["copyFiles","linkFiles","postCreate","postRemove"])if(s in r)oe(r[s],`defaults.${s}`,e);if("sharedDeps"in r&&r.sharedDeps!==void 0)if(typeof r.sharedDeps!=="object"||r.sharedDeps===null)e.push({field:"defaults.sharedDeps",message:"Must be an object"});else ms(r.sharedDeps,"defaults.sharedDeps",e)}if("repos"in o&&o.repos!==void 0)if(!Array.isArray(o.repos))e.push({field:"repos",message:"Must be an array"});else for(let r=0;r<o.repos.length;r++){let i=o.repos[r],s=`repos[${r}]`;if(typeof i!=="object"||i===null){e.push({field:s,message:"Must be an object"});continue}let c=i,f=new Set(["path","worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","monorepo","sharedDeps"]);for(let a of Object.keys(c))if(!f.has(a))e.push({field:`${s}.${a}`,message:`Unknown field '${a}'`});if(!("path"in c)||typeof c.path!=="string")e.push({field:`${s}.path`,message:"Required string field 'path' is missing"});if("worktreeDir"in c&&typeof c.worktreeDir!=="string")e.push({field:`${s}.worktreeDir`,message:"Must be a string"});if("autoUpstream"in c&&typeof c.autoUpstream!=="boolean")e.push({field:`${s}.autoUpstream`,message:"Must be a boolean"});for(let a of["copyFiles","linkFiles","postCreate","postRemove"])if(a in c)oe(c[a],`${s}.${a}`,e);if("sharedDeps"in c&&c.sharedDeps!==void 0)if(typeof c.sharedDeps!=="object"||c.sharedDeps===null)e.push({field:`${s}.sharedDeps`,message:"Must be an object"});else ms(c.sharedDeps,`${s}.sharedDeps`,e);if("monorepo"in c&&c.monorepo!==void 0)if(typeof c.monorepo!=="object"||c.monorepo===null)e.push({field:`${s}.monorepo`,message:"Must be an object"});else{let a=c.monorepo,u=new Set(["autoDetect","extraPatterns","hooks"]);for(let h of Object.keys(a))if(!u.has(h))e.push({field:`${s}.monorepo.${h}`,message:`Unknown field '${h}'`});if("autoDetect"in a&&typeof a.autoDetect!=="boolean")e.push({field:`${s}.monorepo.autoDetect`,message:"Must be a boolean"});if("extraPatterns"in a&&a.extraPatterns!==void 0)oe(a.extraPatterns,`${s}.monorepo.extraPatterns`,e);if("hooks"in a&&a.hooks!==void 0)if(!Array.isArray(a.hooks))e.push({field:`${s}.monorepo.hooks`,message:"Must be an array"});else for(let h=0;h<a.hooks.length;h++){let d=a.hooks[h];if(typeof d!=="object"||d===null){e.push({field:`${s}.monorepo.hooks[${h}]`,message:"Must be an object"});continue}if(!("glob"in d)||typeof d.glob!=="string")e.push({field:`${s}.monorepo.hooks[${h}].glob`,message:"Required string field"});if("copyFiles"in d&&d.copyFiles!==void 0)oe(d.copyFiles,`${s}.monorepo.hooks[${h}].copyFiles`,e);if("linkFiles"in d&&d.linkFiles!==void 0)oe(d.linkFiles,`${s}.monorepo.hooks[${h}].linkFiles`,e);if("postCreate"in d&&d.postCreate!==void 0)oe(d.postCreate,`${s}.monorepo.hooks[${h}].postCreate`,e);if("postRemove"in d&&d.postRemove!==void 0)oe(d.postRemove,`${s}.monorepo.hooks[${h}].postRemove`,e)}}}if("templates"in o&&o.templates!==void 0)if(typeof o.templates!=="object"||o.templates===null||Array.isArray(o.templates))e.push({field:"templates",message:"Must be an object (key-value map)"});else{let r=o.templates,i=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","base"]);for(let[s,c]of Object.entries(r)){let f=`templates.${s}`;if(typeof c!=="object"||c===null){e.push({field:f,message:"Must be an object"});continue}let a=c;for(let u of Object.keys(a))if(!i.has(u))e.push({field:`${f}.${u}`,message:`Unknown field '${u}'`});if("worktreeDir"in a&&typeof a.worktreeDir!=="string")e.push({field:`${f}.worktreeDir`,message:"Must be a string"});if("base"in a&&typeof a.base!=="string")e.push({field:`${f}.base`,message:"Must be a string"});if("autoUpstream"in a&&typeof a.autoUpstream!=="boolean")e.push({field:`${f}.autoUpstream`,message:"Must be a boolean"});for(let u of["copyFiles","linkFiles","postCreate","postRemove"])if(u in a)oe(a[u],`${f}.${u}`,e)}}if("lifecycle"in o&&o.lifecycle!==void 0)if(typeof o.lifecycle!=="object"||o.lifecycle===null)e.push({field:"lifecycle",message:"Must be an object"});else{let r=o.lifecycle,i=new Set(["autoCleanMerged","staleAfterDays","maxWorktrees"]);for(let s of Object.keys(r))if(!i.has(s))e.push({field:`lifecycle.${s}`,message:`Unknown field '${s}'`});if("autoCleanMerged"in r&&typeof r.autoCleanMerged!=="boolean")e.push({field:"lifecycle.autoCleanMerged",message:"Must be a boolean"});if("staleAfterDays"in r&&(typeof r.staleAfterDays!=="number"||r.staleAfterDays<1))e.push({field:"lifecycle.staleAfterDays",message:"Must be a positive number"});if("maxWorktrees"in r&&(typeof r.maxWorktrees!=="number"||r.maxWorktrees<1))e.push({field:"lifecycle.maxWorktrees",message:"Must be a positive number"})}if("sessions"in o&&o.sessions!==void 0)if(typeof o.sessions!=="object"||o.sessions===null)e.push({field:"sessions",message:"Must be an object"});else{let r=o.sessions,i=new Set(["enabled","autoCreate","autoKill","prefix","defaultLayout","layouts"]);for(let s of Object.keys(r))if(!i.has(s))e.push({field:`sessions.${s}`,message:`Unknown field '${s}'`});for(let s of["enabled","autoCreate","autoKill"])if(s in r&&typeof r[s]!=="boolean")e.push({field:`sessions.${s}`,message:"Must be a boolean"});if("prefix"in r&&typeof r.prefix!=="string")e.push({field:"sessions.prefix",message:"Must be a string"});if("defaultLayout"in r&&typeof r.defaultLayout!=="string")e.push({field:"sessions.defaultLayout",message:"Must be a string"});if("layouts"in r&&r.layouts!==void 0)if(typeof r.layouts!=="object"||r.layouts===null||Array.isArray(r.layouts))e.push({field:"sessions.layouts",message:"Must be an object (key-value map)"});else{let s=r.layouts;for(let[c,f]of Object.entries(s)){let a=`sessions.layouts.${c}`;if(typeof f!=="object"||f===null){e.push({field:a,message:"Must be an object"});continue}let u=f;if(!("windows"in u)||!Array.isArray(u.windows))e.push({field:`${a}.windows`,message:"Required array field"});else for(let h=0;h<u.windows.length;h++){let d=u.windows[h];if(typeof d!=="object"||d===null){e.push({field:`${a}.windows[${h}]`,message:"Must be an object"});continue}if(!("name"in d)||typeof d.name!=="string")e.push({field:`${a}.windows[${h}].name`,message:"Required string field"});if("command"in d&&typeof d.command!=="string")e.push({field:`${a}.windows[${h}].command`,message:"Must be a string"})}}}if("defaultLayout"in r&&typeof r.defaultLayout==="string"&&"layouts"in r&&typeof r.layouts==="object"&&r.layouts!==null){let s=r.layouts;if(!(r.defaultLayout in s))e.push({field:"sessions.defaultLayout",message:`Layout '${r.defaultLayout}' does not exist in sessions.layouts`})}}if("profiles"in o&&o.profiles!==void 0)if(typeof o.profiles!=="object"||o.profiles===null||Array.isArray(o.profiles))e.push({field:"profiles",message:"Must be an object (key-value map)"});else{let r=o.profiles,i=new Set(["defaults","repos","theme","templates","lifecycle","sessions"]);for(let[s,c]of Object.entries(r)){let f=`profiles.${s}`;if(typeof c!=="object"||c===null){e.push({field:f,message:"Must be an object"});continue}let a=c;for(let u of Object.keys(a))if(!i.has(u))e.push({field:`${f}.${u}`,message:`Unknown field '${u}'`})}}if("activeProfile"in o&&o.activeProfile!==void 0){if(typeof o.activeProfile!=="string")e.push({field:"activeProfile",message:"Must be a string"});else if("profiles"in o&&o.profiles!==void 0&&typeof o.profiles==="object"&&o.profiles!==null&&!Array.isArray(o.profiles)){let r=o.profiles;if(!(o.activeProfile in r))e.push({field:"activeProfile",message:`Profile '${o.activeProfile}' does not exist in profiles`})}else if(!("profiles"in o)||o.profiles===void 0)e.push({field:"activeProfile",message:"Cannot set activeProfile without profiles"})}return e}function ms(t,e,o){let n=new Set(["strategy","paths","invalidateOn"]);for(let r of Object.keys(t))if(!n.has(r))o.push({field:`${e}.${r}`,message:`Unknown field '${r}'`});if("strategy"in t&&!["hardlink","symlink","copy"].includes(t.strategy))o.push({field:`${e}.strategy`,message:'Must be "hardlink", "symlink", or "copy"'});if("paths"in t)oe(t.paths,`${e}.paths`,o);if("invalidateOn"in t)oe(t.invalidateOn,`${e}.invalidateOn`,o)}function Fo(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Ve(t){if(Array.isArray(t))return t.map((e)=>Ve(e));if(Fo(t)){let e={};for(let[o,n]of Object.entries(t))e[o]=Ve(n);return e}return t}function bs(t,e){if(e===void 0)return Ve(t);if(Array.isArray(e))return e.map((r)=>Ve(r));if(!Fo(e))return Ve(e);let o=Fo(t)?t:{},n={};for(let[r,i]of Object.entries(o))n[r]=Ve(i);for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let s=o[r];if(Fo(s)&&Fo(i)){n[r]=bs(s,i);continue}n[r]=Ve(i)}return n}function $l(t){if(!t.activeProfile)return structuredClone(t);let e=t.profiles?.[t.activeProfile];if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`Active profile '${t.activeProfile}' does not exist`);return bs(t,e)}function Y(t){let e=t??_t();if(!Ee.existsSync(e))return structuredClone(ws);let o;try{let s=pn.readFileSync(e,"utf-8");o=JSON.parse(s)}catch(s){let c=s.message;if(c.includes("JSON"))throw Error(`Invalid JSON in config file: ${c}`);if(s instanceof SyntaxError)throw Error(`Invalid JSON in config file: ${c}`);throw Error(`Failed to read config file: ${c}`)}let n=Bo(o);if(n.length>0){let s=n.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed: ${s}`)}let r=$l(o),i=Bo(r);if(i.length>0){let s=i.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed after applying activeProfile: ${s}`)}return r}function Bt(t,e){let o=un(e),n=t.repos?.find((r)=>un(r.path)===o);return{worktreeDir:n?.worktreeDir??t.defaults?.worktreeDir??fo.worktreeDir,copyFiles:n?.copyFiles??t.defaults?.copyFiles??fo.copyFiles,linkFiles:n?.linkFiles??t.defaults?.linkFiles??fo.linkFiles,postCreate:n?.postCreate??t.defaults?.postCreate??fo.postCreate,postRemove:n?.postRemove??t.defaults?.postRemove??fo.postRemove,autoUpstream:n?.autoUpstream??t.defaults?.autoUpstream??fo.autoUpstream,monorepo:n?.monorepo,sharedDeps:n?.sharedDeps??t.defaults?.sharedDeps}}function Re(t){return(t.repos??[]).map((e)=>un(e.path))}function dn(t,e){let o=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,o).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}function ne(t){let e=t??_t(),o=t?un(e,".."):gs();if(!Ee.existsSync(o))pn.mkdirSync(o,{recursive:!0,mode:448});if(Ee.existsSync(e))return e;return Lo(e,`${JSON.stringify(ws,null,2)}
13
- `),e}function mn(t,e){return t.templates?.[e]}function xn(t,e){return{worktreeDir:e.worktreeDir??t.worktreeDir,copyFiles:e.copyFiles??t.copyFiles,linkFiles:e.linkFiles??t.linkFiles,postCreate:e.postCreate??t.postCreate,postRemove:e.postRemove??t.postRemove,autoUpstream:e.autoUpstream??t.autoUpstream,monorepo:t.monorepo,sharedDeps:t.sharedDeps}}function Me(t){return t.sessions??{}}function wn(t,e){let o=t.sessions;if(!o?.layouts)return;let n=e??o.defaultLayout;if(!n)return;return o.layouts[n]}function Lo(t,e){let o=`${t}.tmp.${Date.now()}`;try{Ee.writeFileSync(o,e,{encoding:"utf-8",mode:384});let n=JSON.parse(e),r=Bo(n);if(r.length>0)throw Error(`Validation failed: ${r.map((i)=>i.message).join("; ")}`);pn.renameSync(o,t)}catch(n){if(Ee.existsSync(o))pn.unlinkSync(o);throw n}}var pn,xs="~/.omw/worktrees/{repo}-{branch}",ws,fo;var $t=H(()=>{pn=Ee,ws={version:1,defaults:{worktreeDir:xs,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0},repos:[]},fo={worktreeDir:xs,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0,sharedDeps:void 0}});import*as Sl from"fs";import{join as Oe,resolve as pe,dirname as Ao}from"path";function ho(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=Oe(pe(t),r),s=Oe(pe(e),r);if(!de(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping copy: ${r}`);continue}if(de(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping copy: ${r}`);continue}try{lo(Ao(s),{recursive:!0}),$s(i,s),n.copied.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to copy ${r}: ${c.message}`)}}return n}function uo(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=pe(Oe(pe(t),r)),s=Oe(pe(e),r);if(!de(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping symlink: ${r}`);continue}if(de(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping symlink: ${r}`);continue}try{lo(Ao(s),{recursive:!0}),Ss(i,s),n.linked.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to symlink ${r}: ${c.message}`)}}return n}function ys(t,e){let o=0,n=[],r=pe(t),i=pe(e);if(!de(r))return{linked:0,errors:[`Source not found: ${t}`]};let s=El(r,{throwIfNoEntry:!1});if(!s||!s.isDirectory())try{return lo(Ao(i),{recursive:!0}),Cs(r,i),{linked:1,errors:[]}}catch(c){return{linked:0,errors:[`Failed to hardlink ${t}: ${c.message}`]}}if(!de(i))lo(i,{recursive:!0});try{let c=Pl(r,{withFileTypes:!0});for(let f of c){let a=Oe(r,f.name),u=Oe(i,f.name);if(f.isDirectory()){let h=ys(a,u);o+=h.linked,n.push(...h.errors)}else if(f.isFile()){if(de(u))continue;try{Cs(a,u),o++}catch(h){try{$s(a,u),o++}catch(d){n.push(`Failed to link/copy ${f.name}: ${d.message}`)}}}}}catch(c){n.push(`Failed to read directory ${t}: ${c.message}`)}return{linked:o,errors:n}}function Ps(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]},r=o.paths??[],i=o.strategy??"symlink";for(let s of r){let c=Oe(pe(t),s),f=Oe(pe(e),s);if(!de(c)){n.skipped.push(s),n.warnings.push(`Source not found, skipping shared dep: ${s}`);continue}if(de(f)){n.skipped.push(s);continue}try{if(i==="symlink")lo(Ao(f),{recursive:!0}),Ss(c,f),n.linked.push(s);else if(i==="hardlink"){let a=ys(c,f);if(a.linked>0)n.linked.push(s);for(let u of a.errors)n.warnings.push(u)}else lo(Ao(f),{recursive:!0}),yl(c,f,{recursive:!0}),n.copied.push(s)}catch(a){n.skipped.push(s),n.warnings.push(`Failed to share dep ${s}: ${a.message}`)}}return n}var $s,yl,de,Ss,Rx,Cs,Pl,El,lo;var gn=H(()=>{({copyFileSync:$s,cpSync:yl,existsSync:de,symlinkSync:Ss,unlinkSync:Rx,linkSync:Cs,readdirSync:Pl,statSync:El,mkdirSync:lo}=Sl)});import{existsSync as Rl,mkdirSync as Ml}from"fs";async function Wt(t,e){let o=e.timeout??30000;for(let n of t)await Ol(n,e.cwd,o,e.env??{},e.onOutput)}async function Ol(t,e,o,n,r){if(!Rl(e))Ml(e,{recursive:!0});let i;try{i=Bun.spawn(["sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}catch(a){if(a.code!=="ENOENT")throw a;i=Bun.spawn(["/bin/sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}let s=!1,c=setTimeout(()=>{s=!0,i.kill()},o),f=i.stderr?new Response(i.stderr).text():Promise.resolve("");try{if(r&&i.stdout){let u=i.stdout.getReader(),h=new TextDecoder,d="";while(!0){let{done:w,value:x}=await u.read();if(w)break;d+=h.decode(x,{stream:!0});let m=d.split(`
14
- `);d=m.pop()??"";for(let b of m)if(b)r(b)}if(d+=h.decode(),d)r(d)}let a=await i.exited;if(s)throw new mo(t,o);if(a!==0){let u=(await f).trim();throw new po(t,a,u)}}finally{clearTimeout(c)}}var po,mo;var me=H(()=>{po=class po extends Error{command;exitCode;stderr;constructor(t,e,o){super(`Hook command failed (exit ${e}): ${t}
15
- ${o}`);this.command=t;this.exitCode=e;this.stderr=o;this.name="HookError"}};mo=class mo extends Error{command;timeoutMs;constructor(t,e){super(`Hook command timed out after ${e}ms: ${t}`);this.command=t;this.timeoutMs=e;this.name="HookTimeoutError"}}});import{existsSync as Wl,readdirSync as Fx,readFileSync as Bx,statSync as Dl}from"fs";import{join as Fl,relative as Ax}from"path";function bn(t,e){let o=[],n=[];for(let r of e){let i=r.trim();if(!i){n.push(i);continue}let s=Fl(t,i);try{if(Wl(s)&&Dl(s).isDirectory())o.push(i);else n.push(i)}catch{n.push(i)}}return{valid:o,invalid:n}}var wr=()=>{};function Xe(t,e){return t.map((o)=>{let n=new Bun.Glob(o.glob),r=e.filter((i)=>n.match(i));return{glob:o.glob,matchedPaths:r,copyFiles:o.copyFiles??[],linkFiles:o.linkFiles??[],postCreate:o.postCreate??[],postRemove:o.postRemove??[]}}).filter((o)=>o.matchedPaths.length>0)}function Bl(t,e){return t.replace(/\{packagePath\}/g,e.packagePath).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}async function xo(t,e,o){for(let n of t){let r=n[e],i=e==="postCreate"&&n.copyFiles.length>0,s=e==="postCreate"&&n.linkFiles.length>0,c=r.length>0;if(!i&&!s&&!c)continue;for(let f of n.matchedPaths){let{join:a}=await import("path"),u=a(o.mainRepoPath,f),h=a(o.cwd,f);if(i){let d=ho(u,h,n.copyFiles);for(let w of d.copied)o.onOutput?.(`Copied ${f}/${w}`);for(let w of d.warnings)o.onOutput?.(`\u26A0 ${w}`)}if(s){let d=uo(u,h,n.linkFiles);for(let w of d.linked)o.onOutput?.(`Linked ${f}/${w}`);for(let w of d.warnings)o.onOutput?.(`\u26A0 ${w}`)}if(c){let d=r.map((x)=>Bl(x,{packagePath:f,repo:o.repo,branch:o.branch})),w={...o.env??{},OMW_FOCUS_PATHS:o.focusPaths.join(","),OMW_PACKAGE_PATH:f};await Wt(d,{cwd:o.cwd,timeout:o.timeout,env:w,onOutput:o.onOutput})}}}}var Cn=H(()=>{me();gn()});import{useTerminalDimensions as Ll}from"@opentui/solid";function We(t){let e=Ll(),o=()=>Math.max(0,Math.floor((e().width-t.width)/2)),n=()=>Math.max(0,Math.floor((e().height-t.height)/2)),r=()=>React.createElement("box",{x:o(),y:n(),width:t.width,height:t.height,border:!0,borderStyle:"rounded",borderColor:t.borderColor??l.border.active,backgroundColor:t.backgroundColor??l.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:t.gap??0,title:t.title,titleAlignment:"left",position:"absolute"},t.children,React.createElement(O,{when:t.footer},t.footer));return React.createElement(O,{when:t.backdrop,fallback:r()},React.createElement("box",{x:0,y:0,width:e().width,height:e().height,backgroundColor:t.backdropColor??l.bg.overlay,position:"absolute"},r()))}var Io=H(()=>{Rt();Tt()});import{useKeyboard as Al,useTerminalDimensions as Il}from"@opentui/solid";import{basename as Es,resolve as jl}from"path";function Rs(){let t=Et(),e=Ot(),o=Il(),[n,r]=k("input"),[i,s]=k(""),[c,f]=k(""),[a,u]=k("branch"),[h,d]=k(""),[w,x]=k([]),[m,b]=k(""),[S,R]=k([]),[P,M]=k(-1),[st,ct]=k(!1),_=()=>{let z=i().toLowerCase();if(!z)return S().slice(0,10);return S().filter((T)=>T.name.toLowerCase().includes(z)).slice(0,10)};ae(ke(()=>et(),async()=>{try{let z=et(),T=await E.listBranches(z);R(T)}catch{R([])}})),ae(ke(i,()=>{M(-1),ct(i().length>0&&_().length>0)}));let ot=(z,T)=>{x((Z)=>Z.map((dt,A)=>A===z?{...dt,...T}:dt))},et=()=>{let z=e.worktrees()??[],T=t.selectedWorktreePath();return(T?z.find((dt)=>dt.path===T)??z[t.selectedWorktreeIndex()]:z[t.selectedWorktreeIndex()])?.repoPath??t.repoPath()},re=()=>{let z=e.worktrees()??[],T=t.selectedWorktreePath();return(T?z.find((dt)=>dt.path===T)??z[t.selectedWorktreeIndex()]:z[t.selectedWorktreeIndex()])?.repoName??t.repoPath().split("/").pop()??""},G=()=>{let z=i();if(!z)return"";let T=et(),Z=Y(),dt=Bt(Z,T),A=z.replace(/\//g,"-"),Xt=Es(T);return jl(dn(dt.worktreeDir,{repo:Xt,branch:A}))};Al(async(z)=>{if(t.activeTab()!=="add")return;if(t.showCommandPalette())return;let T=z.name;if(T==="escape"){if(n()==="preview"){r("input");return}t.setActiveTab("list"),s(""),f(""),u("branch"),r("input");return}if(n()==="input"){if(T==="tab"){if(st()&&a()==="branch")ct(!1),M(-1);u((Z)=>Z==="branch"?"focus":"branch");return}if(a()==="branch"&&st()&&_().length>0){if(T==="down"||z.sequence==="\x1B[B"){M((Z)=>Math.min(Z+1,_().length-1));return}if(T==="up"||z.sequence==="\x1B[A"){M((Z)=>Math.max(Z-1,-1));return}}if(T==="return"||T==="enter"){if(a()==="branch"&&P()>=0){let Z=_()[P()];if(Z){s(Z.name),ct(!1),M(-1);return}}if(!i())return;ct(!1),d(G()),r("preview");return}if(T==="backspace"){if(a()==="branch")s((Z)=>Z.slice(0,-1));else f((Z)=>Z.slice(0,-1));return}if(z.sequence==="\x15"||z.ctrl&&T==="u"){if(a()==="branch")s("");else f("");return}if(z.sequence==="\x17"||z.ctrl&&T==="w"){if(a()==="branch")s((Z)=>Z.replace(/\S+\s*$/,""));else f((Z)=>Z.replace(/\S+\s*$/,""));return}if(z.sequence&&z.sequence.length===1&&z.sequence.charCodeAt(0)>=32)if(a()==="branch")s((Z)=>Z+z.sequence);else f((Z)=>Z+z.sequence)}if(n()==="preview"){if(T==="return"||T==="enter"){r("creating");let Z=i(),dt=h(),A=et(),Xt=Es(A);try{let xe=Y(),F=Bt(xe,A),nt=[{label:"Creating worktree",status:"pending"}];if(F.autoUpstream)nt.push({label:"Setting upstream",status:"pending"});if(F.copyFiles.length>0)nt.push({label:"Copying files",status:"pending"});if(F.linkFiles.length>0)nt.push({label:"Creating symlinks",status:"pending"});if(F.postCreate.length>0)nt.push({label:"Running hooks",status:"pending"});let pt=c(),U=[];if(pt)U=pt.split(/[,\s]+/).map((rt)=>rt.trim()).filter(Boolean);if(U.length>0)nt.push({label:"Setting focus",status:"pending"});if(U.length>0&&F.monorepo?.hooks&&F.monorepo.hooks.length>0){if(Xe(F.monorepo.hooks,U).length>0)nt.push({label:"Running monorepo hooks",status:"pending"})}x(nt);let Q=0;if(ot(Q,{status:"running"}),await E.add(Z,dt,{createBranch:!0},A),ot(Q,{status:"done"}),Q++,F.autoUpstream){ot(Q,{status:"running"});try{let rt=await E.getDefaultRemote(A);if(await E.remoteBranchExists(Z,rt,A))await E.setUpstream(Z,rt,A),ot(Q,{status:"done",message:`\u2192 ${rt}/${Z}`});else ot(Q,{status:"done",message:"no remote branch"})}catch(rt){ot(Q,{status:"error",message:rt.message})}Q++}if(F.copyFiles.length>0)ot(Q,{status:"running"}),ho(A,dt,F.copyFiles),ot(Q,{status:"done"}),Q++;if(F.linkFiles.length>0)ot(Q,{status:"running"}),uo(A,dt,F.linkFiles),ot(Q,{status:"done"}),Q++;let ft={OMW_BRANCH:Z,OMW_WORKTREE_PATH:dt,OMW_REPO_PATH:A};if(F.postCreate.length>0)ot(Q,{status:"running"}),await Wt(F.postCreate,{cwd:dt,env:ft,onOutput:(rt)=>ot(Q,{message:rt})}),ot(Q,{status:"done"}),Q++;if(U.length>0){ot(Q,{status:"running"});let{valid:rt}=bn(dt,U);if(U=rt,rt.length>0)so(dt,rt),ft.OMW_FOCUS_PATHS=rt.join(",");ot(Q,{status:"done"}),Q++}if(U.length>0&&F.monorepo?.hooks&&F.monorepo.hooks.length>0){ot(Q,{status:"running"});let rt=Xe(F.monorepo.hooks,U);if(rt.length>0)await xo(rt,"postCreate",{cwd:dt,env:ft,repo:Xt,branch:Z,focusPaths:U,mainRepoPath:A,onOutput:(to)=>ot(Q,{message:to})});ot(Q,{status:"done"}),Q++}b("Worktree created successfully!"),r("done"),qe.success(`Worktree created: ${Z}`),e.refetch(),setTimeout(()=>{t.setActiveTab("list"),s(""),f(""),u("branch"),r("input")},1500)}catch(xe){qe.error(xe.message);let nt=w().findIndex((pt)=>pt.status==="running");if(nt>=0)ot(nt,{status:"error",message:xe.message});b(`${xe.message}`),r("error")}return}}if(n()==="error"){if(T==="escape"||T==="return"||T==="enter")r("input"),b("")}});let D=()=>o().width,L=()=>o().height,K=()=>Math.max(50,Math.min(80,D()-4)),tt=4,mt=()=>{if(n()==="input"){let z=st()&&a()==="branch"?_().length*2:0,T=i().length>0?4:0;return Math.max(21+tt,Math.min(21+tt+z+T,L()-4))}if(n()==="preview")return Math.max(13+tt,Math.min((c().length>0?15:13)+tt,L()-4));if(n()==="creating")return Math.max(9+tt,Math.min(w().length*2+7+tt,L()-4));if(n()==="done")return Math.max(11+tt,Math.min((c().length>0?15:13)+tt,L()-4));return Math.max(11+tt,Math.min(11+tt,L()-4))},V=()=>Math.max(K()-4,10),ut=()=>Math.max(V(),20);return React.createElement(We,{width:K(),height:mt(),borderColor:n()==="done"?l.text.success:n()==="error"?l.text.error:l.border.active,backgroundColor:l.bg.surface,gap:1,title:" Create Worktree ",footer:React.createElement(iw,null,React.createElement("box",{height:1,width:V()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(V(),1)))),React.createElement(O,{when:n()==="input"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Tab:switch"),React.createElement("text",{fg:l.text.secondary},"\u2191\u2193:pick"),React.createElement("text",{fg:l.text.secondary},"Enter:confirm"),React.createElement("text",{fg:l.text.secondary},"Esc:cancel"))),React.createElement(O,{when:n()==="preview"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Enter:create"),React.createElement("text",{fg:l.text.secondary},"Esc:back"))),React.createElement(O,{when:n()==="creating"},React.createElement("text",{fg:l.text.secondary},"Creating worktree...")),React.createElement(O,{when:n()==="done"},React.createElement("text",{fg:l.text.secondary},"\u2713 Done \u2014 returning to list")),React.createElement(O,{when:n()==="error"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Enter:retry"),React.createElement("text",{fg:l.text.secondary},"Esc:back"))))},React.createElement(O,{when:n()==="input"},React.createElement("box",{height:1,width:V(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"New Worktree"),React.createElement("text",{x:17,y:0,fg:l.text.secondary},re())),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(V())),React.createElement("text",{fg:a()==="branch"?l.text.accent:l.text.secondary},"Branch name"),React.createElement("box",{width:ut(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.primary},i()),React.createElement(O,{when:a()==="branch"},React.createElement("text",{x:i().length+1,y:0,fg:l.text.accent},"\u2588"))),React.createElement(O,{when:st()&&a()==="branch"&&_().length>0},React.createElement(St,{each:_()},(z,T)=>React.createElement("box",{height:1,width:V(),backgroundColor:T()===P()?l.select.focusedBg:l.bg.surface},React.createElement("text",{x:1,y:0,fg:T()===P()?l.tab.active:l.text.primary},T()===P()?"\u25B8 ":" ",z.name),React.createElement("text",{x:Math.max(1+z.name.length+4,27),y:0,fg:l.text.secondary},z.isRemote?"(remote) ":"",z.lastCommitDate)))),React.createElement("text",{fg:l.text.secondary},"Tab to switch fields \xB7 \u2191\u2193 to select branch"),React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:a()==="focus"?l.text.accent:l.text.secondary},"Focus "),React.createElement("text",{fg:l.text.secondary},"(optional)")),React.createElement("box",{width:ut(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.primary},c()),React.createElement(O,{when:a()==="focus"},React.createElement("text",{x:c().length+1,y:0,fg:l.text.accent},"\u2588"))),React.createElement("text",{fg:l.text.secondary},"comma-separated paths, e.g. apps/web,apps/api"),React.createElement(O,{when:i().length>0},React.createElement("text",{fg:l.text.secondary},"Target path"),React.createElement("text",{fg:l.text.primary},G())),React.createElement("text",{fg:l.text.primary},"Type a branch name, e.g. feature/my-feature")),React.createElement(O,{when:n()==="preview"},React.createElement("box",{height:1,width:V(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Confirm Worktree")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(V())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},h())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Focus")),React.createElement("text",{fg:l.text.accent},c()))),React.createElement("text",{fg:l.text.success},"\u2713 Ready to create. Press Enter to confirm.")),React.createElement(O,{when:n()==="creating"},React.createElement("box",{height:1,width:V(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Creating Worktree")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(V())),React.createElement(St,{each:w()},(z)=>React.createElement("box",{height:1},React.createElement("text",{fg:z.status==="done"?l.text.success:z.status==="running"?l.text.accent:z.status==="error"?l.text.error:l.text.secondary},z.status==="done"?"\u2713":z.status==="running"?"\u27F3":z.status==="error"?"\u2717":"\u25CB"," ",z.label),React.createElement(O,{when:z.message},React.createElement("text",{x:z.label.length+4,y:0,fg:l.text.secondary},z.message))))),React.createElement(O,{when:n()==="done"},React.createElement("box",{height:1,width:V(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.success},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Worktree Created")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(V())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},h())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Focus")),React.createElement("text",{fg:l.text.accent},c()))),React.createElement("text",{fg:l.text.success},"\u2713 ",m())),React.createElement(O,{when:n()==="error"},React.createElement("box",{height:1,width:V(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.error},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Error")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(V())),React.createElement("text",{fg:l.text.error},"\u2717 Failed"),React.createElement("box",{width:ut(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.primary},m().slice(0,Math.max(ut()-3,10)))),React.createElement("text",{fg:l.text.secondary},"Press Enter or Escape to try again")))}var Ms=H(()=>{Rt();te();fe();at();$t();gn();me();le();wr();Cn();cr();Tt();Io()});import{useKeyboard as Gl,useTerminalDimensions as Tl}from"@opentui/solid";function Os(){let t=Et(),e=Ot(),o=Tl(),[n,r]=k(!1),[i,s]=k(""),[c,f]=k(!1),a=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let S=m.find((R)=>R.path===b);if(S)return S}return m[t.selectedWorktreeIndex()]},u=()=>{t.setShowRemove(!1),r(!1),s(""),f(!1)},h=async(m)=>{let b=a();if(!b){u();return}r(!0),s("Removing...");try{let S=Y(),R=Bt(S,b.repoPath);if(R.postRemove.length>0)s("Running postRemove hooks..."),await Wt(R.postRemove,{cwd:b.path,env:{OMW_BRANCH:b.branch??"",OMW_WORKTREE_PATH:b.path,OMW_REPO_PATH:b.repoPath}}).catch(()=>{});await E.remove(b.path,{force:m},b.repoPath),s("Removed successfully!"),qe.success("Worktree removed");let P=e.worktrees()??[],M=t.selectedWorktreeIndex(),st=P[M-1]??P[M+1]??null;if(M>0)t.setSelectedWorktreeIndex(M-1);else t.setSelectedWorktreeIndex(0);t.setSelectedWorktreePath(st?.path??null),e.refetch(),setTimeout(u,1000)}catch(S){let R=S.message;if(!m&&R.includes("dirty"))s("Worktree has changes. Press Enter to force remove."),r(!1),f(!0);else s(`Failed: ${R}`),r(!1),qe.error(`Failed: ${R}`)}};Gl(async(m)=>{if(!t.showRemove())return;if(t.showCommandPalette())return;let b=m.name;if(b==="escape"){u();return}if(c()&&(b==="return"||b==="enter")){f(!1),await h(!0);return}if((b==="return"||b==="enter")&&!n())await h(!1)});let d=()=>a(),w=()=>Math.max(50,Math.min(80,o().width-4)),x=()=>10;return React.createElement(We,{width:w(),height:x(),borderColor:l.border.active,backgroundColor:l.bg.elevated,gap:1,title:" Remove Worktree ",backdrop:!0,footer:React.createElement("box",{flexDirection:"column"},React.createElement(O,{when:!n()&&!c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"[Enter] Confirm"),React.createElement("text",{fg:l.text.secondary},"[Esc] Cancel"))),React.createElement(O,{when:c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"[Enter] Force remove"),React.createElement("text",{fg:l.text.secondary},"[Esc] Cancel"))))},React.createElement(O,{when:!!d()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},d()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},d()?.path)),React.createElement(O,{when:c()},React.createElement("text",{fg:l.text.warning},i())),React.createElement(O,{when:n()},React.createElement("text",{fg:i().startsWith("Failed")?l.text.error:l.text.success},i()))),React.createElement(O,{when:!d()},React.createElement("text",{fg:l.text.secondary},"No worktree selected.")))}var Ws=H(()=>{Rt();te();fe();at();$t();me();cr();Tt();Io()});function Fs(t){let[e,o]=k([]),n=(i)=>{o((s)=>s.filter((c)=>c.id!==i))},r=(i)=>{let s=`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`,c=i.duration??3000;o((f)=>[...f,{...i,id:s}].slice(-5)),setTimeout(()=>{n(s)},c)};return React.createElement(Ds.Provider,{value:{toasts:e,addToast:r,removeToast:n}},t.children)}function $n(){let t=Ke(Ds);if(!t)throw Error("useToast must be used within ToastProvider");return t}var Ds;var Sn=H(()=>{Rt();Ds=Ue()});import{useKeyboard as _l}from"@opentui/solid";function Bs(t){let e=Et(),o=Ot(),n=$n(),[r,i]=k("confirming"),[s,c]=k(""),[f,a]=k(0),u=()=>{let x=o.worktrees()??[],m=e.selectedWorktrees(),b=[];for(let S of m){let R=x.find((P)=>P.path===S);if(R&&!R.isMain)b.push({branch:R.branch??"(detached)",path:R.path,repoPath:R.repoPath})}return b},h=()=>{e.setShowBulkActions(!1),i("confirming"),c(""),a(0)},d=async()=>{let x=u();if(x.length===0){h();return}i("executing"),a(0);let m=[];for(let b=0;b<x.length;b++){let S=x[b];c(`Removing ${S.branch} (${b+1}/${x.length})...`),a(b);try{let R=Y(),P=Bt(R,S.repoPath);if(P.postRemove.length>0)await Wt(P.postRemove,{cwd:S.path,env:{OMW_BRANCH:S.branch,OMW_WORKTREE_PATH:S.path,OMW_REPO_PATH:S.repoPath}}).catch(()=>{});await E.remove(S.path,{force:!1},S.repoPath)}catch(R){m.push(`${S.branch}: ${R.message}`)}}if(Mt(),e.clearSelection(),e.setSelectedWorktreeIndex(0),e.setSelectedWorktreePath(null),o.refetch(),m.length>0)i("error"),c(`Failed: ${m.join("; ")}`),n.addToast({message:`Failed to remove ${m.length} worktree(s)`,type:"error"}),setTimeout(h,3000);else i("done"),c(`Removed ${x.length} worktree(s) successfully!`),n.addToast({message:`Removed ${x.length} worktrees`,type:"success"}),setTimeout(h,1500)};_l(async(x)=>{if(!e.showBulkActions())return;if(e.showCommandPalette())return;let m=x.name;if(r()==="executing")return;if(m==="escape"){h();return}if((m==="return"||m==="enter")&&r()==="confirming")await d()});let w=()=>u().length;return React.createElement("box",{x:0,y:0,width:t.w,height:t.h,backgroundColor:l.bg.base},React.createElement("box",{x:2,y:1,width:t.w-3,height:t.h-2,flexDirection:"column",backgroundColor:l.bg.base},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.error},"Bulk Delete Worktrees")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},"\u2500".repeat(Math.max(t.w-5,10)))),React.createElement("box",{height:1}),React.createElement(O,{when:r()==="confirming"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.warning},`Delete ${w()} worktree(s)?`)),React.createElement("box",{height:1}),React.createElement(St,{each:u().slice(0,Math.max(t.h-10,5))},(x)=>React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:l.text.accent},`\u2022 ${x.branch}`))),React.createElement(O,{when:w()>Math.max(t.h-10,5)},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:l.text.secondary},`... and ${w()-Math.max(t.h-10,5)} more`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Enter:delete all Esc:cancel"))),React.createElement(O,{when:r()==="executing"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.warning},s())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},`Progress: ${f()+1}/${w()}`))),React.createElement(O,{when:r()==="done"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.success},s()))),React.createElement(O,{when:r()==="error"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.error},s())))))}var Ls=H(()=>{Rt();te();Sn();fe();at();$t();me();Tt()});import{useKeyboard as Nl,useTerminalDimensions as Hl}from"@opentui/solid";import{spawnSync as Jl}from"child_process";function As(){let t=Et(),e=Hl(),o=_t(),n=()=>{try{return Y()}catch{return null}},[r,i]=k(n()),[s,c]=k("");Nl((u)=>{if(t.activeTab()!=="config")return;if(t.showCommandPalette())return;let h=u.name;if(h==="e"){let d=process.env.EDITOR??process.env.VISUAL??"vi";ne(),Jl(d,[o],{stdio:"inherit"}),i(n()),c("Config reloaded"),setTimeout(()=>c(""),2000)}if(h==="r")i(n()),c("Reloaded"),setTimeout(()=>c(""),2000);if(h==="i")ne(),i(n()),c("Config initialized"),setTimeout(()=>c(""),2000)});let f=()=>e().width,a=()=>e().height;return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:l.bg.base,flexDirection:"column"},React.createElement("box",{width:"100%",height:"100%",border:!0,borderStyle:"rounded",borderColor:l.border.default,backgroundColor:l.bg.surface,title:" Configuration ",titleAlignment:"left",flexDirection:"column",paddingX:1,paddingY:1},React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:l.text.secondary},"Path:"),React.createElement("text",{fg:l.text.primary},o)),React.createElement(O,{when:!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.warning},"No config file found."),React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:l.text.secondary},"Press"),React.createElement("text",{fg:l.text.accent},"i"),React.createElement("text",{fg:l.text.secondary},"to initialize with defaults.")))),React.createElement(O,{when:!!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.accent},"Defaults"),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"worktreeDir")),React.createElement("text",{fg:l.text.primary},r()?.defaults?.worktreeDir??"../{repo}-{branch}")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"copyFiles")),React.createElement("text",{fg:l.text.primary},"[",(r()?.defaults?.copyFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"linkFiles")),React.createElement("text",{fg:l.text.primary},"[",(r()?.defaults?.linkFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"postCreate")),React.createElement("text",{fg:l.text.primary},"[",(r()?.defaults?.postCreate??[]).join(", "),"]"))),React.createElement("box",null,React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(f()-34,10)))),React.createElement(O,{when:(r()?.repos?.length??0)>0},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.accent},"Repos (",r()?.repos?.length,")"),React.createElement(St,{each:r()?.repos?.slice(0,4)},(u)=>React.createElement("box",{flexDirection:"column",gap:0},React.createElement("text",{fg:l.text.primary},u.path.split("/").pop()??u.path),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:l.text.secondary},"copyFiles")),React.createElement("text",{fg:l.text.primary},(u.copyFiles??[]).length>0?(u.copyFiles??[]).join(", "):"\u2014")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:l.text.secondary},"postCreate")),React.createElement("text",{fg:l.text.primary},(u.postCreate??[]).length>0?(u.postCreate??[]).join(", "):"\u2014")))))),React.createElement(O,{when:(r()?.repos?.length??0)===0},React.createElement("text",{fg:l.text.secondary},"No per-repo configs defined."))),React.createElement(O,{when:!!s()},React.createElement("text",{fg:l.text.success},s()))),React.createElement("box",{width:"100%",height:1,backgroundColor:l.bg.base,flexDirection:"row",gap:2},React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:l.text.secondary},"e"),React.createElement("text",{fg:l.text.primary},":edit")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:l.text.secondary},"r"),React.createElement("text",{fg:l.text.primary},":reload")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:l.text.secondary},"i"),React.createElement("text",{fg:l.text.primary},":init"))))}var Is=H(()=>{Rt();te();$t();Tt()});import{existsSync as Qe,readdirSync as js,rmSync as zl}from"fs";import{basename as gr,dirname as br,join as Gs,resolve as Ze}from"path";function vl(t){let e=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,e)}function Ts(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _s(t){if(!Qe(_t()))return[];let e=t.find((c)=>c.isMain);if(!e)return[];let o=Y(),n=Ze(e.path),r=gr(n);return[o.repos?.find((c)=>Ze(c.path)===n)?.worktreeDir??o.defaults?.worktreeDir].filter((c)=>typeof c==="string").map((c)=>vl(c)).filter((c)=>!br(c).includes("{")&&gr(c).includes("{")).map((c)=>{let f=gr(c),a=`^${Ts(f).replace(/\\\{repo\\\}/g,Ts(r)).replace(/\\\{branch\\\}/g,".+")}$`;return{path:Ze(br(c)),matches:(u)=>new RegExp(a).test(u)}})}function Ns(t){let e=new Set;for(let o of t)if(!o.isMain)e.add(Ze(br(o.path)));return[...e]}function Hs(t){let e=new Set(t.map((n)=>Ze(n.path))),o=new Set;for(let n of _s(t)){if(!Qe(n.path))continue;let r=js(n.path,{withFileTypes:!0}).filter((i)=>i.isDirectory()).filter((i)=>n.matches(i.name)).map((i)=>Ze(Gs(n.path,i.name)));for(let i of r)if(!e.has(i))o.add(i)}for(let n of Ns(t)){if(!Qe(n))continue;let r=js(n,{withFileTypes:!0}).filter((i)=>i.isDirectory()).map((i)=>Ze(Gs(n,i.name)));for(let i of r)if(!e.has(i))o.add(i)}return[...o]}function kl(t){return _s(t).some((e)=>Qe(e.path))||Ns(t).some((e)=>Qe(e))}async function Ul(){let t=Bun.spawn(["git","--version"],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[e,o]=await Promise.all([new Response(t.stdout).text(),t.exited]);if(o!==0)return null;return e.trim().match(/git version (\d+\.\d+(?:\.\d+)?)/)?.[1]??null}async function Kl(){try{return await E.checkVersion(),{name:"Git version",status:"pass",message:`${await Ul()??"unknown"} (>= 2.17 required)`}}catch(e){if(e instanceof Oo)return{name:"Git version",status:"fail",message:e.message};return{name:"Git version",status:"fail",message:`Check failed: ${e.message}`}}}async function ql(){try{let o=(Y().repos??[]).map((n)=>n.path).filter((n)=>!Qe(n));if(o.length>0)return{name:"Configuration",status:"warn",message:"missing repository paths",detail:o};return{name:"Configuration",status:"pass",message:"valid"}}catch(e){return{name:"Configuration",status:"fail",message:`Check failed: ${e.message}`}}}function Vl(t){let o=t.map((n)=>n.path).filter((n)=>!Qe(n));if(o.length>0)return{name:"Stale worktrees",status:"warn",message:"missing worktree paths",detail:o};return{name:"Stale worktrees",status:"pass",message:"none"}}function Xl(t){try{let o=Hs(t);if(o.length===0)return{name:"Orphaned directories",status:"pass",message:kl(t)?"none":"no worktree directory"};return{name:"Orphaned directories",status:"warn",message:"orphaned worktree directories found",detail:o}}catch(o){return{name:"Orphaned directories",status:"fail",message:`Check failed: ${o.message}`}}}function Zl(t){let o=t.filter((r)=>r.isLocked);if(o.length===0)return{name:"Worktree locks",status:"pass",message:"all clear"};return{name:"Worktree locks",status:"warn",message:"locked worktrees present",detail:o.map((r)=>{let i=r.branch??"detached";if(!r.lockReason)return`${i} - ${r.path} (potential stale lock: no reason)`;return`${i} - ${r.path} (reason: ${r.lockReason})`})}}function Ql(t){let o=t.filter((n)=>n.isDirty&&!n.isMain);if(o.length===0)return{name:"Dirty worktrees",status:"pass",message:"none"};return{name:"Dirty worktrees",status:"warn",message:"dirty non-main worktrees found",detail:o.map((n)=>`${n.branch??"detached"} - ${n.path}`)}}async function wo(t){let e=await E.list(t).catch(()=>[]),o=[await Kl(),await ql(),Vl(e),Xl(e),Zl(e),Ql(e)];return{checks:o,healthy:o.every((n)=>n.status==="pass")}}async function Yl(t){try{return await E.prune(t),{action:"Prune stale worktrees",success:!0}}catch(e){return{action:"Prune stale worktrees",success:!1,detail:e.message}}}async function th(t){let e=[];try{let o=Hs(await E.list(t).catch(()=>[]));for(let n of o)try{zl(n,{recursive:!0,force:!0}),e.push({action:"Remove orphaned directory",success:!0,detail:n})}catch(r){e.push({action:"Remove orphaned directory",success:!1,detail:`${n}: ${r.message}`})}}catch(o){e.push({action:"Remove orphaned directories",success:!1,detail:o.message})}return e}async function eh(t){let e=[];try{let n=(await E.list(t)).filter((r)=>r.isLocked&&!r.lockReason);for(let r of n)try{await E.unlock(r.path,t),e.push({action:"Unlock stale lock",success:!0,detail:`${r.branch??"detached"} - ${r.path}`})}catch(i){e.push({action:"Unlock stale lock",success:!1,detail:`${r.path}: ${i.message}`})}}catch(o){e.push({action:"Fix stale locks",success:!1,detail:o.message})}return e}async function yn(t){let e=[];return e.push(await Yl(t)),e.push(...await th(t)),e.push(...await eh(t)),e}var Cr=H(()=>{$t();at();Ct()});import{useKeyboard as oh,useTerminalDimensions as nh}from"@opentui/solid";function Js(){let t=Et(),e=nh(),[o,n]=k(null),[r,i]=k(!0),[s,c]=k(""),[f,a]=k(!1),[u,h]=k([]),d=async()=>{i(!0),c(""),h([]);try{let _=await wo();n(_)}catch(_){c(_.message)}i(!1)},w=async()=>{if(o()?.healthy)return;a(!0);try{let _=await yn();h(_);let ot=await wo();n(ot)}catch(_){c(_.message)}a(!1)};d(),oh((_)=>{if(t.activeTab()!=="doctor")return;if(t.showCommandPalette())return;let ot=_.name;if(ot==="r")d();if(ot==="f"&&!r()&&!f()&&!o()?.healthy)w()});let x=()=>e().width,m=()=>e().height,b=()=>Math.max(50,Math.min(80,x()-4)),S=()=>{let _=st()+ct()+8+(ct()>0?2:0);return Math.max(12,Math.min(_,m()-4))},R=()=>Math.max(b()-4,10),P=(_)=>{if(_==="pass")return"\u2713";if(_==="warn")return"\u26A0";return"\u2717"},M=(_)=>{if(_==="pass")return l.text.success;if(_==="warn")return l.text.warning;return l.text.error},st=()=>o()?.checks.length??0,ct=()=>u().length;return React.createElement(We,{width:b(),height:S(),borderColor:o()?.healthy?l.text.success:o()?l.text.warning:l.border.default,backgroundColor:l.bg.surface,title:" Doctor ",footer:React.createElement(Vw,null,React.createElement("box",{height:1,width:R()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(R(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"r:recheck"),React.createElement(O,{when:!o()?.healthy},React.createElement("text",{fg:l.text.secondary},"f:fix")),React.createElement("text",{fg:l.text.secondary},"Esc:back")))},React.createElement(O,{when:r()},React.createElement("text",{fg:l.text.secondary},"Running health checks...")),React.createElement(O,{when:f()},React.createElement("text",{fg:l.text.accent},"Running auto-fix...")),React.createElement(O,{when:!r()&&!f()&&!!s()},React.createElement("text",{fg:l.text.error},"Error: ",s())),React.createElement(O,{when:!r()&&!f()&&!s()&&!!o()},React.createElement("text",{fg:l.text.accent},"Health Checks"),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(R())),React.createElement(St,{each:o().checks},(_)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:M(_.status)},P(_.status)),React.createElement("text",{x:2,y:0,fg:l.text.primary},_.name,":"),React.createElement("text",{x:_.name.length+4,y:0,fg:l.text.secondary},_.message))}),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(R())),React.createElement("text",{fg:o().healthy?l.text.success:l.text.warning},o().healthy?"\u2713 All checks passed":`${o().checks.filter((_)=>_.status==="fail").length} error(s), ${o().checks.filter((_)=>_.status==="warn").length} warning(s) found`),React.createElement(O,{when:ct()>0},React.createElement("text",{fg:l.text.accent},"Fix Results"),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(R())),React.createElement(St,{each:u()},(_)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:_.success?l.text.success:l.text.error},_.success?"\u2713":"\u2717"),React.createElement("text",{x:2,y:0,fg:l.text.primary},_.action),React.createElement(O,{when:!!_.detail},React.createElement("text",{x:_.action.length+3,y:0,fg:l.text.secondary},"(",_.detail,")")))}))))}var zs=H(()=>{Rt();te();Cr();Tt();Io()});var ks={};xt(ks,{writePin:()=>yr,removePin:()=>Pr,readPin:()=>To,listPinnedWorktrees:()=>Er,isPinned:()=>De});import{statSync as rh,readFileSync as $r,writeFileSync as ih,unlinkSync as sh,mkdirSync as ch,existsSync as Sr}from"fs";import{join as jo,resolve as ah,dirname as vs}from"path";function Go(t){let e=jo(t,".git"),o=rh(e,{throwIfNoEntry:!1});if(!o)return jo(e,"omw-pin");if(o.isDirectory())return jo(e,"omw-pin");let r=$r(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim(),i=ah(t,r);return jo(i,"omw-pin")}function fh(t){let e=Go(t),o=vs(e),n=jo(o,"HEAD"),r=$r(n,"utf-8").trim(),i=r.match(/^ref:\s+refs\/heads\/(.+)$/);return i?i[1]:r}function yr(t,e){let o=Go(t),n={branch:fh(t),pinnedAt:new Date().toISOString(),...e?{reason:e}:{}};ch(vs(o),{recursive:!0}),ih(o,JSON.stringify(n),{encoding:"utf-8",mode:384})}function To(t){let e=Go(t);if(!Sr(e))return null;return JSON.parse($r(e,"utf-8"))}function Pr(t){let e=Go(t);if(!Sr(e))return;sh(e)}function De(t){return Sr(Go(t))}function Er(t){return t.filter((e)=>De(e.path))}var go=()=>{};import{useKeyboard as lh}from"@opentui/solid";function Us(){let t=Et(),e=Ot(),o=()=>e.worktrees()??[],n=()=>t.selectedWorktreeIndex(),r=(u)=>{let h=Math.max(0,Math.min(u,Math.max(o().length-1,0))),d=o()[h];t.setSelectedWorktreeIndex(h),t.setSelectedWorktreePath(d?.path??null)},i=Yt(()=>{let u=o(),h=e.isMultiRepo(),d=[];if(!h){for(let b=0;b<u.length;b++)d.push({type:"worktree",wt:u[b],flatIdx:b});return d}let w=new Map;for(let b of u){let S=w.get(b.repoName);if(S)S.push(b);else w.set(b.repoName,[b])}let x=0,m=!0;for(let[b,S]of w){if(!m)d.push({type:"separator"});m=!1,d.push({type:"header",repoName:b});for(let R of S)d.push({type:"worktree",wt:R,flatIdx:x}),x++}return d}),s=()=>t.selectedWorktrees().size;lh((u)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;let h=u.name,d=o();if(h==="j"||h==="down")r(Math.min(n()+1,d.length-1));if(h==="k"||h==="up")r(Math.max(n()-1,0));if(h==="space"){let w=n(),x=d[w];if(x&&!x.isMain)t.toggleWorktreeSelection(x.path)}if(u.ctrl&&h==="a")t.selectAllNonMain(d.filter((w)=>!w.isMain).map((w)=>w.path))});let c=(u)=>{if(u.isLocked)return"\uD83D\uDD12";if(u.isDirty)return"\u25CF";return"\u2713"},f=(u)=>{if(u.isLocked)return l.text.warning;if(u.isDirty)return l.text.error;return l.text.success},a=(u,h)=>{let d=u.branch??"(detached)",w=Math.max(8,_o-(h?9:7));return d.length>w?d.slice(0,w-1)+"\u2026":d};return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:l.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:0},React.createElement(O,{when:e.loading()},React.createElement("text",{fg:l.text.secondary},"Loading...")),React.createElement(O,{when:!e.loading()},React.createElement(St,{each:i()},(u)=>{if(u.type==="header")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:l.text.accent},React.createElement("b",null,u.repoName)));if(u.type==="separator")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(_o)));let h=u.wt,d=()=>u.flatIdx===n(),w=()=>t.selectedWorktrees().has(h.path);return React.createElement("box",{width:"100%",height:1,backgroundColor:d()?l.select.focusedBg:w()?l.bg.elevated:l.bg.surface,paddingX:1,onMouseDown:()=>r(u.flatIdx)},React.createElement("text",{x:0,y:0,fg:f(h)},c(h)),React.createElement("text",{x:2,y:0,fg:d()?l.tab.active:l.text.primary},a(h,!1)),React.createElement(O,{when:w()},React.createElement("text",{x:_o-1,y:0,fg:l.text.accent},"\u2713")),React.createElement(O,{when:!!kt(h.path)},React.createElement("text",{x:_o-(w()?3:1),y:0,fg:l.text.accent},"S")),React.createElement(O,{when:De(h.path)},React.createElement("text",{x:_o-(w()?5:3)+(kt(h.path)?0:2),y:0,fg:l.text.warning},"P")))}),React.createElement(O,{when:s()>0},React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:l.text.accent},`Selected: ${s()}`)))))}var _o=24;var Ks=H(()=>{Rt();te();fe();Tt();go();Pe()});import{useKeyboard as hh,useTerminalDimensions as uh}from"@opentui/solid";function qs(){let t=Et(),e=Ot(),o=uh(),[n,r]=k(""),[i,s]=k(0),c=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let S=m.find((R)=>R.path===b);if(S)return S}return m[t.selectedWorktreeIndex()]},f=()=>{let m=process.env.VISUAL||process.env.EDITOR;if(m)return m;let b=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let S of b)try{if(Bun.spawnSync(["which",S],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return S}catch{}return null},a=Yt(()=>[{id:"add",label:"Add Worktree",description:"Create a new git worktree",action:()=>{t.setActiveTab("add"),t.setShowCommandPalette(!1)}},{id:"delete",label:"Delete Worktree",description:"Remove the selected worktree",action:()=>{let m=c();if(!m||m.isMain)return;t.setShowRemove(!0),t.setShowCommandPalette(!1)}},{id:"open-editor",label:"Open in Editor",description:"Open selected worktree in IDE",action:()=>{let m=c();if(!m)return;let b=f();if(!b)return;t.setShowCommandPalette(!1),Bun.spawn([b,m.path],{stdout:"inherit",stderr:"inherit"})}},{id:"refresh",label:"Refresh",description:"Reload worktree list",action:()=>{e.refetch(),t.setShowCommandPalette(!1)}},{id:"config",label:"Open Config",description:"View configuration",action:()=>{t.setActiveTab("config"),t.setShowCommandPalette(!1)}},{id:"doctor",label:"Run Doctor",description:"Check worktree health",action:()=>{t.setActiveTab("doctor"),t.setShowCommandPalette(!1)}},...rn.map((m)=>({id:`theme:${m}`,label:`Theme: ${ss[m]}`,description:"Switch color theme",action:()=>{sn(m);try{let b=_t(),S={...Y()};S.theme=m,Lo(b,JSON.stringify(S,null,2))}catch{}t.setShowCommandPalette(!1)}})),{id:"quit",label:"Quit",description:"Exit oh-my-worktree",action:()=>process.exit(0)}]),u=Yt(()=>{let m=n().toLowerCase();if(!m)return a();return a().filter((b)=>b.label.toLowerCase().includes(m)||b.description.toLowerCase().includes(m))});hh((m)=>{if(!t.showCommandPalette())return;let b=m.name;if(b==="escape"){t.setShowCommandPalette(!1),r(""),s(0);return}if(b==="return"||b==="enter"){let S=u()[i()];if(S)S.action();r(""),s(0);return}if(b==="down"||b==="j"){s((S)=>Math.min(S+1,u().length-1));return}if(b==="up"||b==="k"){s((S)=>Math.max(S-1,0));return}if(b==="backspace"){r((S)=>S.slice(0,-1)),s(0);return}if(m.sequence&&m.sequence.length===1&&m.sequence.charCodeAt(0)>=32)r((S)=>S+m.sequence),s(0)});let h=()=>Math.max(50,Math.min(80,o().width-4)),d=()=>Math.max(10,Math.min(u().length+8,o().height-4)),w=()=>h()-4,x=()=>d()-8;return React.createElement(We,{width:h(),height:d(),borderColor:l.border.active,backgroundColor:l.bg.surface,title:" Command Palette ",footer:React.createElement(dg,null,React.createElement("box",{height:1,width:w()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(w(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"\u2191\u2193:navigate"),React.createElement("text",{fg:l.text.secondary},"Enter:run"),React.createElement("text",{fg:l.text.secondary},"Esc:close")))},React.createElement("box",{height:1,width:w(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},n()),React.createElement("text",{x:3+n().length,y:0,fg:l.text.accent},"\u2588")),React.createElement("box",{height:1,width:w()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(w(),1)))),React.createElement("box",{width:w(),height:x(),backgroundColor:l.bg.surface,flexDirection:"column"},React.createElement(St,{each:u().slice(0,x())},(m,b)=>{let S=()=>b()===i();return React.createElement("box",{height:1,width:w(),backgroundColor:S()?l.select.focusedBg:l.bg.surface,onMouseDown:()=>{s(b()),m.action()}},React.createElement("text",{x:2,y:0,fg:S()?l.tab.active:l.text.primary},m.label),React.createElement("text",{x:Math.max(25,m.label.length+4),y:0,fg:l.text.secondary},m.description))}),React.createElement(O,{when:u().length===0},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:l.text.secondary},"No commands found")))))}var Vs=H(()=>{Rt();te();fe();Tt();Io();$t()});import{useTerminalDimensions as ph}from"@opentui/solid";function dh(t){if(t==="success")return"\u2713";if(t==="warning")return"\u26A0";if(t==="error")return"\u2717";return"\u2139"}function mh(t){if(t==="success")return l.text.success;if(t==="warning")return l.text.warning;if(t==="error")return l.text.error;return l.text.primary}function Xs(){let t=ph(),e=()=>Math.min(60,Math.max(24,t().width-4));return React.createElement("box",{x:(()=>Math.max(0,t().width-e()-1))(),y:1,width:e(),height:5,flexDirection:"column"},React.createElement(St,{each:$n().toasts()},(n,r)=>React.createElement("box",{x:0,y:r(),width:e(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:mh(n.type)},`${dh(n.type)} ${n.message}`))))}var Zs=H(()=>{Rt();Sn();Tt()});var tc={};xt(tc,{launchTUI:()=>Sh});import{render as xh,useKeyboard as wh,useTerminalDimensions as gh,useRenderer as bh}from"@opentui/solid";import{resolve as Qs}from"path";function Ch(){let t=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let e of t)try{if(Bun.spawnSync(["which",e],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return e}catch{}return null}function $h(t){let e=Et(),o=Ot(),n=bh(),[r,i]=k(!1),s=gh(),c=()=>{let m=o.worktrees()??[],b=e.selectedWorktreePath();if(b){let S=m.find((R)=>R.path===b);if(S)return S}return m[e.selectedWorktreeIndex()]};ae(()=>{let m=o.worktrees()??[],b=m.map((M)=>M.path);if(e.pruneSelectedWorktrees(b),m.length===0){if(e.selectedWorktreeIndex()!==0)e.setSelectedWorktreeIndex(0);if(e.selectedWorktreePath()!==null)e.setSelectedWorktreePath(null);return}let S=e.selectedWorktreePath();if(S){let M=m.findIndex((st)=>st.path===S);if(M>=0){if(M!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(M);return}}let R=Math.min(e.selectedWorktreeIndex(),m.length-1),P=m[R]?.path??null;if(R!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(R);if(P!==e.selectedWorktreePath())e.setSelectedWorktreePath(P)}),wh((m)=>{if(e.showCommandPalette())return;let b=m.name;if(m.ctrl&&b==="p"){e.setShowCommandPalette(!0);return}if(b==="escape"){if(e.showBulkActions()){e.setShowBulkActions(!1);return}if(e.showDetailView()){e.setShowDetailView(!1);return}if(e.showRemove()){e.setShowRemove(!1);return}if(r()){i(!1);return}if(e.activeTab()!=="list"){e.setActiveTab("list");return}}if(e.showBulkActions())return;if(e.showRemove())return;if(e.activeTab()==="add")return;if(e.activeTab()==="list"){if(e.showDetailView())return;if(b==="a"){e.setActiveTab("add");return}if(b==="r"){o.refetch();return}if(b==="d"){let S=c();if(S&&!S.isMain)e.setShowRemove(!0);return}if(b==="o"){let S=c();if(S){let R=process.env.VISUAL||process.env.EDITOR||Ch();if(R)Bun.spawn([R,S.path],{stdout:"inherit",stderr:"inherit"})}return}}if(b==="h"){e.setActiveTab("doctor");return}if(b==="q"||b==="Q")n.destroy();if(b==="?")i((S)=>!S)});let f=()=>s().width,a=()=>s().height,u=()=>t.repoPath.split("/").pop()??"",h=()=>{let m=o.repoNames();if(m.length<=1)return u();return`${m.length} repos`},d=()=>{let m=o.worktrees()??[];return`${u()} \xB7 ${m.length} worktrees`},w=()=>{return` Worktrees (${(o.worktrees()??[]).length}) `},x=()=>f()-Ys-1;return React.createElement("box",{width:f(),height:a(),backgroundColor:l.bg.base,flexDirection:"column"},React.createElement("box",{height:1,backgroundColor:l.bg.overlay},React.createElement("text",{x:1,y:0,fg:l.text.accent},"\uD83C\uDF33 oh-my-worktree"),React.createElement("text",{x:f()-h().length-2,y:0,fg:l.text.secondary},h())),React.createElement("box",{flexGrow:1,flexDirection:"row"},React.createElement("box",{width:Ys,flexShrink:0,backgroundColor:l.bg.surface,border:!0,borderStyle:"rounded",borderColor:l.border.default,title:w(),titleAlignment:"left"},React.createElement(Us,null)),React.createElement("box",{width:1}),React.createElement("box",{flexGrow:1,backgroundColor:l.bg.base},React.createElement(O,{when:e.activeTab()!=="config"&&!e.showRemove()&&!e.showBulkActions()},React.createElement(ps,null)),React.createElement(O,{when:e.activeTab()==="list"&&e.showBulkActions()},React.createElement(Bs,{w:x(),h:a()-3})),React.createElement(O,{when:e.activeTab()==="config"},React.createElement(As,null)))),React.createElement(Xs,null),React.createElement("toaster",{position:"bottom-right"}),React.createElement("box",{height:1,backgroundColor:l.bg.overlay},React.createElement("text",{x:0,y:0,fg:l.border.subtle},"\u2500".repeat(f()))),React.createElement("box",{height:1,backgroundColor:l.bg.overlay},React.createElement("text",{x:1,y:0,fg:l.text.secondary},"d:delete a:add o:open r:refresh ^P:cmd h:health q:quit")),React.createElement(O,{when:r()&&!e.showCommandPalette()},React.createElement("box",{x:Math.max(0,Math.floor((f()-Math.max(40,Math.min(60,f()-4)))/2)),y:Math.max(0,Math.floor((a()-14)/2)),width:Math.max(40,Math.min(60,f()-4)),height:14,border:!0,borderStyle:"rounded",borderColor:l.border.active,backgroundColor:l.bg.elevated,title:" Keyboard Shortcuts ",titleAlignment:"left",flexDirection:"column",paddingX:1,paddingY:1,position:"absolute"},React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"q"),React.createElement("text",{x:8,fg:l.text.primary},"Quit")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"j/k"),React.createElement("text",{x:8,fg:l.text.primary},"Navigate list")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"a"),React.createElement("text",{x:8,fg:l.text.primary},"Add worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"d"),React.createElement("text",{x:8,fg:l.text.primary},"Delete worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"r"),React.createElement("text",{x:8,fg:l.text.primary},"Refresh list")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"Ctrl+P"),React.createElement("text",{x:8,fg:l.text.primary},"Command palette")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"?"),React.createElement("text",{x:8,fg:l.text.primary},"Toggle help")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.accent},"Press ? to close")))),React.createElement(O,{when:e.activeTab()==="add"},React.createElement(Rs,null)),React.createElement(O,{when:e.activeTab()==="doctor"},React.createElement(Js,null)),React.createElement(O,{when:e.showRemove()},React.createElement(Os,null)),React.createElement(O,{when:e.showCommandPalette()},React.createElement(qs,null)))}async function Sh(){if(process.stdout.isTTY)process.stdout.write("\x1B]0;Oh My Worktree\x07");let t=await E.getMainRepoPath().catch(()=>process.cwd()),e=[t];try{let o={...Y()},n=Re(o),r=new Set([Qs(t)]);for(let i of n){let s=Qs(i);if(!r.has(s))r.add(s),e.push(i)}if(o.theme&&rn.includes(o.theme))sn(o.theme)}catch{}await xh(()=>React.createElement(os,{repoPath:t,repoPaths:e},React.createElement(is,{repoPaths:e},React.createElement(Fs,null,React.createElement($h,{repoPath:t})))),{exitOnCtrlC:!0,useMouse:!0})}var Ys=28;var ec=H(()=>{Rt();te();fe();at();ds();Ms();Ws();Ls();Is();zs();Ks();Tt();Vs();Sn();Zs();$t()});import{existsSync as _g,mkdirSync as yh,readFileSync as Ph,statSync as Eh,writeFileSync as Rh}from"fs";import{dirname as Mh,join as Pn,resolve as Oh}from"path";function Wh(t){let e=Pn(t,".git"),o=Eh(e,{throwIfNoEntry:!1});if(!o)return Pn(e,"omw-pr");if(o.isDirectory())return Pn(e,"omw-pr");let r=Ph(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim(),i=Oh(t,r);return Pn(i,"omw-pr")}function oc(t,e){let o=Wh(t);yh(Mh(o),{recursive:!0}),Rh(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}var nc=()=>{};import{appendFileSync as Dh,existsSync as Fh,mkdirSync as Bh,readFileSync as Rr,rmSync as Lh,statSync as Ah,writeFileSync as Ih}from"fs";import{dirname as jh,join as En,resolve as Gh}from"path";function Mr(t){let e=En(t,".git"),o=Ah(e,{throwIfNoEntry:!1});if(!o)return En(e,"omw-activity.log");if(o.isDirectory())return En(e,"omw-activity.log");let r=Rr(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim(),i=Gh(t,r);return En(i,"omw-activity.log")}function Ut(t,e){let o=Mr(t);Bh(jh(o),{recursive:!0}),Dh(o,`${JSON.stringify(e)}
16
- `,{encoding:"utf-8",mode:384});let n=Rr(o,"utf-8").split(/\r?\n/).filter(Boolean);if(n.length>Th){let r=n.slice(-_h);Ih(o,`${r.join(`
3
+ var Ma=Object.defineProperty;var Oa=(t)=>t;function Wa(t,e){this[t]=Oa.bind(null,e)}var xt=(t,e)=>{for(var o in e)Ma(t,o,{get:e[o],enumerable:!0,configurable:!0,set:Wa.bind(e,o)})};var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var le=import.meta.require;function Ji(t){if(t instanceof Error)return t;return Error(typeof t==="string"?t:"Unknown error",{cause:t})}function zi(t,e=Ct){let o=e&&e.context&&e.context[Sf],n=Ji(t);if(!o)throw n;try{for(let r of o)r(n)}catch(r){zi(r,e&&e.owner||null)}}function Pf(){let t={owner:Ct,context:Ct?Ct.context:null,owned:null,cleanups:null};if(Ct)if(!Ct.owned)Ct.owned=[t];else Ct.owned.push(t);return t}function k(t,e){return[()=>t,(o)=>{return t=typeof o==="function"?o(t):o}]}function pe(t,e){}function ne(t,e){Ct=Pf();let o;try{o=t(e)}catch(n){zi(n)}finally{Ct=Ct.owner}return()=>o}function Qe(t,e,o={}){let n=Array.isArray(t),r=o.defer;return()=>{if(r)return;let i;if(n){i=[];for(let s=0;s<t.length;s++)i.push(t[s]())}else i=t();return e(i)}}function cn(t){if(Ct)if(!Ct.cleanups)Ct.cleanups=[t];else Ct.cleanups.push(t);return t}function Ye(t){let e=Symbol("context");return{id:e,Provider:Rf(e),defaultValue:t}}function to(t){return Ct&&Ct.context&&Ct.context[t.id]!==void 0?Ct.context[t.id]:t.defaultValue}function yf(t){let e=ne(()=>ir(t()));return e.toArray=()=>{let o=e();return Array.isArray(o)?o:o!=null?[o]:[]},e}function ir(t){if(typeof t==="function"&&!t.length)return ir(t());if(Array.isArray(t)){let e=[];for(let o=0;o<t.length;o++){let n=ir(t[o]);Array.isArray(n)?e.push.apply(e,n):e.push(n)}return e}return t}function Rf(t){return function(o){return ne(()=>{return Ct.context={...Ct.context,[t]:o.value},yf(()=>o.children)})}}function Hi(t){let e=String(t),o=e.length-1;return ue.context.id+(o?String.fromCharCode(96+o):"")+e}function Ef(t,e){let o=t.each||[],n=o.length,r=t.children;if(n){let i=Array(n);for(let s=0;s<n;s++)i[s]=e(r,o[s],s);return i}return t.fallback}function St(t){return Ef(t,(e,o,n)=>e(o,()=>n))}function O(t){let e;return t.when?typeof(e=t.children)==="function"?e(t.keyed?t.when:()=>t.when):e:t.fallback||""}function vi(t,e,o={}){if(typeof e!=="function")o=e||{},e=t,t=!0;let n=new Set,r=ue.getNextContextId(),i={},s=o.storage?o.storage(o.initialValue)[0]():o.initialValue,c,u;if(ue.context.async&&o.ssrLoadFrom!=="initial"){if(i=ue.context.resources[r]||(ue.context.resources[r]={}),i.ref){if(!i.data&&!i.ref[0]._loading&&!i.ref[0].error)i.ref[1].refetch();return i.ref}}let a=()=>{if(u)throw u;let x=o.ssrLoadFrom!=="initial"&&ue.context.async&&"data"in ue.context.resources[r];if(!x&&Lo)Lo.push(r);if(!x&&l._loading){let m=to(Mf);if(m)m.resources.set(r,l),n.add(m)}return x},l=()=>{return a()?ue.context.resources[r].data:s},h=()=>{return a(),l._loading};l._loading=!1,l.error=void 0,l.state="initialValue"in o?"ready":"unresolved",Object.defineProperties(l,{latest:{get(){return l()}},loading:{get(){return h()}}});function d(){let x=ue.context;if(!x.async)return l._loading=!!(typeof t==="function"?t():t);if(x.resources&&r in x.resources&&"data"in x.resources[r]){s=x.resources[r].data;return}let m;try{if(Lo=[],m=typeof t==="function"?t():t,Lo.length)return}finally{Lo=null}if(!c){if(m==null||m===!1)return;c=e(m,{value:s})}if(c!=null&&typeof c==="object"&&"then"in c){if(l._loading=!0,l.state="pending",c=c.then((b)=>{return l._loading=!1,l.state="ready",x.resources[r].data=b,c=null,Ni(n),b}).catch((b)=>{throw l._loading=!1,l.state="errored",l.error=u=Ji(b),c=null,Ni(n),u}),x.serialize)x.serialize(r,c,o.deferStream);return c}if(x.resources[r].data=c,x.serialize)x.serialize(r,c);return c=null,x.resources[r].data}if(o.ssrLoadFrom!=="initial")d();let g=[l,{refetch:d,mutate:(x)=>s=x}];if(c)i.ref=g;return g}function Of(t){for(let e of t.resources.values())if(e._loading)return!1;return!0}function Ni(t){for(let e of t){if(!Of(e))continue;e.completed(),t.delete(e)}}var pm,dm,mm,Sf,Ct=null,ue,Mf,Lo=null;var Et=N(()=>{pm=Symbol("solid-proxy"),dm=Symbol("solid-track"),mm=Symbol("solid-dev-component"),Sf=Symbol("error");ue={context:void 0,getContextId(){if(!this.context)throw Error("getContextId cannot be used under non-hydrating context");return Hi(this.context.count)},getNextContextId(){if(!this.context)throw Error("getNextContextId cannot be used under non-hydrating context");return Hi(this.context.count++)}};Mf=Ye()});function ki(t){return typeof t==="object"&&t!==null&&"frames"in t&&"interval"in t&&Array.isArray(t.frames)}function Ui(t){return typeof t==="object"&&t!==null&&"label"in t&&"onClick"in t}function sr(t,e){switch(t){case"success":return e.success;case"error":return e.error;case"warning":return e.warning;case"info":return e.info;case"loading":return cr(e.loading);default:return""}}function cr(t){if(ki(t))return t.frames[0]??"\u25CC";return t}function ar(t){return ki(t)?t:null}var Wf,Ki;var Vi=N(()=>{Wf={frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"],interval:100},Ki={success:"\u2713",error:"\u2717",warning:"!",info:"\u2139",loading:Wf,close:"\xD7"}});import{BoxRenderable as fn,TextAttributes as Df,TextRenderable as Ao,parseColor as Ff}from"@opentui/core";function jf(t){return t!==null&&typeof t==="object"&&"ok"in t&&typeof t.ok==="boolean"&&"status"in t&&typeof t.status==="number"}function Nf(t,e={}){let[o,n]=t.split("-"),r={position:"absolute"};if(o==="top")r.top=e.top??an.top;else r.bottom=e.bottom??an.bottom;if(n==="left")r.left=e.left??an.left,r.alignItems="flex-start";else if(n==="center")r.left=0,r.width="100%",r.alignItems="center";else r.right=e.right??an.right,r.alignItems="flex-end";return r}function Jf(t){return t.includes("center")}function zf(t){return t.startsWith("top")}function vf(t,e={top:0,right:0,bottom:0,left:0}){if(!t)return{...e};let{padding:o,paddingX:n,paddingY:r}=t;return{top:t.paddingTop??r??o??e.top,right:t.paddingRight??n??o??e.right,bottom:t.paddingBottom??r??o??e.bottom,left:t.paddingLeft??n??o??e.left}}function kf(...t){let e={};for(let o of t){if(!o)continue;Object.assign(e,o)}return e}function qi(t,e,o){let n=fr.style,r=fr[t]?.style,i=e?.style,s=e?.[t]?.style,c=kf(n,r,i,s,o);if(c.border===!1)delete c.borderStyle,delete c.borderColor;return c}function Xi(t,e,o){if(o!==void 0)return o;let n=e?.[t]?.duration;if(n!==void 0)return n;if(e?.duration!==void 0)return e.duration;return fr.duration}var Bf,Lf=200,Zi=60,an,Af,fr,If=1,Tf=class{subscribers=[];toasts=[];dismissedToasts=new Set;_activeToasts=[];_updateActiveToastsCache=()=>{let t=this.toasts.filter((e)=>!this.dismissedToasts.has(e.id));if(t.length!==this._activeToasts.length||t.some((e,o)=>e!==this._activeToasts[o]))this._activeToasts=t};subscribe=(t)=>{return this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);if(e>-1)this.subscribers.splice(e,1)}};publish=(t)=>{for(let e of this.subscribers)e(t)};addToast=(t)=>{this.toasts=[...this.toasts,t],this._updateActiveToastsCache(),this.publish(t)};create=(t)=>{let{message:e,...o}=t,n=typeof t.id==="number"||t.id&&t.id.length>0?t.id:If++,r=this.toasts.find((s)=>s.id===n),i=t.dismissible===void 0?!0:t.dismissible;if(this.dismissedToasts.has(n))this.dismissedToasts.delete(n);if(r)this.toasts=this.toasts.map((s)=>{if(s.id===n)return this.publish({...s,...t,id:n,title:e}),{...s,...t,id:n,dismissible:i,title:e};return s}),this._updateActiveToastsCache();else this.addToast({title:e,...o,dismissible:i,id:n,type:t.type??"default"});return n};dismiss=(t)=>{if(t!==void 0)this.dismissedToasts.add(t),this._updateActiveToastsCache(),setTimeout(()=>{for(let e of this.subscribers)e({id:t,dismiss:!0})},0);else{for(let e of this.toasts){this.dismissedToasts.add(e.id);for(let o of this.subscribers)o({id:e.id,dismiss:!0})}this._updateActiveToastsCache()}return t};message=(t,e)=>{return this.create({...e,message:t,type:"default"})};error=(t,e)=>{return this.create({...e,message:t,type:"error"})};success=(t,e)=>{return this.create({...e,message:t,type:"success"})};info=(t,e)=>{return this.create({...e,message:t,type:"info"})};warning=(t,e)=>{return this.create({...e,message:t,type:"warning"})};loading=(t,e)=>{return this.create({...e,message:t,type:"loading"})};promise=(t,e)=>{if(!e)return;let o;if(e.loading!==void 0)o=this.create({...e,type:"loading",message:e.loading,description:typeof e.description!=="function"?e.description:void 0});let n=t instanceof Function?t():t,r=o!==void 0,i,s=n.then(async(u)=>{if(i=["resolve",u],jf(u)&&!u.ok){r=!1;let a=typeof e.error==="function"?await e.error(`HTTP error! status: ${u.status}`):e.error,l=typeof e.description==="function"?await e.description(`HTTP error! status: ${u.status}`):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:l,...h})}else if(u instanceof Error){r=!1;let a=typeof e.error==="function"?await e.error(u):e.error,l=typeof e.description==="function"?await e.description(u):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:l,...h})}else if(e.success!==void 0){r=!1;let a=typeof e.success==="function"?await e.success(u):e.success,l=typeof e.description==="function"?await e.description(u):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"success",description:l,...h})}}).catch(async(u)=>{if(i=["reject",u],e.error!==void 0){r=!1;let a=typeof e.error==="function"?await e.error(u):e.error,l=typeof e.description==="function"?await e.description(u):e.description,h=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:l,...h})}}).finally(()=>{if(r)this.dismiss(o),o=void 0;e.finally?.()}),c=()=>new Promise((u,a)=>s.then(()=>i[0]==="reject"?a(i[1]):u(i[1])).catch(a));if(typeof o!=="string"&&typeof o!=="number")return{unwrap:c};return Object.assign(o,{unwrap:c})};getActiveToasts=()=>{return this._activeToasts}},At,_f=(t,e)=>At.message(t,e),Gf=()=>At.toasts,Hf=()=>At.getActiveToasts(),eo,Uf,Qi;var Yi=N(()=>{Vi();Bf={SHORT:2000,DEFAULT:4000,LONG:6000,EXTENDED:1e4,PERSISTENT:1/0},an={top:1,right:2,bottom:1,left:2},Af={border:!0,borderStyle:"single",borderColor:"#333333",minHeight:3,backgroundColor:"#1a1a1a",foregroundColor:"#ffffff",mutedColor:"#6b7280"},fr={style:Af,duration:Bf.DEFAULT,default:{style:{borderColor:"#333333"}},success:{style:{borderColor:"#22c55e"}},error:{style:{borderColor:"#ef4444"}},warning:{style:{borderColor:"#f59e0b"}},info:{style:{borderColor:"#3b82f6"}},loading:{style:{borderColor:"#6b7280"}}};At=new Tf,eo=Object.assign(_f,{success:At.success,info:At.info,warning:At.warning,error:At.error,message:At.message,promise:At.promise,dismiss:At.dismiss,loading:At.loading},{getHistory:Gf,getToasts:Hf});Uf=class extends fn{_toast;_icons;_toastOptions;_computedStyle;_closeButton;_onRemove;_remainingTime;_closeTimerStartTime=0;_lastCloseTimerStartTime=0;_timerHandle=null;_paused=!1;_dismissed=!1;_spinnerHandle=null;_spinnerFrameIndex=0;_spinnerConfig=null;_iconText=null;_contentBox=null;_titleText=null;_descriptionText=null;_actionsBox=null;constructor(t,e){let o=qi(e.toast.type,e.toastOptions,e.toast.style),n=Xi(e.toast.type,e.toastOptions,e.toast.duration),r=vf(o,{top:0,right:1,bottom:0,left:1});super(t,{id:`toast-${e.toast.id}`,flexDirection:"row",gap:1,border:o.border,borderStyle:o.borderStyle,borderColor:o.borderColor,customBorderChars:o.customBorderChars,backgroundColor:o.backgroundColor,minHeight:o.minHeight,maxWidth:o.maxWidth??Zi,minWidth:o.minWidth,paddingTop:r.top,paddingRight:r.right,paddingBottom:r.bottom,paddingLeft:r.left,onMouseOver:()=>this.pause(),onMouseOut:()=>this.resume()});if(this._toast=e.toast,this._icons=e.icons===!1?!1:{...Ki,...e.icons},this._toastOptions=e.toastOptions,this._computedStyle=o,this._closeButton=e.closeButton,this._onRemove=e.onRemove,this._remainingTime=n,this.setupContent(),this._remainingTime!==1/0&&this._toast.type!=="loading")this.startTimer();if(this._toast.type==="loading")this.startSpinner()}setupContent(){let t=this.ctx,e=this._toast,o=this._computedStyle,n=this._icons,r=o.iconColor??o.borderColor,i=e.type==="loading";if(i&&n!==!1)this._spinnerConfig=ar(n.loading);let s=e.icon??(n===!1?void 0:i?cr(n.loading):sr(e.type,n));if(s)this._iconText=new Ao(t,{id:`${this.id}-icon`,content:s,fg:r,flexShrink:0,paddingTop:0,paddingBottom:0}),this.add(this._iconText);this._contentBox=new fn(t,{id:`${this.id}-content`,flexDirection:"column",flexGrow:1,flexShrink:1,gap:0});let c=typeof e.title==="function"?e.title():e.title;if(c)this._titleText=new Ao(t,{id:`${this.id}-title`,content:c,fg:o.foregroundColor,attributes:Df.BOLD,wrapMode:"word"}),this._contentBox.add(this._titleText);let u=typeof e.description==="function"?e.description():e.description;if(u)this._descriptionText=new Ao(t,{id:`${this.id}-description`,content:u,fg:o.mutedColor,wrapMode:"word"}),this._contentBox.add(this._descriptionText);if(this.add(this._contentBox),e.action){if(this._actionsBox=new fn(t,{id:`${this.id}-actions`,flexDirection:"row",gap:1,flexShrink:0,alignItems:"center"}),e.action&&Ui(e.action)){let a=new Ao(t,{id:`${this.id}-action`,content:`[${e.action.label}]`,fg:o.foregroundColor,onMouseUp:()=>e.action?.onClick?.()});this._actionsBox.add(a)}this.add(this._actionsBox)}if((e.closeButton??this._closeButton)&&e.dismissible!==!1){let a=n===!1?"\xD7":n.close,l=new Ao(t,{id:`${this.id}-close`,content:a,fg:o.mutedColor,flexShrink:0,onMouseUp:()=>this.dismiss()});this.add(l)}}startTimer(){if(this._remainingTime===1/0)return;this._closeTimerStartTime=Date.now(),this._timerHandle=setTimeout(()=>{this._toast.onAutoClose?.(this._toast),this.dismiss()},this._remainingTime)}pause(){if(this._paused||this._remainingTime===1/0)return;if(this._paused=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;if(this._lastCloseTimerStartTime<this._closeTimerStartTime){let t=Date.now()-this._closeTimerStartTime;this._remainingTime=Math.max(0,this._remainingTime-t)}this._lastCloseTimerStartTime=Date.now()}resume(){if(!this._paused||this._remainingTime===1/0)return;this._paused=!1,this.startTimer()}startSpinner(){if(this._spinnerHandle||!this._spinnerConfig)return;let{frames:t,interval:e}=this._spinnerConfig;this._spinnerHandle=setInterval(()=>{this._spinnerFrameIndex=(this._spinnerFrameIndex+1)%t.length;let o=t[this._spinnerFrameIndex];if(this._iconText&&o)this._iconText.content=o,this.requestRender()},e)}stopSpinner(){if(this._spinnerHandle)clearInterval(this._spinnerHandle),this._spinnerHandle=null}dismiss(){if(this._dismissed)return;if(this._dismissed=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),this._toast.onDismiss?.(this._toast),At.dismiss(this._toast.id),setTimeout(()=>{this._onRemove?.(this._toast)},Lf)}updateToast(t){this._toast=t;let e=qi(t.type,this._toastOptions,t.style);if(this._computedStyle=e,e.borderColor)this.borderColor=e.borderColor;if(e.customBorderChars)this.customBorderChars=e.customBorderChars;let o=e.iconColor??e.borderColor;if(this._iconText){let i=t.icon??(this._icons===!1?void 0:sr(t.type,this._icons));if(i)this._iconText.content=i;if(o)this._iconText.fg=Ff(o)}if(this._titleText){let i=typeof t.title==="function"?t.title():t.title;if(i)this._titleText.content=i}if(this._descriptionText){let i=typeof t.description==="function"?t.description():t.description;if(i)this._descriptionText.content=i}let n=this._spinnerHandle!==null,r=t.type==="loading";if(n&&!r)this.stopSpinner(),this._spinnerConfig=null;else if(!n&&r){if(this._icons!==!1)this._spinnerConfig=ar(this._icons.loading);this.startSpinner()}if(t.type!=="loading"){if(this._timerHandle)clearTimeout(this._timerHandle);if(this._remainingTime=Xi(t.type,this._toastOptions,t.duration),this._remainingTime!==1/0)this.startTimer()}this.requestRender()}get toast(){return this._toast}get isDismissed(){return this._dismissed}destroy(){if(this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),super.destroy()}},Qi=class extends fn{_options={};_toastRenderables=new Map;_unsubscribe=null;constructor(t,e={}){super(t,{id:"toaster",flexDirection:"column",gap:1,zIndex:9999});this._options=e,this.applyLayoutOptions(),this.subscribe()}applyLayoutOptions(){let t=this._options.position??"bottom-right",e=Nf(t,this._options.offset??{}),o=Jf(t);if(Object.assign(this,e),super.gap=this._options.gap??1,!o)super.maxWidth=this._options.maxWidth??Zi}isToastPosition(t){return t==="top-left"||t==="top-center"||t==="top-right"||t==="bottom-left"||t==="bottom-center"||t==="bottom-right"}set position(t){if(this.isToastPosition(t))this._options.position=t,this.applyLayoutOptions();else super.position=t}set offset(t){this._options.offset=t,this.applyLayoutOptions()}set gap(t){this._options.gap=t,super.gap=t}set visibleToasts(t){this._options.visibleToasts=t}set closeButton(t){this._options.closeButton=t}set icons(t){this._options.icons=t}set stackingMode(t){this._options.stackingMode=t}set maxWidth(t){this._options.maxWidth=t,super.maxWidth=t}set toastOptions(t){this._options.toastOptions=t}subscribe(){this._unsubscribe=At.subscribe((t)=>{if("dismiss"in t&&t.dismiss)this.removeToast(t.id);else this.addOrUpdateToast(t)})}addOrUpdateToast(t){let e=this._toastRenderables.get(t.id);if(e){e.updateToast(t);return}if((this._options.stackingMode??"single")==="single")for(let[n]of this._toastRenderables)this.removeToast(n);else{let n=this._options.visibleToasts??3,r=this._toastRenderables.size;if(r>=n){let i=r-n+1,s=Array.from(this._toastRenderables.keys());for(let c=0;c<i;c++){let u=s[c];if(u!==void 0)this.removeToast(u)}}}let o=new Uf(this.ctx,{toast:t,icons:this._options.icons,toastOptions:this._options.toastOptions,closeButton:this._options.closeButton,onRemove:(n)=>this.handleToastRemoved(n)});if(this._toastRenderables.set(t.id,o),zf(this._options.position??"bottom-right"))this.add(o);else this.add(o,0);this.requestRender()}removeToast(t){let e=this._toastRenderables.get(t);if(e)e.dismiss()}handleToastRemoved(t){let e=this._toastRenderables.get(t.id);if(e)this._toastRenderables.delete(t.id),this.remove(e.id),e.destroy(),this.requestRender()}get toastCount(){return this._toastRenderables.size}dismissAll(){for(let[t]of this._toastRenderables)this.removeToast(t)}destroy(){this._unsubscribe?.();for(let[,t]of this._toastRenderables)t.destroy();this._toastRenderables.clear(),super.destroy()}}});import{createElement as Em,extend as Kf,spread as Mm}from"@opentui/solid";var lr=N(()=>{Yi();Kf({toaster:Qi})});function es(t){let[e,o]=k("list"),[n,r]=k(0),[i,s]=k(null),[c,u]=k(!1),[a,l]=k(!1),[h,d]=k(!1),[g,x]=k(new Set),[m,b]=k(!1),S=(it)=>{let st=new Set(g());if(st.has(it))st.delete(it);else st.add(it);x(st)},R=(it)=>{x(new Set(it))},y=(it)=>{let st=new Set(it),G=g(),ot=new Set;for(let et of G)if(st.has(et))ot.add(et);if(ot.size!==G.size)x(ot)},M=()=>{x(new Set)};return React.createElement(ts.Provider,{value:{activeTab:e,setActiveTab:o,selectedWorktreeIndex:n,setSelectedWorktreeIndex:r,selectedWorktreePath:i,setSelectedWorktreePath:s,showRemove:c,setShowRemove:u,showCommandPalette:a,setShowCommandPalette:l,showDetailView:h,setShowDetailView:d,repoPath:()=>t.repoPath,repoPaths:()=>t.repoPaths,selectedWorktrees:g,toggleWorktreeSelection:S,selectAllNonMain:R,pruneSelectedWorktrees:y,clearSelection:M,showBulkActions:m,setShowBulkActions:b}},t.children)}function Rt(){let t=to(ts);if(!t)throw Error("useApp must be used within AppProvider");return t}var ts;var re=N(()=>{Et();ts=Ye()});var Gt,Io,hr,jo;var Zt=N(()=>{Gt=class Gt extends Error{exitCode;stderr;command;constructor(t,e,o,n){super(t);this.exitCode=e;this.stderr=o;this.command=n;this.name="GitError"}};Io=class Io extends Error{installed;required;constructor(t,e){super(`git version ${t} is below minimum required ${e}`);this.installed=t;this.required=e;this.name="GitVersionError"}};hr=class hr extends Error{branch;reason;constructor(t,e,o){super(t);this.branch=e;this.reason=o;this.name="ArchiveError"}};jo=class jo extends Error{path;reason;constructor(t,e,o){super(t);this.path=e;this.reason=o;this.name="ImportError"}}});import{resolve as os,dirname as Vf}from"path";import{mkdirSync as qf,existsSync as Xf}from"fs";function To(t){let e=ln.get(t);if(!e)return;if(Date.now()>e.expires){ln.delete(t);return}return e.data}function ie(t,e,o=Zf){return ln.set(t,{data:e,expires:Date.now()+o}),e}function Mt(){ln.clear()}class E{static gitVersionChecked=!1;static async run(t,e){let o=Bun.spawn(["git",...t],{cwd:e??Bun.cwd,stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[n,r,i]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(i!==0)throw new Gt(`git ${t[0]} failed: ${r.trim()}`,i,r.trim(),`git ${t.join(" ")}`);return n.trim()}static async exec(t,e){return this.run(t,e)}static async checkVersion(){if(this.gitVersionChecked)return;let e=(await this.run(["--version"])).match(/git version (\d+)\.(\d+)\.?((\d+)?)/);if(!e)throw Error("Cannot parse git version");let[,o,n]=e.map(Number);if(o<2||o===2&&n<17)throw new Io(`${o}.${n}`,"2.17");this.gitVersionChecked=!0}static async list(t){await this.checkVersion();let e=t??Bun.cwd,o=await this.getMainRepoPath(e).catch(()=>e),n=`list:${o}`,r=To(n);if(r)return r;let i=o.split("/").pop()??"",s=await this.run(["worktree","list","--porcelain"],e),c=this.parsePorcelain(s,i,o),u=await Promise.all(c.map(async(a)=>({...a,isDirty:await this.isDirty(a.path).catch(()=>!1)})));return ie(n,u)}static async listAll(t){await this.checkVersion();let e=new Set,o=[];for(let r of t){let i=os(r);if(!e.has(i))e.add(i),o.push(i)}return(await Promise.all(o.map(async(r)=>{try{return await this.list(r)}catch{return[]}}))).flat()}static parsePorcelain(t,e,o){let n=t.trim();if(!n)return[];return n.split(/\n\n+/).filter(Boolean).map((i,s)=>{let c=i.split(`
4
+ `),u=c.find((b)=>b.startsWith("worktree ")),a=c.find((b)=>b.startsWith("HEAD ")),l=c.find((b)=>b.startsWith("branch ")),h=c.find((b)=>b.startsWith("locked")),d=u?.slice(9)??"",g=a?.slice(5)??"",x=null;if(l)x=l.slice(7).replace(/^refs\/heads\//,"");let m=h&&h.startsWith("locked ")?h.slice(7):void 0;return{path:d,branch:x,head:g,isMain:s===0,isDirty:!1,isLocked:Boolean(h),lockReason:m,repoName:e,repoPath:o}})}static async add(t,e,o,n){await this.checkVersion();let r=Vf(e);if(!Xf(r))qf(r,{recursive:!0});let s=!await this.localBranchExists(t,n),c=["worktree","add",e,t];if(s)c=["worktree","add","-b",t,e,o?.base??"HEAD"];await this.run(c,n),Mt()}static async localBranchExists(t,e){try{return await this.run(["rev-parse","--verify",`refs/heads/${t}`],e??Bun.cwd),!0}catch{return!1}}static async remove(t,e,o){await this.checkVersion();let n=["worktree","remove",t];if(e?.force)n.push("--force");await this.run(n,o),Mt()}static async move(t,e,o){await this.checkVersion(),await this.run(["worktree","move",t,e],o),Mt()}static async prune(t){await this.checkVersion(),await this.run(["worktree","prune"],t),Mt()}static async isWorktree(t){let e=t??Bun.cwd;try{let o=await this.run(["rev-parse","--git-dir"],e),n=await this.run(["rev-parse","--git-common-dir"],e);return o!==n&&!o.endsWith("/.git")&&!o.endsWith("\\.git")}catch{return!1}}static async getMainRepoPath(t){let e=t??Bun.cwd,o=await this.run(["rev-parse","--git-common-dir"],e),n=os(e,o);return n.endsWith("/.git")?n.slice(0,-5):n}static async getBranchForWorktree(t){try{let e=await this.run(["rev-parse","--abbrev-ref","HEAD"],t);return e==="HEAD"?null:e}catch{return null}}static async isDirty(t){try{return(await this.run(["status","--porcelain"],t??Bun.cwd)).length>0}catch{return!1}}static async getAheadBehind(t,e){let o=e??Bun.cwd,n=`ahead-behind:${o}:${t}`,r=To(n);if(r)return r;try{let i=await this.run(["rev-parse","--abbrev-ref",`${t}@{upstream}`],o),s=await this.run(["rev-list","--left-right","--count",`${i}...${t}`],o),[c,u]=s.split(/\s+/).map(Number);return ie(n,{ahead:u??0,behind:c??0})}catch{return ie(n,{ahead:0,behind:0})}}static async getLastCommit(t){let e=t??Bun.cwd,o=`last-commit:${e}`,n=To(o);if(n!==void 0)return n;try{let r=await this.run(["log","-1","--format=%h\x1F%s\x1F%cr"],e);if(!r)return ie(o,null);let[i,s,c]=r.split("\x1F");return ie(o,{hash:i??"",message:s??"",relativeDate:c??""})}catch{return ie(o,null)}}static async getDirtyCount(t){let e=t??Bun.cwd,o=`dirty-count:${e}`,n=To(o);if(n!==void 0)return n;try{let r=await this.run(["status","--porcelain"],e);if(!r)return ie(o,0);return ie(o,r.split(`
5
+ `).filter(Boolean).length)}catch{return ie(o,0)}}static async unlock(t,e){await this.checkVersion(),await this.run(["worktree","unlock",t],e),Mt()}static async isMergedInto(t,e,o){try{return(await this.run(["branch","--merged",e],o??Bun.cwd)).split(`
6
+ `).some((r)=>r.trim().replace(/^[*+] /,"")===t)}catch{return!1}}static async getDefaultRemote(t){try{return await this.run(["config","checkout.defaultRemote"],t??Bun.cwd)||"origin"}catch{return"origin"}}static async remoteBranchExists(t,e,o){let n=e??await this.getDefaultRemote(o);try{return await this.run(["rev-parse","--verify",`refs/remotes/${n}/${t}`],o??Bun.cwd),!0}catch{return!1}}static async listBranches(t){let e=t??Bun.cwd,o=`branches:${e}`,n=To(o);if(n)return n;let[r,i]=await Promise.all([this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/heads/"],e).catch(()=>""),this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/remotes/"],e).catch(()=>"")]),s=[];for(let c of r.split(`
7
+ `).filter(Boolean)){let[u,a]=c.split("\x1F");s.push({name:u??"",isRemote:!1,lastCommitDate:a??""})}for(let c of i.split(`
8
+ `).filter(Boolean)){let[u,a]=c.split("\x1F");if(!u||u.endsWith("/HEAD"))continue;let l=u.replace(/^[^/]+\//,"");if(s.some((h)=>h.name===l))continue;s.push({name:l,isRemote:!0,lastCommitDate:a??""})}return ie(o,s)}static async diffBetween(t,e,o,n){let r=["diff"];if(o?.stat)r.push("--stat");if(o?.nameOnly)r.push("--name-only");return r.push(t,e),this.run(r,n)}static async getWorktreeLastActivity(t){try{let e=await this.run(["log","-1","--format=%ci"],t);return e?new Date(e):null}catch{return null}}static async setUpstream(t,e,o){let n=e??await this.getDefaultRemote(o),r=o??Bun.cwd;try{if(await this.run(["config",`branch.${t}.remote`],r))return}catch{}await this.run(["branch",`--set-upstream-to=${n}/${t}`,t],r)}}var Zf=3000,ln;var ct=N(()=>{Zt();ln=new Map});function rs(t){let[e,{refetch:o}]=vi(async()=>{try{if(t.repoPaths.length<=1)return await E.list(t.repoPaths[0]);return await E.listAll(t.repoPaths)}catch(s){throw s}}),n=()=>{Mt(),o()},r=ne(()=>{let s=e()??[],c=new Set,u=[];for(let a of s)if(!c.has(a.repoName))c.add(a.repoName),u.push(a.repoName);return u}),i=ne(()=>r().length>1);return React.createElement(ns.Provider,{value:{worktrees:()=>e(),refetch:n,loading:()=>e.loading,error:()=>e.error,repoNames:r,isMultiRepo:i}},t.children)}function Ot(){let t=to(ns);if(!t)throw Error("useGit must be used within GitProvider");return t}var ns;var de=N(()=>{Et();ct();ns=Ye()});var Qf,hn,is,Yf,un,f;var Ht=N(()=>{Et();Qf={opencode:{bg:{base:"#090909",surface:"#111111",elevated:"#1a1a1a",overlay:"#000000"},border:{default:"#2a2a2a",active:"#4fc3f7",subtle:"#1e1e1e"},text:{primary:"#e8e8e8",secondary:"#666666",accent:"#4fc3f7",success:"#4ade80",warning:"#fbbf24",error:"#f87171",selected:"#ffffff"},tab:{active:"#4fc3f7",activeBg:"#1a1a1a",inactive:"#555555",inactiveBg:"#000000"},select:{focusedBg:"#1a2a3a",focusedFg:"#4fc3f7",selectedBg:"#161616",selectedFg:"#e8e8e8",normalFg:"#e8e8e8",descFg:"#666666"}},"tokyo-night":{bg:{base:"#1a1b26",surface:"#1f2335",elevated:"#24283b",overlay:"#0d1117"},border:{default:"#3b4261",active:"#7aa2f7",subtle:"#292e42"},text:{primary:"#c0caf5",secondary:"#565f89",accent:"#7aa2f7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",selected:"#ffffff"},tab:{active:"#7aa2f7",activeBg:"#24283b",inactive:"#565f89",inactiveBg:"#1a1b26"},select:{focusedBg:"#283457",focusedFg:"#7aa2f7",selectedBg:"#2a2f44",selectedFg:"#c0caf5",normalFg:"#c0caf5",descFg:"#565f89"}},dracula:{bg:{base:"#282a36",surface:"#21222c",elevated:"#343746",overlay:"#191a21"},border:{default:"#6272a4",active:"#bd93f9",subtle:"#44475a"},text:{primary:"#f8f8f2",secondary:"#6272a4",accent:"#bd93f9",success:"#50fa7b",warning:"#ffb86c",error:"#ff5555",selected:"#ffffff"},tab:{active:"#bd93f9",activeBg:"#343746",inactive:"#6272a4",inactiveBg:"#282a36"},select:{focusedBg:"#44475a",focusedFg:"#bd93f9",selectedBg:"#383a4a",selectedFg:"#f8f8f2",normalFg:"#f8f8f2",descFg:"#6272a4"}},nord:{bg:{base:"#2e3440",surface:"#3b4252",elevated:"#434c5e",overlay:"#242933"},border:{default:"#4c566a",active:"#81a1c1",subtle:"#3b4252"},text:{primary:"#eceff4",secondary:"#4c566a",accent:"#81a1c1",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",selected:"#ffffff"},tab:{active:"#88c0d0",activeBg:"#434c5e",inactive:"#4c566a",inactiveBg:"#2e3440"},select:{focusedBg:"#3b4252",focusedFg:"#88c0d0",selectedBg:"#3b4252",selectedFg:"#eceff4",normalFg:"#eceff4",descFg:"#4c566a"}},catppuccin:{bg:{base:"#1e1e2e",surface:"#181825",elevated:"#313244",overlay:"#11111b"},border:{default:"#45475a",active:"#cba6f7",subtle:"#313244"},text:{primary:"#cdd6f4",secondary:"#585b70",accent:"#cba6f7",success:"#a6e3a1",warning:"#fab387",error:"#f38ba8",selected:"#ffffff"},tab:{active:"#cba6f7",activeBg:"#313244",inactive:"#585b70",inactiveBg:"#1e1e2e"},select:{focusedBg:"#313244",focusedFg:"#cba6f7",selectedBg:"#313244",selectedFg:"#cdd6f4",normalFg:"#cdd6f4",descFg:"#585b70"}},"github-dark":{bg:{base:"#0d1117",surface:"#161b22",elevated:"#21262d",overlay:"#010409"},border:{default:"#30363d",active:"#58a6ff",subtle:"#21262d"},text:{primary:"#e6edf3",secondary:"#484f58",accent:"#58a6ff",success:"#3fb950",warning:"#d29922",error:"#f85149",selected:"#ffffff"},tab:{active:"#58a6ff",activeBg:"#21262d",inactive:"#484f58",inactiveBg:"#0d1117"},select:{focusedBg:"#1f2937",focusedFg:"#58a6ff",selectedBg:"#1f2937",selectedFg:"#e6edf3",normalFg:"#e6edf3",descFg:"#484f58"}}},hn=["opencode","tokyo-night","dracula","nord","catppuccin","github-dark"],is={opencode:"OpenCode","tokyo-night":"Tokyo Night",dracula:"Dracula",nord:"Nord",catppuccin:"Catppuccin Mocha","github-dark":"GitHub Dark"},[Yf,un]=k("opencode"),f=new Proxy({},{get(t,e){return new Proxy({},{get(o,n){return Qf[Yf()][e]?.[n]}})}})});import{readFileSync as tl,statSync as el}from"fs";import{join as ss,resolve as ol}from"path";function _o(t){let e=ss(t,".git"),o=el(e,{throwIfNoEntry:!1});if(!o||o.isDirectory())return e;let r=tl(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim();return ol(t,r)}function se(t,e){return ss(_o(t),e)}var Oe=()=>{};import{existsSync as nl,mkdirSync as rl,readFileSync as il,writeFileSync as sl}from"fs";import{dirname as cl}from"path";function cs(t){return se(t,"omw-focus")}function uo(t,e){let o=cs(t);rl(cl(o),{recursive:!0}),sl(o,e.join(`
9
+ `),{encoding:"utf-8",mode:384})}function Qt(t){let e=cs(t);if(!nl(e))return null;return il(e,"utf-8").split(/\r?\n/).filter(Boolean)}var me=N(()=>{Oe()});import{existsSync as pr,mkdirSync as al,readFileSync as fl,writeFileSync as ll,unlinkSync as hl}from"fs";import{dirname as ul}from"path";function ur(t){return t.replace(/\//g,"-").replace(/[^a-zA-Z0-9._-]/g,"_")}async function xe(t){let e=Bun.spawn(["tmux",...t],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C"}}),[o,n,r]=await Promise.all([new Response(e.stdout).text(),new Response(e.stderr).text(),e.exited]);if(r!==0)throw new po(`tmux ${t[0]} failed: ${n.trim()}`,n.trim());return o.trim()}function We(t,e){let o=ur(e??as),n=ur(t);return`${o}_${n}`}function dr(t){return se(t,"omw-session")}function pl(t,e){let o=dr(t);al(ul(o),{recursive:!0}),ll(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}function Kt(t){let e=dr(t);if(!pr(e))return null;try{return JSON.parse(fl(e,"utf-8"))}catch{return null}}function mr(t){let e=dr(t);if(pr(e))hl(e)}async function mo(){try{return await Bun.spawn(["tmux","-V"],{stdout:"pipe",stderr:"pipe"}).exited===0}catch{return!1}}function xr(){return Boolean(Bun.env.TMUX)}async function ge(t){try{return await xe(["has-session","-t",t]),!0}catch{return!1}}async function dl(t,e,o){if(await ge(t))throw new po(`Session '${t}' already exists`,"session_exists");if(!pr(e))throw new po(`Worktree path does not exist: ${e}`,"path_not_found");let n=o?.windows??[],r=n[0],i=["new-session","-d","-s",t,"-c",e];if(r)i.push("-n",r.name);if(await xe(i),r?.command)await xe(["send-keys","-t",`${t}:${r.name}`,r.command,"Enter"]);for(let s=1;s<n.length;s++){let c=n[s];if(await xe(["new-window","-t",t,"-n",c.name,"-c",e]),c.command)await xe(["send-keys","-t",`${t}:${c.name}`,c.command,"Enter"])}if(n.length>0)await xe(["select-window","-t",`${t}:${n[0].name}`])}async function gr(t){if(!await ge(t))return;await xe(["kill-session","-t",t])}async function pn(t){if(!await ge(t))throw new po(`Session '${t}' does not exist`,"session_not_found");if(xr())await xe(["switch-client","-t",t]);else if(await Bun.spawn(["tmux","attach-session","-t",t],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0)throw new po(`Failed to attach to session '${t}'`,"attach_failed")}async function wr(t){let e=ur(t??as);try{let o=await xe(["list-sessions","-F","#{session_name}|#{session_windows}|#{session_attached}|#{session_created}"]);if(!o)return[];return o.split(`
10
+ `).filter(Boolean).filter((n)=>n.startsWith(`${e}_`)||n.startsWith(`${e}:`)).map((n)=>{let[r,i,s,c]=n.split("|");return{name:r??"",windows:parseInt(i??"0",10),attached:s==="1",created:c??""}})}catch{return[]}}async function dn(t,e,o){let n=We(t,o?.prefix),r=o?.attach??!0;if(await ge(n)){if(r)await pn(n);return n}if(await dl(n,e,o?.layout),pl(e,{name:n,branch:t,worktreePath:e,createdAt:new Date().toISOString(),layout:o?.layoutName}),r)await pn(n);return n}async function mn(t,e,o){let n=We(t,o),r=await ge(n);if(r)await gr(n);return mr(e),r}var po,as="omw";var De=N(()=>{Oe();po=class po extends Error{reason;constructor(t,e){super(t);this.reason=e;this.name="SessionError"}}});import{useTerminalDimensions as ml}from"@opentui/solid";function fs(t){let e=Ot(),o=ml(),n=()=>o().width,r=()=>o().height,[i,s]=k(null),[c,u]=k(!0),[a,l]=k(""),h;cn(()=>{if(h)clearTimeout(h)});let d=()=>{return(e.worktrees()??[]).find((it)=>it.isMain)?.branch??"main"};pe(Qe(()=>t.worktree.path,(y)=>{if(h)clearTimeout(h);if(!y){s(null),l(""),u(!1);return}s(null),l(""),u(!0),h=setTimeout(async()=>{if(t.worktree.path!==y)return;try{let[M,it,st]=await Promise.all([gl(y),t.worktree.branch&&!t.worktree.isMain?E.diffBetween(d(),t.worktree.branch,{stat:!0},y).catch(()=>""):Promise.resolve(""),t.worktree.branch?E.getAheadBehind(t.worktree.branch,y):Promise.resolve({ahead:0,behind:0})]);if(t.worktree.path!==y)return;let G=null;try{G=Qt(y)}catch{}let ot=null,et=Kt(y);if(et){let fe=await ge(et.name).catch(()=>!1);ot={meta:et,active:fe}}if(t.worktree.path!==y)return;s({commits:M,diffStat:it,aheadBehind:st,focus:G,session:ot}),l("")}catch(M){if(t.worktree.path!==y)return;s(null),l(M.message)}finally{if(t.worktree.path===y)u(!1)}},xl)}));let g=()=>{let y=t.worktree;if(y.isLocked)return"\uD83D\uDD12 locked";if(y.isDirty)return"\u25CF dirty";return"\u2713 clean"},x=()=>{let y=t.worktree;if(y.isLocked)return f.text.warning;if(y.isDirty)return f.text.error;return f.text.success},m=()=>{let y=i();if(!y)return"";let M=[];if(y.aheadBehind.ahead>0)M.push(`\u2191${y.aheadBehind.ahead}`);if(y.aheadBehind.behind>0)M.push(`\u2193${y.aheadBehind.behind}`);return M.length>0?M.join(" "):"\u2713 up to date"},b=()=>{let y=i();if(!y)return f.text.secondary;return y.aheadBehind.ahead||y.aheadBehind.behind?f.text.warning:f.text.success},S=()=>{let y=i();if(!y||!y.diffStat)return[];return y.diffStat.split(`
11
+ `).filter(Boolean)},R=()=>"\u2500".repeat(Math.max(n()-7,10));return React.createElement("box",{x:0,y:0,width:n(),height:r(),backgroundColor:f.bg.base},React.createElement("scrollbox",{x:2,y:1,width:n()-3,height:r()-3},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0},"Worktree Detail"),React.createElement("text",{x:17,y:0,fg:f.text.secondary},"(Esc to close)")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},R())),React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},t.worktree.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},t.worktree.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Status")),React.createElement("text",{fg:x()},g())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"HEAD")),React.createElement("text",{fg:f.text.secondary},t.worktree.head?.slice(0,8))),React.createElement(O,{when:c()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Loading details..."))),React.createElement(O,{when:!c()&&!!a()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.error},`Failed to load details: ${a()}`))),React.createElement(O,{when:!c()&&!a()&&!!i()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0},"Upstream")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},R())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Sync")),React.createElement("text",{fg:b()},m())),React.createElement(O,{when:i().aheadBehind.ahead>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Ahead")),React.createElement("text",{fg:f.text.warning},`${i().aheadBehind.ahead} commit(s)`))),React.createElement(O,{when:i().aheadBehind.behind>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Behind")),React.createElement("text",{fg:f.text.warning},`${i().aheadBehind.behind} commit(s)`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0},"Recent Commits")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},R())),React.createElement(O,{when:i().commits.length>0,fallback:React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"No commits found"))},React.createElement(St,{each:i().commits},(y)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.primary},y)))),React.createElement(O,{when:!t.worktree.isMain&&S().length>0},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0},`Diff vs ${d()}`)),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},R())),React.createElement(St,{each:S()},(y)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.primary},y)))),React.createElement(O,{when:i().focus&&i().focus.length>0},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0},"Focus Paths")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},R())),React.createElement(St,{each:i().focus},(y)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.primary},` \u2022 ${y}`)))),React.createElement(O,{when:i().session},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0},"Session")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},R())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Name")),React.createElement("text",{fg:f.text.primary},i().session.meta.name)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Status")),React.createElement("text",{fg:i().session.active?f.text.success:f.text.error},i().session.active?"\u25CF active":"\u25CB inactive")),React.createElement(O,{when:i().session.meta.layout},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Layout")),React.createElement("text",{fg:f.text.primary},i().session.meta.layout)))),React.createElement(O,{when:t.worktree.isMain},React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:Yt,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Type")),React.createElement("text",{fg:f.text.accent},"main worktree")))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},R())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Esc:back d:delete o:open r:refresh"))))}async function gl(t){try{let e=Bun.spawn(["git","log","--oneline","-10"],{cwd:t,stdout:"pipe",stderr:"pipe",env:{...process.env,LC_ALL:"C"}}),o=await new Response(e.stdout).text();if(await e.exited,e.exitCode!==0)return[];return o.trim().split(`
12
+ `).filter(Boolean)}catch{return[]}}var xl=150,Yt=16;var ls=N(()=>{Et();de();Ht();me();De();ct()});import{useKeyboard as wl,useTerminalDimensions as bl}from"@opentui/solid";function hs(){let t=Rt(),e=Ot(),o=bl(),n=()=>{let b=e.worktrees()??[],S=t.selectedWorktreePath();if(S){let R=b.find((y)=>y.path===S);if(R)return R}return b[t.selectedWorktreeIndex()]},r=()=>o().width,i=()=>o().height,s=14,[c,u]=k(null),[a,l]=k(!1),[h,d]=k(""),g;cn(()=>{if(g)clearTimeout(g)}),pe(Qe(()=>n()?.path,(b)=>{if(g)clearTimeout(g);if(!b){u(null),l(!1),d("");return}u(null),l(!0),d(""),g=setTimeout(async()=>{let S=n();if(!S||S.path!==b)return;try{let[R,y,M]=await Promise.all([S.branch?E.getAheadBehind(S.branch,S.path):Promise.resolve({ahead:0,behind:0}),E.getLastCommit(S.path),E.getDirtyCount(S.path)]);if(n()?.path===b)u({aheadBehind:R,lastCommit:y,dirtyCount:M}),d("")}catch(R){if(n()?.path===b)u(null),d(R.message)}finally{if(n()?.path===b)l(!1)}},Cl)}));let x=()=>{if(a())return"Loading...";if(h())return"Unavailable";let b=c();if(!b)return"";let S=[];if(b.aheadBehind.ahead>0)S.push(`\u2191${b.aheadBehind.ahead}`);if(b.aheadBehind.behind>0)S.push(`\u2193${b.aheadBehind.behind}`);return S.length>0?S.join(" "):"\u2713 up to date"},m=()=>{let b=n();if(!b)return"";if(b.isLocked)return"\uD83D\uDD12 locked";let S=c();if(S&&S.dirtyCount>0)return`\u25CF ${S.dirtyCount} file(s) dirty`;if(b.isDirty)return"\u25CF dirty";return"\u2713 clean"};return wl((b)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;let S=b.name;if(S==="x"&&t.selectedWorktrees().size>0){t.setShowBulkActions(!0);return}if(S==="return"&&!t.showDetailView()&&n()){t.setShowDetailView(!0);return}if(S==="escape"&&t.showDetailView()){t.setShowDetailView(!1);return}}),React.createElement("box",{width:"100%",height:"100%",backgroundColor:f.bg.base},React.createElement(O,{when:t.showDetailView()&&!!n()},React.createElement(fs,{worktree:n()})),React.createElement(O,{when:!t.showDetailView()},React.createElement(O,{when:e.loading()},React.createElement("text",{x:2,y:2,fg:f.text.secondary},"Loading worktrees...")),React.createElement(O,{when:!e.loading()&&!!e.error()},React.createElement("text",{x:2,y:2,fg:f.text.error},"Error: ",e.error()?.message),React.createElement("text",{x:2,y:3,fg:f.text.secondary},"Not in a git repository?")),React.createElement(O,{when:!e.loading()&&!e.error()&&!!n()},React.createElement("box",{width:"100%",height:"100%",border:!0,borderStyle:"rounded",borderColor:f.border.default,flexDirection:"column",backgroundColor:f.bg.surface,paddingX:1,paddingY:1},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("text",{fg:f.text.accent},"Worktree Details")),React.createElement("box",{height:1},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement(O,{when:e.isMultiRepo()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Repo")),React.createElement("text",{fg:f.text.warning},n()?.repoName))),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},n()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},n()?.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Status")),React.createElement("text",{fg:n()?.isDirty?f.text.error:n()?.isLocked?f.text.warning:f.text.success},m())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Sync")),React.createElement("text",{fg:h()?f.text.error:a()?f.text.secondary:c()?.aheadBehind?.ahead||c()?.aheadBehind?.behind?f.text.warning:f.text.success},x())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"HEAD")),React.createElement("text",{fg:f.text.secondary},n()?.head?.slice(0,8))),React.createElement(O,{when:c()?.lastCommit},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Last Commit")),React.createElement("text",{fg:f.text.primary},c().lastCommit.relativeDate)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"")),React.createElement("text",{fg:f.text.secondary},c().lastCommit.message.length>50?c().lastCommit.message.slice(0,47)+"...":c().lastCommit.message))),React.createElement(O,{when:(()=>{let b=Qt(n()?.path??"");return b&&b.length>0})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Focus")),React.createElement("text",{fg:f.text.accent},Qt(n()?.path??"")?.join(", ")??""))),React.createElement(O,{when:(()=>{return!!Kt(n()?.path??"")})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Session")),React.createElement("text",{fg:f.text.accent},(()=>{let b=Kt(n()?.path??"");if(!b)return"";return b.layout?`${b.name} [${b.layout}]`:b.name})()))),React.createElement(O,{when:n()?.isMain},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Type")),React.createElement("text",{fg:f.text.accent},"main worktree"))),React.createElement("box",{height:1},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Enter:detail"),React.createElement("text",{fg:f.text.secondary},"d:delete"),React.createElement("text",{fg:f.text.secondary},"a:add"),React.createElement("text",{fg:f.text.secondary},"o:open"),React.createElement("text",{fg:f.text.secondary},"r:refresh"),React.createElement("text",{fg:f.text.secondary},"^P:commands")))),React.createElement(O,{when:!e.loading()&&!e.error()&&!n()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.secondary},"No worktree selected."),React.createElement("text",{fg:f.text.accent},"Press 'a' to create one.")))))}var Cl=150;var us=N(()=>{Et();re();de();Ht();me();De();ct();ls()});import{join as br,resolve as xn}from"path";import*as Fe from"fs";function ce(t,e,o){if(!Array.isArray(t)||t.some((n)=>typeof n!=="string"))o.push({field:e,message:"Must be an array of strings"})}function xs(){let e=Bun.env.XDG_CONFIG_HOME??br(Bun.env.HOME??"~",".config");return br(e,"oh-my-worktree")}function Nt(){return br(xs(),"config.json")}function Ho(t){let e=[];if(typeof t!=="object"||t===null)return e.push({field:"root",message:"Config must be a JSON object"}),e;let o=t;if(!("version"in o))e.push({field:"version",message:"Required field 'version' is missing"});else if(o.version!==1)e.push({field:"version",message:`Expected version 1, got ${JSON.stringify(o.version)}`});let n=new Set(["version","defaults","repos","$schema","theme","templates","lifecycle","sessions","profiles","activeProfile"]);for(let r of Object.keys(o))if(!n.has(r))e.push({field:r,message:`Unknown field '${r}'`});if("defaults"in o&&o.defaults!==void 0)if(typeof o.defaults!=="object"||o.defaults===null)e.push({field:"defaults",message:"Must be an object"});else{let r=o.defaults,i=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","sharedDeps"]);for(let s of Object.keys(r))if(!i.has(s))e.push({field:`defaults.${s}`,message:`Unknown field '${s}'`});if("worktreeDir"in r&&typeof r.worktreeDir!=="string")e.push({field:"defaults.worktreeDir",message:"Must be a string"});if("autoUpstream"in r&&typeof r.autoUpstream!=="boolean")e.push({field:"defaults.autoUpstream",message:"Must be a boolean"});for(let s of["copyFiles","linkFiles","postCreate","postRemove"])if(s in r)ce(r[s],`defaults.${s}`,e);if("sharedDeps"in r&&r.sharedDeps!==void 0)if(typeof r.sharedDeps!=="object"||r.sharedDeps===null)e.push({field:"defaults.sharedDeps",message:"Must be an object"});else ps(r.sharedDeps,"defaults.sharedDeps",e)}if("repos"in o&&o.repos!==void 0)if(!Array.isArray(o.repos))e.push({field:"repos",message:"Must be an array"});else for(let r=0;r<o.repos.length;r++){let i=o.repos[r],s=`repos[${r}]`;if(typeof i!=="object"||i===null){e.push({field:s,message:"Must be an object"});continue}let c=i,u=new Set(["path","worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","monorepo","sharedDeps"]);for(let a of Object.keys(c))if(!u.has(a))e.push({field:`${s}.${a}`,message:`Unknown field '${a}'`});if(!("path"in c)||typeof c.path!=="string")e.push({field:`${s}.path`,message:"Required string field 'path' is missing"});if("worktreeDir"in c&&typeof c.worktreeDir!=="string")e.push({field:`${s}.worktreeDir`,message:"Must be a string"});if("autoUpstream"in c&&typeof c.autoUpstream!=="boolean")e.push({field:`${s}.autoUpstream`,message:"Must be a boolean"});for(let a of["copyFiles","linkFiles","postCreate","postRemove"])if(a in c)ce(c[a],`${s}.${a}`,e);if("sharedDeps"in c&&c.sharedDeps!==void 0)if(typeof c.sharedDeps!=="object"||c.sharedDeps===null)e.push({field:`${s}.sharedDeps`,message:"Must be an object"});else ps(c.sharedDeps,`${s}.sharedDeps`,e);if("monorepo"in c&&c.monorepo!==void 0)if(typeof c.monorepo!=="object"||c.monorepo===null)e.push({field:`${s}.monorepo`,message:"Must be an object"});else{let a=c.monorepo,l=new Set(["autoDetect","extraPatterns","hooks"]);for(let h of Object.keys(a))if(!l.has(h))e.push({field:`${s}.monorepo.${h}`,message:`Unknown field '${h}'`});if("autoDetect"in a&&typeof a.autoDetect!=="boolean")e.push({field:`${s}.monorepo.autoDetect`,message:"Must be a boolean"});if("extraPatterns"in a&&a.extraPatterns!==void 0)ce(a.extraPatterns,`${s}.monorepo.extraPatterns`,e);if("hooks"in a&&a.hooks!==void 0)if(!Array.isArray(a.hooks))e.push({field:`${s}.monorepo.hooks`,message:"Must be an array"});else for(let h=0;h<a.hooks.length;h++){let d=a.hooks[h];if(typeof d!=="object"||d===null){e.push({field:`${s}.monorepo.hooks[${h}]`,message:"Must be an object"});continue}if(!("glob"in d)||typeof d.glob!=="string")e.push({field:`${s}.monorepo.hooks[${h}].glob`,message:"Required string field"});if("copyFiles"in d&&d.copyFiles!==void 0)ce(d.copyFiles,`${s}.monorepo.hooks[${h}].copyFiles`,e);if("linkFiles"in d&&d.linkFiles!==void 0)ce(d.linkFiles,`${s}.monorepo.hooks[${h}].linkFiles`,e);if("postCreate"in d&&d.postCreate!==void 0)ce(d.postCreate,`${s}.monorepo.hooks[${h}].postCreate`,e);if("postRemove"in d&&d.postRemove!==void 0)ce(d.postRemove,`${s}.monorepo.hooks[${h}].postRemove`,e)}}}if("templates"in o&&o.templates!==void 0)if(typeof o.templates!=="object"||o.templates===null||Array.isArray(o.templates))e.push({field:"templates",message:"Must be an object (key-value map)"});else{let r=o.templates,i=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","base"]);for(let[s,c]of Object.entries(r)){let u=`templates.${s}`;if(typeof c!=="object"||c===null){e.push({field:u,message:"Must be an object"});continue}let a=c;for(let l of Object.keys(a))if(!i.has(l))e.push({field:`${u}.${l}`,message:`Unknown field '${l}'`});if("worktreeDir"in a&&typeof a.worktreeDir!=="string")e.push({field:`${u}.worktreeDir`,message:"Must be a string"});if("base"in a&&typeof a.base!=="string")e.push({field:`${u}.base`,message:"Must be a string"});if("autoUpstream"in a&&typeof a.autoUpstream!=="boolean")e.push({field:`${u}.autoUpstream`,message:"Must be a boolean"});for(let l of["copyFiles","linkFiles","postCreate","postRemove"])if(l in a)ce(a[l],`${u}.${l}`,e)}}if("lifecycle"in o&&o.lifecycle!==void 0)if(typeof o.lifecycle!=="object"||o.lifecycle===null)e.push({field:"lifecycle",message:"Must be an object"});else{let r=o.lifecycle,i=new Set(["autoCleanMerged","staleAfterDays","maxWorktrees"]);for(let s of Object.keys(r))if(!i.has(s))e.push({field:`lifecycle.${s}`,message:`Unknown field '${s}'`});if("autoCleanMerged"in r&&typeof r.autoCleanMerged!=="boolean")e.push({field:"lifecycle.autoCleanMerged",message:"Must be a boolean"});if("staleAfterDays"in r&&(typeof r.staleAfterDays!=="number"||r.staleAfterDays<1))e.push({field:"lifecycle.staleAfterDays",message:"Must be a positive number"});if("maxWorktrees"in r&&(typeof r.maxWorktrees!=="number"||r.maxWorktrees<1))e.push({field:"lifecycle.maxWorktrees",message:"Must be a positive number"})}if("sessions"in o&&o.sessions!==void 0)if(typeof o.sessions!=="object"||o.sessions===null)e.push({field:"sessions",message:"Must be an object"});else{let r=o.sessions,i=new Set(["enabled","autoCreate","autoKill","prefix","defaultLayout","layouts"]);for(let s of Object.keys(r))if(!i.has(s))e.push({field:`sessions.${s}`,message:`Unknown field '${s}'`});for(let s of["enabled","autoCreate","autoKill"])if(s in r&&typeof r[s]!=="boolean")e.push({field:`sessions.${s}`,message:"Must be a boolean"});if("prefix"in r&&typeof r.prefix!=="string")e.push({field:"sessions.prefix",message:"Must be a string"});if("defaultLayout"in r&&typeof r.defaultLayout!=="string")e.push({field:"sessions.defaultLayout",message:"Must be a string"});if("layouts"in r&&r.layouts!==void 0)if(typeof r.layouts!=="object"||r.layouts===null||Array.isArray(r.layouts))e.push({field:"sessions.layouts",message:"Must be an object (key-value map)"});else{let s=r.layouts;for(let[c,u]of Object.entries(s)){let a=`sessions.layouts.${c}`;if(typeof u!=="object"||u===null){e.push({field:a,message:"Must be an object"});continue}let l=u;if(!("windows"in l)||!Array.isArray(l.windows))e.push({field:`${a}.windows`,message:"Required array field"});else for(let h=0;h<l.windows.length;h++){let d=l.windows[h];if(typeof d!=="object"||d===null){e.push({field:`${a}.windows[${h}]`,message:"Must be an object"});continue}if(!("name"in d)||typeof d.name!=="string")e.push({field:`${a}.windows[${h}].name`,message:"Required string field"});if("command"in d&&typeof d.command!=="string")e.push({field:`${a}.windows[${h}].command`,message:"Must be a string"})}}}if("defaultLayout"in r&&typeof r.defaultLayout==="string"&&"layouts"in r&&typeof r.layouts==="object"&&r.layouts!==null){let s=r.layouts;if(!(r.defaultLayout in s))e.push({field:"sessions.defaultLayout",message:`Layout '${r.defaultLayout}' does not exist in sessions.layouts`})}}if("profiles"in o&&o.profiles!==void 0)if(typeof o.profiles!=="object"||o.profiles===null||Array.isArray(o.profiles))e.push({field:"profiles",message:"Must be an object (key-value map)"});else{let r=o.profiles,i=new Set(["defaults","repos","theme","templates","lifecycle","sessions"]);for(let[s,c]of Object.entries(r)){let u=`profiles.${s}`;if(typeof c!=="object"||c===null){e.push({field:u,message:"Must be an object"});continue}let a=c;for(let l of Object.keys(a))if(!i.has(l))e.push({field:`${u}.${l}`,message:`Unknown field '${l}'`})}}if("activeProfile"in o&&o.activeProfile!==void 0){if(typeof o.activeProfile!=="string")e.push({field:"activeProfile",message:"Must be a string"});else if("profiles"in o&&o.profiles!==void 0&&typeof o.profiles==="object"&&o.profiles!==null&&!Array.isArray(o.profiles)){let r=o.profiles;if(!(o.activeProfile in r))e.push({field:"activeProfile",message:`Profile '${o.activeProfile}' does not exist in profiles`})}else if(!("profiles"in o)||o.profiles===void 0)e.push({field:"activeProfile",message:"Cannot set activeProfile without profiles"})}return e}function ps(t,e,o){let n=new Set(["strategy","paths","invalidateOn"]);for(let r of Object.keys(t))if(!n.has(r))o.push({field:`${e}.${r}`,message:`Unknown field '${r}'`});if("strategy"in t&&!["hardlink","symlink","copy"].includes(t.strategy))o.push({field:`${e}.strategy`,message:'Must be "hardlink", "symlink", or "copy"'});if("paths"in t)ce(t.paths,`${e}.paths`,o);if("invalidateOn"in t)ce(t.invalidateOn,`${e}.invalidateOn`,o)}function Go(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function oo(t){if(Array.isArray(t))return t.map((e)=>oo(e));if(Go(t)){let e={};for(let[o,n]of Object.entries(t))e[o]=oo(n);return e}return t}function gs(t,e){if(e===void 0)return oo(t);if(Array.isArray(e))return e.map((r)=>oo(r));if(!Go(e))return oo(e);let o=Go(t)?t:{},n={};for(let[r,i]of Object.entries(o))n[r]=oo(i);for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let s=o[r];if(Go(s)&&Go(i)){n[r]=gs(s,i);continue}n[r]=oo(i)}return n}function $l(t){if(!t.activeProfile)return structuredClone(t);let e=t.profiles?.[t.activeProfile];if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`Active profile '${t.activeProfile}' does not exist`);return gs(t,e)}function Y(t){let e=t??Nt();if(!Fe.existsSync(e))return structuredClone(ms);let o;try{let s=gn.readFileSync(e,"utf-8");o=JSON.parse(s)}catch(s){let c=s.message;if(c.includes("JSON"))throw Error(`Invalid JSON in config file: ${c}`);if(s instanceof SyntaxError)throw Error(`Invalid JSON in config file: ${c}`);throw Error(`Failed to read config file: ${c}`)}let n=Ho(o);if(n.length>0){let s=n.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed: ${s}`)}let r=$l(o),i=Ho(r);if(i.length>0){let s=i.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed after applying activeProfile: ${s}`)}return r}function Lt(t,e){let o=xn(e),n=t.repos?.find((r)=>xn(r.path)===o);return{worktreeDir:n?.worktreeDir??t.defaults?.worktreeDir??xo.worktreeDir,copyFiles:n?.copyFiles??t.defaults?.copyFiles??xo.copyFiles,linkFiles:n?.linkFiles??t.defaults?.linkFiles??xo.linkFiles,postCreate:n?.postCreate??t.defaults?.postCreate??xo.postCreate,postRemove:n?.postRemove??t.defaults?.postRemove??xo.postRemove,autoUpstream:n?.autoUpstream??t.defaults?.autoUpstream??xo.autoUpstream,monorepo:n?.monorepo,sharedDeps:n?.sharedDeps??t.defaults?.sharedDeps}}function Be(t){return(t.repos??[]).map((e)=>xn(e.path))}function wn(t,e){let o=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,o).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}function ae(t){let e=t??Nt(),o=t?xn(e,".."):xs();if(!Fe.existsSync(o))gn.mkdirSync(o,{recursive:!0,mode:448});if(Fe.existsSync(e))return e;return No(e,`${JSON.stringify(ms,null,2)}
13
+ `),e}function bn(t,e){return t.templates?.[e]}function Cn(t,e){return{worktreeDir:e.worktreeDir??t.worktreeDir,copyFiles:e.copyFiles??t.copyFiles,linkFiles:e.linkFiles??t.linkFiles,postCreate:e.postCreate??t.postCreate,postRemove:e.postRemove??t.postRemove,autoUpstream:e.autoUpstream??t.autoUpstream,monorepo:t.monorepo,sharedDeps:t.sharedDeps}}function Le(t){return t.sessions??{}}function $n(t,e){let o=t.sessions;if(!o?.layouts)return;let n=e??o.defaultLayout;if(!n)return;return o.layouts[n]}function No(t,e){let o=`${t}.tmp.${Date.now()}`;try{Fe.writeFileSync(o,e,{encoding:"utf-8",mode:384});let n=JSON.parse(e),r=Ho(n);if(r.length>0)throw Error(`Validation failed: ${r.map((i)=>i.message).join("; ")}`);gn.renameSync(o,t)}catch(n){if(Fe.existsSync(o))gn.unlinkSync(o);throw n}}var gn,ds="~/.omw/worktrees/{repo}-{branch}",ms,xo;var $t=N(()=>{gn=Fe,ms={version:1,defaults:{worktreeDir:ds,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0},repos:[]},xo={worktreeDir:ds,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0,sharedDeps:void 0}});import*as Sl from"fs";import{join as Ae,resolve as we,dirname as Jo}from"path";function wo(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=Ae(we(t),r),s=Ae(we(e),r);if(!be(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping copy: ${r}`);continue}if(be(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping copy: ${r}`);continue}try{go(Jo(s),{recursive:!0}),bs(i,s),n.copied.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to copy ${r}: ${c.message}`)}}return n}function bo(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=we(Ae(we(t),r)),s=Ae(we(e),r);if(!be(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping symlink: ${r}`);continue}if(be(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping symlink: ${r}`);continue}try{go(Jo(s),{recursive:!0}),Cs(i,s),n.linked.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to symlink ${r}: ${c.message}`)}}return n}function $s(t,e){let o=0,n=[],r=we(t),i=we(e);if(!be(r))return{linked:0,errors:[`Source not found: ${t}`]};let s=Rl(r,{throwIfNoEntry:!1});if(!s||!s.isDirectory())try{return go(Jo(i),{recursive:!0}),ws(r,i),{linked:1,errors:[]}}catch(c){return{linked:0,errors:[`Failed to hardlink ${t}: ${c.message}`]}}if(!be(i))go(i,{recursive:!0});try{let c=yl(r,{withFileTypes:!0});for(let u of c){let a=Ae(r,u.name),l=Ae(i,u.name);if(u.isDirectory()){let h=$s(a,l);o+=h.linked,n.push(...h.errors)}else if(u.isFile()){if(be(l))continue;try{ws(a,l),o++}catch(h){try{bs(a,l),o++}catch(d){n.push(`Failed to link/copy ${u.name}: ${d.message}`)}}}}}catch(c){n.push(`Failed to read directory ${t}: ${c.message}`)}return{linked:o,errors:n}}function Ss(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]},r=o.paths??[],i=o.strategy??"symlink";for(let s of r){let c=Ae(we(t),s),u=Ae(we(e),s);if(!be(c)){n.skipped.push(s),n.warnings.push(`Source not found, skipping shared dep: ${s}`);continue}if(be(u)){n.skipped.push(s);continue}try{if(i==="symlink")go(Jo(u),{recursive:!0}),Cs(c,u),n.linked.push(s);else if(i==="hardlink"){let a=$s(c,u);if(a.linked>0)n.linked.push(s);for(let l of a.errors)n.warnings.push(l)}else go(Jo(u),{recursive:!0}),Pl(c,u,{recursive:!0}),n.copied.push(s)}catch(a){n.skipped.push(s),n.warnings.push(`Failed to share dep ${s}: ${a.message}`)}}return n}var bs,Pl,be,Cs,bx,ws,yl,Rl,go;var Sn=N(()=>{({copyFileSync:bs,cpSync:Pl,existsSync:be,symlinkSync:Cs,unlinkSync:bx,linkSync:ws,readdirSync:yl,statSync:Rl,mkdirSync:go}=Sl)});import{existsSync as El,mkdirSync as Ml}from"fs";async function Wt(t,e){let o=e.timeout??30000;for(let n of t)await Ol(n,e.cwd,o,e.env??{},e.onOutput)}async function Ol(t,e,o,n,r){if(!El(e))Ml(e,{recursive:!0});let i;try{i=Bun.spawn(["sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}catch(a){if(a.code!=="ENOENT")throw a;i=Bun.spawn(["/bin/sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}let s=!1,c=setTimeout(()=>{s=!0,i.kill()},o),u=i.stderr?new Response(i.stderr).text():Promise.resolve("");try{if(r&&i.stdout){let l=i.stdout.getReader(),h=new TextDecoder,d="";while(!0){let{done:g,value:x}=await l.read();if(g)break;d+=h.decode(x,{stream:!0});let m=d.split(`
14
+ `);d=m.pop()??"";for(let b of m)if(b)r(b)}if(d+=h.decode(),d)r(d)}let a=await i.exited;if(s)throw new $o(t,o);if(a!==0){let l=(await u).trim();throw new Co(t,a,l)}}finally{clearTimeout(c)}}var Co,$o;var Ce=N(()=>{Co=class Co extends Error{command;exitCode;stderr;constructor(t,e,o){super(`Hook command failed (exit ${e}): ${t}
15
+ ${o}`);this.command=t;this.exitCode=e;this.stderr=o;this.name="HookError"}};$o=class $o extends Error{command;timeoutMs;constructor(t,e){super(`Hook command timed out after ${e}ms: ${t}`);this.command=t;this.timeoutMs=e;this.name="HookTimeoutError"}}});import{existsSync as Wl,readdirSync as yx,readFileSync as Rx,statSync as Dl}from"fs";import{join as Fl,relative as Mx}from"path";function Pn(t,e){let o=[],n=[];for(let r of e){let i=r.trim();if(!i){n.push(i);continue}let s=Fl(t,i);try{if(Wl(s)&&Dl(s).isDirectory())o.push(i);else n.push(i)}catch{n.push(i)}}return{valid:o,invalid:n}}var Cr=()=>{};function no(t,e){return t.map((o)=>{let n=new Bun.Glob(o.glob),r=e.filter((i)=>n.match(i));return{glob:o.glob,matchedPaths:r,copyFiles:o.copyFiles??[],linkFiles:o.linkFiles??[],postCreate:o.postCreate??[],postRemove:o.postRemove??[]}}).filter((o)=>o.matchedPaths.length>0)}function Bl(t,e){return t.replace(/\{packagePath\}/g,e.packagePath).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}async function So(t,e,o){for(let n of t){let r=n[e],i=e==="postCreate"&&n.copyFiles.length>0,s=e==="postCreate"&&n.linkFiles.length>0,c=r.length>0;if(!i&&!s&&!c)continue;for(let u of n.matchedPaths){let{join:a}=await import("path"),l=a(o.mainRepoPath,u),h=a(o.cwd,u);if(i){let d=wo(l,h,n.copyFiles);for(let g of d.copied)o.onOutput?.(`Copied ${u}/${g}`);for(let g of d.warnings)o.onOutput?.(`\u26A0 ${g}`)}if(s){let d=bo(l,h,n.linkFiles);for(let g of d.linked)o.onOutput?.(`Linked ${u}/${g}`);for(let g of d.warnings)o.onOutput?.(`\u26A0 ${g}`)}if(c){let d=r.map((x)=>Bl(x,{packagePath:u,repo:o.repo,branch:o.branch})),g={...o.env??{},OMW_FOCUS_PATHS:o.focusPaths.join(","),OMW_PACKAGE_PATH:u};await Wt(d,{cwd:o.cwd,timeout:o.timeout,env:g,onOutput:o.onOutput})}}}}var yn=N(()=>{Ce();Sn()});import{useTerminalDimensions as Ll}from"@opentui/solid";function Ie(t){let e=Ll(),o=()=>Math.max(0,Math.floor((e().width-t.width)/2)),n=()=>Math.max(0,Math.floor((e().height-t.height)/2)),r=()=>React.createElement("box",{x:o(),y:n(),width:t.width,height:t.height,border:!0,borderStyle:"rounded",borderColor:t.borderColor??f.border.active,backgroundColor:t.backgroundColor??f.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:t.gap??0,title:t.title,titleAlignment:"left",position:"absolute"},t.children,React.createElement(O,{when:t.footer},t.footer));return React.createElement(O,{when:t.backdrop,fallback:r()},React.createElement("box",{x:0,y:0,width:e().width,height:e().height,backgroundColor:t.backdropColor??f.bg.overlay,position:"absolute"},r()))}var zo=N(()=>{Et();Ht()});import{useKeyboard as Al,useTerminalDimensions as Il}from"@opentui/solid";import{basename as Ps,resolve as jl}from"path";function ys(){let t=Rt(),e=Ot(),o=Il(),[n,r]=k("input"),[i,s]=k(""),[c,u]=k(""),[a,l]=k("branch"),[h,d]=k(""),[g,x]=k([]),[m,b]=k(""),[S,R]=k([]),[y,M]=k(-1),[it,st]=k(!1),G=()=>{let z=i().toLowerCase();if(!z)return S().slice(0,10);return S().filter((_)=>_.name.toLowerCase().includes(z)).slice(0,10)};pe(Qe(()=>et(),async()=>{try{let z=et(),_=await E.listBranches(z);R(_)}catch{R([])}})),pe(Qe(i,()=>{M(-1),st(i().length>0&&G().length>0)}));let ot=(z,_)=>{x((Z)=>Z.map((dt,A)=>A===z?{...dt,..._}:dt))},et=()=>{let z=e.worktrees()??[],_=t.selectedWorktreePath();return(_?z.find((dt)=>dt.path===_)??z[t.selectedWorktreeIndex()]:z[t.selectedWorktreeIndex()])?.repoPath??t.repoPath()},fe=()=>{let z=e.worktrees()??[],_=t.selectedWorktreePath();return(_?z.find((dt)=>dt.path===_)??z[t.selectedWorktreeIndex()]:z[t.selectedWorktreeIndex()])?.repoName??t.repoPath().split("/").pop()??""},T=()=>{let z=i();if(!z)return"";let _=et(),Z=Y(),dt=Lt(Z,_),A=z.replace(/\//g,"-"),te=Ps(_);return jl(wn(dt.worktreeDir,{repo:te,branch:A}))};Al(async(z)=>{if(t.activeTab()!=="add")return;if(t.showCommandPalette())return;let _=z.name;if(_==="escape"){if(n()==="preview"){r("input");return}t.setActiveTab("list"),s(""),u(""),l("branch"),r("input");return}if(n()==="input"){if(_==="tab"){if(it()&&a()==="branch")st(!1),M(-1);l((Z)=>Z==="branch"?"focus":"branch");return}if(a()==="branch"&&it()&&G().length>0){if(_==="down"||z.sequence==="\x1B[B"){M((Z)=>Math.min(Z+1,G().length-1));return}if(_==="up"||z.sequence==="\x1B[A"){M((Z)=>Math.max(Z-1,-1));return}}if(_==="return"||_==="enter"){if(a()==="branch"&&y()>=0){let Z=G()[y()];if(Z){s(Z.name),st(!1),M(-1);return}}if(!i())return;st(!1),d(T()),r("preview");return}if(_==="backspace"){if(a()==="branch")s((Z)=>Z.slice(0,-1));else u((Z)=>Z.slice(0,-1));return}if(z.sequence==="\x15"||z.ctrl&&_==="u"){if(a()==="branch")s("");else u("");return}if(z.sequence==="\x17"||z.ctrl&&_==="w"){if(a()==="branch")s((Z)=>Z.replace(/\S+\s*$/,""));else u((Z)=>Z.replace(/\S+\s*$/,""));return}if(z.sequence&&z.sequence.length===1&&z.sequence.charCodeAt(0)>=32)if(a()==="branch")s((Z)=>Z+z.sequence);else u((Z)=>Z+z.sequence)}if(n()==="preview"){if(_==="return"||_==="enter"){r("creating");let Z=i(),dt=h(),A=et(),te=Ps(A);try{let $e=Y(),F=Lt($e,A),nt=[{label:"Creating worktree",status:"pending"}];if(F.autoUpstream)nt.push({label:"Setting upstream",status:"pending"});if(F.copyFiles.length>0)nt.push({label:"Copying files",status:"pending"});if(F.linkFiles.length>0)nt.push({label:"Creating symlinks",status:"pending"});if(F.postCreate.length>0)nt.push({label:"Running hooks",status:"pending"});let pt=c(),U=[];if(pt)U=pt.split(/[,\s]+/).map((rt)=>rt.trim()).filter(Boolean);if(U.length>0)nt.push({label:"Setting focus",status:"pending"});if(U.length>0&&F.monorepo?.hooks&&F.monorepo.hooks.length>0){if(no(F.monorepo.hooks,U).length>0)nt.push({label:"Running monorepo hooks",status:"pending"})}x(nt);let Q=0;if(ot(Q,{status:"running"}),await E.add(Z,dt,{createBranch:!0},A),ot(Q,{status:"done"}),Q++,F.autoUpstream){ot(Q,{status:"running"});try{let rt=await E.getDefaultRemote(A);if(await E.remoteBranchExists(Z,rt,A))await E.setUpstream(Z,rt,A),ot(Q,{status:"done",message:`\u2192 ${rt}/${Z}`});else ot(Q,{status:"done",message:"no remote branch"})}catch(rt){ot(Q,{status:"error",message:rt.message})}Q++}if(F.copyFiles.length>0)ot(Q,{status:"running"}),wo(A,dt,F.copyFiles),ot(Q,{status:"done"}),Q++;if(F.linkFiles.length>0)ot(Q,{status:"running"}),bo(A,dt,F.linkFiles),ot(Q,{status:"done"}),Q++;let ft={OMW_BRANCH:Z,OMW_WORKTREE_PATH:dt,OMW_REPO_PATH:A};if(F.postCreate.length>0)ot(Q,{status:"running"}),await Wt(F.postCreate,{cwd:dt,env:ft,onOutput:(rt)=>ot(Q,{message:rt})}),ot(Q,{status:"done"}),Q++;if(U.length>0){ot(Q,{status:"running"});let{valid:rt}=Pn(dt,U);if(U=rt,rt.length>0)uo(dt,rt),ft.OMW_FOCUS_PATHS=rt.join(",");ot(Q,{status:"done"}),Q++}if(U.length>0&&F.monorepo?.hooks&&F.monorepo.hooks.length>0){ot(Q,{status:"running"});let rt=no(F.monorepo.hooks,U);if(rt.length>0)await So(rt,"postCreate",{cwd:dt,env:ft,repo:te,branch:Z,focusPaths:U,mainRepoPath:A,onOutput:(so)=>ot(Q,{message:so})});ot(Q,{status:"done"}),Q++}b("Worktree created successfully!"),r("done"),eo.success(`Worktree created: ${Z}`),e.refetch(),setTimeout(()=>{t.setActiveTab("list"),s(""),u(""),l("branch"),r("input")},1500)}catch($e){eo.error($e.message);let nt=g().findIndex((pt)=>pt.status==="running");if(nt>=0)ot(nt,{status:"error",message:$e.message});b(`${$e.message}`),r("error")}return}}if(n()==="error"){if(_==="escape"||_==="return"||_==="enter")r("input"),b("")}});let D=()=>o().width,L=()=>o().height,K=()=>Math.max(50,Math.min(80,D()-4)),tt=4,mt=()=>{if(n()==="input"){let z=it()&&a()==="branch"?G().length*2:0,_=i().length>0?4:0;return Math.max(21+tt,Math.min(21+tt+z+_,L()-4))}if(n()==="preview")return Math.max(13+tt,Math.min((c().length>0?15:13)+tt,L()-4));if(n()==="creating")return Math.max(9+tt,Math.min(g().length*2+7+tt,L()-4));if(n()==="done")return Math.max(11+tt,Math.min((c().length>0?15:13)+tt,L()-4));return Math.max(11+tt,Math.min(11+tt,L()-4))},q=()=>Math.max(K()-4,10),ut=()=>Math.max(q(),20);return React.createElement(Ie,{width:K(),height:mt(),borderColor:n()==="done"?f.text.success:n()==="error"?f.text.error:f.border.active,backgroundColor:f.bg.surface,gap:1,title:" Create Worktree ",footer:React.createElement(Qx,null,React.createElement("box",{height:1,width:q()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(q(),1)))),React.createElement(O,{when:n()==="input"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Tab:switch"),React.createElement("text",{fg:f.text.secondary},"\u2191\u2193:pick"),React.createElement("text",{fg:f.text.secondary},"Enter:confirm"),React.createElement("text",{fg:f.text.secondary},"Esc:cancel"))),React.createElement(O,{when:n()==="preview"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Enter:create"),React.createElement("text",{fg:f.text.secondary},"Esc:back"))),React.createElement(O,{when:n()==="creating"},React.createElement("text",{fg:f.text.secondary},"Creating worktree...")),React.createElement(O,{when:n()==="done"},React.createElement("text",{fg:f.text.secondary},"\u2713 Done \u2014 returning to list")),React.createElement(O,{when:n()==="error"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Enter:retry"),React.createElement("text",{fg:f.text.secondary},"Esc:back"))))},React.createElement(O,{when:n()==="input"},React.createElement("box",{height:1,width:q(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.accent},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"New Worktree"),React.createElement("text",{x:17,y:0,fg:f.text.secondary},fe())),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(q())),React.createElement("text",{fg:a()==="branch"?f.text.accent:f.text.secondary},"Branch name"),React.createElement("box",{width:ut(),height:1,backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.primary},i()),React.createElement(O,{when:a()==="branch"},React.createElement("text",{x:i().length+1,y:0,fg:f.text.accent},"\u2588"))),React.createElement(O,{when:it()&&a()==="branch"&&G().length>0},React.createElement(St,{each:G()},(z,_)=>React.createElement("box",{height:1,width:q(),backgroundColor:_()===y()?f.select.focusedBg:f.bg.surface},React.createElement("text",{x:1,y:0,fg:_()===y()?f.tab.active:f.text.primary},_()===y()?"\u25B8 ":" ",z.name),React.createElement("text",{x:Math.max(1+z.name.length+4,27),y:0,fg:f.text.secondary},z.isRemote?"(remote) ":"",z.lastCommitDate)))),React.createElement("text",{fg:f.text.secondary},"Tab to switch fields \xB7 \u2191\u2193 to select branch"),React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:a()==="focus"?f.text.accent:f.text.secondary},"Focus "),React.createElement("text",{fg:f.text.secondary},"(optional)")),React.createElement("box",{width:ut(),height:1,backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.primary},c()),React.createElement(O,{when:a()==="focus"},React.createElement("text",{x:c().length+1,y:0,fg:f.text.accent},"\u2588"))),React.createElement("text",{fg:f.text.secondary},"comma-separated paths, e.g. apps/web,apps/api"),React.createElement(O,{when:i().length>0},React.createElement("text",{fg:f.text.secondary},"Target path"),React.createElement("text",{fg:f.text.primary},T())),React.createElement("text",{fg:f.text.primary},"Type a branch name, e.g. feature/my-feature")),React.createElement(O,{when:n()==="preview"},React.createElement("box",{height:1,width:q(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.accent},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Confirm Worktree")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(q())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},h())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Focus")),React.createElement("text",{fg:f.text.accent},c()))),React.createElement("text",{fg:f.text.success},"\u2713 Ready to create. Press Enter to confirm.")),React.createElement(O,{when:n()==="creating"},React.createElement("box",{height:1,width:q(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.accent},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Creating Worktree")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(q())),React.createElement(St,{each:g()},(z)=>React.createElement("box",{height:1},React.createElement("text",{fg:z.status==="done"?f.text.success:z.status==="running"?f.text.accent:z.status==="error"?f.text.error:f.text.secondary},z.status==="done"?"\u2713":z.status==="running"?"\u27F3":z.status==="error"?"\u2717":"\u25CB"," ",z.label),React.createElement(O,{when:z.message},React.createElement("text",{x:z.label.length+4,y:0,fg:f.text.secondary},z.message))))),React.createElement(O,{when:n()==="done"},React.createElement("box",{height:1,width:q(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.success},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Worktree Created")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(q())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},h())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Focus")),React.createElement("text",{fg:f.text.accent},c()))),React.createElement("text",{fg:f.text.success},"\u2713 ",m())),React.createElement(O,{when:n()==="error"},React.createElement("box",{height:1,width:q(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.error},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Error")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(q())),React.createElement("text",{fg:f.text.error},"\u2717 Failed"),React.createElement("box",{width:ut(),height:1,backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.primary},m().slice(0,Math.max(ut()-3,10)))),React.createElement("text",{fg:f.text.secondary},"Press Enter or Escape to try again")))}var Rs=N(()=>{Et();re();de();ct();$t();Sn();Ce();me();Cr();yn();lr();Ht();zo()});import{useKeyboard as Tl,useTerminalDimensions as _l}from"@opentui/solid";function Es(){let t=Rt(),e=Ot(),o=_l(),[n,r]=k(!1),[i,s]=k(""),[c,u]=k(!1),a=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let S=m.find((R)=>R.path===b);if(S)return S}return m[t.selectedWorktreeIndex()]},l=()=>{t.setShowRemove(!1),r(!1),s(""),u(!1)},h=async(m)=>{let b=a();if(!b){l();return}r(!0),s("Removing...");try{let S=Y(),R=Lt(S,b.repoPath);if(R.postRemove.length>0)s("Running postRemove hooks..."),await Wt(R.postRemove,{cwd:b.path,env:{OMW_BRANCH:b.branch??"",OMW_WORKTREE_PATH:b.path,OMW_REPO_PATH:b.repoPath}}).catch(()=>{});await E.remove(b.path,{force:m},b.repoPath),s("Removed successfully!"),eo.success("Worktree removed");let y=e.worktrees()??[],M=t.selectedWorktreeIndex(),it=y[M-1]??y[M+1]??null;if(M>0)t.setSelectedWorktreeIndex(M-1);else t.setSelectedWorktreeIndex(0);t.setSelectedWorktreePath(it?.path??null),e.refetch(),setTimeout(l,1000)}catch(S){let R=S.message;if(!m&&R.includes("dirty"))s("Worktree has changes. Press Enter to force remove."),r(!1),u(!0);else s(`Failed: ${R}`),r(!1),eo.error(`Failed: ${R}`)}};Tl(async(m)=>{if(!t.showRemove())return;if(t.showCommandPalette())return;let b=m.name;if(b==="escape"){l();return}if(c()&&(b==="return"||b==="enter")){u(!1),await h(!0);return}if((b==="return"||b==="enter")&&!n())await h(!1)});let d=()=>a(),g=()=>Math.max(50,Math.min(80,o().width-4)),x=()=>10;return React.createElement(Ie,{width:g(),height:x(),borderColor:f.border.active,backgroundColor:f.bg.elevated,gap:1,title:" Remove Worktree ",backdrop:!0,footer:React.createElement("box",{flexDirection:"column"},React.createElement(O,{when:!n()&&!c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"[Enter] Confirm"),React.createElement("text",{fg:f.text.secondary},"[Esc] Cancel"))),React.createElement(O,{when:c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"[Enter] Force remove"),React.createElement("text",{fg:f.text.secondary},"[Esc] Cancel"))))},React.createElement(O,{when:!!d()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},d()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},d()?.path)),React.createElement(O,{when:c()},React.createElement("text",{fg:f.text.warning},i())),React.createElement(O,{when:n()},React.createElement("text",{fg:i().startsWith("Failed")?f.text.error:f.text.success},i()))),React.createElement(O,{when:!d()},React.createElement("text",{fg:f.text.secondary},"No worktree selected.")))}var Ms=N(()=>{Et();re();de();ct();$t();Ce();lr();Ht();zo()});function Ws(t){let[e,o]=k([]),n=(i)=>{o((s)=>s.filter((c)=>c.id!==i))},r=(i)=>{let s=`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`,c=i.duration??3000;o((u)=>[...u,{...i,id:s}].slice(-5)),setTimeout(()=>{n(s)},c)};return React.createElement(Os.Provider,{value:{toasts:e,addToast:r,removeToast:n}},t.children)}function Rn(){let t=to(Os);if(!t)throw Error("useToast must be used within ToastProvider");return t}var Os;var En=N(()=>{Et();Os=Ye()});import{useKeyboard as Gl}from"@opentui/solid";function Ds(t){let e=Rt(),o=Ot(),n=Rn(),[r,i]=k("confirming"),[s,c]=k(""),[u,a]=k(0),l=()=>{let x=o.worktrees()??[],m=e.selectedWorktrees(),b=[];for(let S of m){let R=x.find((y)=>y.path===S);if(R&&!R.isMain)b.push({branch:R.branch??"(detached)",path:R.path,repoPath:R.repoPath})}return b},h=()=>{e.setShowBulkActions(!1),i("confirming"),c(""),a(0)},d=async()=>{let x=l();if(x.length===0){h();return}i("executing"),a(0);let m=[];for(let b=0;b<x.length;b++){let S=x[b];c(`Removing ${S.branch} (${b+1}/${x.length})...`),a(b);try{let R=Y(),y=Lt(R,S.repoPath);if(y.postRemove.length>0)await Wt(y.postRemove,{cwd:S.path,env:{OMW_BRANCH:S.branch,OMW_WORKTREE_PATH:S.path,OMW_REPO_PATH:S.repoPath}}).catch(()=>{});await E.remove(S.path,{force:!1},S.repoPath)}catch(R){m.push(`${S.branch}: ${R.message}`)}}if(Mt(),e.clearSelection(),e.setSelectedWorktreeIndex(0),e.setSelectedWorktreePath(null),o.refetch(),m.length>0)i("error"),c(`Failed: ${m.join("; ")}`),n.addToast({message:`Failed to remove ${m.length} worktree(s)`,type:"error"}),setTimeout(h,3000);else i("done"),c(`Removed ${x.length} worktree(s) successfully!`),n.addToast({message:`Removed ${x.length} worktrees`,type:"success"}),setTimeout(h,1500)};Gl(async(x)=>{if(!e.showBulkActions())return;if(e.showCommandPalette())return;let m=x.name;if(r()==="executing")return;if(m==="escape"){h();return}if((m==="return"||m==="enter")&&r()==="confirming")await d()});let g=()=>l().length;return React.createElement("box",{x:0,y:0,width:t.w,height:t.h,backgroundColor:f.bg.base},React.createElement("box",{x:2,y:1,width:t.w-3,height:t.h-2,flexDirection:"column",backgroundColor:f.bg.base},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.error},"Bulk Delete Worktrees")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},"\u2500".repeat(Math.max(t.w-5,10)))),React.createElement("box",{height:1}),React.createElement(O,{when:r()==="confirming"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.warning},`Delete ${g()} worktree(s)?`)),React.createElement("box",{height:1}),React.createElement(St,{each:l().slice(0,Math.max(t.h-10,5))},(x)=>React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:f.text.accent},`\u2022 ${x.branch}`))),React.createElement(O,{when:g()>Math.max(t.h-10,5)},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:f.text.secondary},`... and ${g()-Math.max(t.h-10,5)} more`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Enter:delete all Esc:cancel"))),React.createElement(O,{when:r()==="executing"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.warning},s())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},`Progress: ${u()+1}/${g()}`))),React.createElement(O,{when:r()==="done"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.success},s()))),React.createElement(O,{when:r()==="error"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.error},s())))))}var Fs=N(()=>{Et();re();En();de();ct();$t();Ce();Ht()});import{useKeyboard as Hl,useTerminalDimensions as Nl}from"@opentui/solid";import{spawnSync as Jl}from"child_process";function Bs(){let t=Rt(),e=Nl(),o=Nt(),n=()=>{try{return Y()}catch{return null}},[r,i]=k(n()),[s,c]=k("");Hl((l)=>{if(t.activeTab()!=="config")return;if(t.showCommandPalette())return;let h=l.name;if(h==="e"){let d=process.env.EDITOR??process.env.VISUAL??"vi";ae(),Jl(d,[o],{stdio:"inherit"}),i(n()),c("Config reloaded"),setTimeout(()=>c(""),2000)}if(h==="r")i(n()),c("Reloaded"),setTimeout(()=>c(""),2000);if(h==="i")ae(),i(n()),c("Config initialized"),setTimeout(()=>c(""),2000)});let u=()=>e().width,a=()=>e().height;return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:f.bg.base,flexDirection:"column"},React.createElement("box",{width:"100%",height:"100%",border:!0,borderStyle:"rounded",borderColor:f.border.default,backgroundColor:f.bg.surface,title:" Configuration ",titleAlignment:"left",flexDirection:"column",paddingX:1,paddingY:1},React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:f.text.secondary},"Path:"),React.createElement("text",{fg:f.text.primary},o)),React.createElement(O,{when:!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.warning},"No config file found."),React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:f.text.secondary},"Press"),React.createElement("text",{fg:f.text.accent},"i"),React.createElement("text",{fg:f.text.secondary},"to initialize with defaults.")))),React.createElement(O,{when:!!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.accent},"Defaults"),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"worktreeDir")),React.createElement("text",{fg:f.text.primary},r()?.defaults?.worktreeDir??"../{repo}-{branch}")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"copyFiles")),React.createElement("text",{fg:f.text.primary},"[",(r()?.defaults?.copyFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"linkFiles")),React.createElement("text",{fg:f.text.primary},"[",(r()?.defaults?.linkFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"postCreate")),React.createElement("text",{fg:f.text.primary},"[",(r()?.defaults?.postCreate??[]).join(", "),"]"))),React.createElement("box",null,React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(u()-34,10)))),React.createElement(O,{when:(r()?.repos?.length??0)>0},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.accent},"Repos (",r()?.repos?.length,")"),React.createElement(St,{each:r()?.repos?.slice(0,4)},(l)=>React.createElement("box",{flexDirection:"column",gap:0},React.createElement("text",{fg:f.text.primary},l.path.split("/").pop()??l.path),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:f.text.secondary},"copyFiles")),React.createElement("text",{fg:f.text.primary},(l.copyFiles??[]).length>0?(l.copyFiles??[]).join(", "):"\u2014")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:f.text.secondary},"postCreate")),React.createElement("text",{fg:f.text.primary},(l.postCreate??[]).length>0?(l.postCreate??[]).join(", "):"\u2014")))))),React.createElement(O,{when:(r()?.repos?.length??0)===0},React.createElement("text",{fg:f.text.secondary},"No per-repo configs defined."))),React.createElement(O,{when:!!s()},React.createElement("text",{fg:f.text.success},s()))),React.createElement("box",{width:"100%",height:1,backgroundColor:f.bg.base,flexDirection:"row",gap:2},React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:f.text.secondary},"e"),React.createElement("text",{fg:f.text.primary},":edit")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:f.text.secondary},"r"),React.createElement("text",{fg:f.text.primary},":reload")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:f.text.secondary},"i"),React.createElement("text",{fg:f.text.primary},":init"))))}var Ls=N(()=>{Et();re();$t();Ht()});import{existsSync as io,readdirSync as As,rmSync as zl}from"fs";import{basename as $r,dirname as Sr,join as Is,resolve as ro}from"path";function vl(t){let e=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,e)}function js(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ts(t){if(!io(Nt()))return[];let e=t.find((c)=>c.isMain);if(!e)return[];let o=Y(),n=ro(e.path),r=$r(n);return[o.repos?.find((c)=>ro(c.path)===n)?.worktreeDir??o.defaults?.worktreeDir].filter((c)=>typeof c==="string").map((c)=>vl(c)).filter((c)=>!Sr(c).includes("{")&&$r(c).includes("{")).map((c)=>{let u=$r(c),a=`^${js(u).replace(/\\\{repo\\\}/g,js(r)).replace(/\\\{branch\\\}/g,".+")}$`;return{path:ro(Sr(c)),matches:(l)=>new RegExp(a).test(l)}})}function _s(t){let e=new Set;for(let o of t)if(!o.isMain)e.add(ro(Sr(o.path)));return[...e]}function Gs(t){let e=new Set(t.map((n)=>ro(n.path))),o=new Set;for(let n of Ts(t)){if(!io(n.path))continue;let r=As(n.path,{withFileTypes:!0}).filter((i)=>i.isDirectory()).filter((i)=>n.matches(i.name)).map((i)=>ro(Is(n.path,i.name)));for(let i of r)if(!e.has(i))o.add(i)}for(let n of _s(t)){if(!io(n))continue;let r=As(n,{withFileTypes:!0}).filter((i)=>i.isDirectory()).map((i)=>ro(Is(n,i.name)));for(let i of r)if(!e.has(i))o.add(i)}return[...o]}function kl(t){return Ts(t).some((e)=>io(e.path))||_s(t).some((e)=>io(e))}async function Ul(){let t=Bun.spawn(["git","--version"],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[e,o]=await Promise.all([new Response(t.stdout).text(),t.exited]);if(o!==0)return null;return e.trim().match(/git version (\d+\.\d+(?:\.\d+)?)/)?.[1]??null}async function Kl(){try{return await E.checkVersion(),{name:"Git version",status:"pass",message:`${await Ul()??"unknown"} (>= 2.17 required)`}}catch(e){if(e instanceof Io)return{name:"Git version",status:"fail",message:e.message};return{name:"Git version",status:"fail",message:`Check failed: ${e.message}`}}}async function Vl(){try{let o=(Y().repos??[]).map((n)=>n.path).filter((n)=>!io(n));if(o.length>0)return{name:"Configuration",status:"warn",message:"missing repository paths",detail:o};return{name:"Configuration",status:"pass",message:"valid"}}catch(e){return{name:"Configuration",status:"fail",message:`Check failed: ${e.message}`}}}function ql(t){let o=t.map((n)=>n.path).filter((n)=>!io(n));if(o.length>0)return{name:"Stale worktrees",status:"warn",message:"missing worktree paths",detail:o};return{name:"Stale worktrees",status:"pass",message:"none"}}function Xl(t){try{let o=Gs(t);if(o.length===0)return{name:"Orphaned directories",status:"pass",message:kl(t)?"none":"no worktree directory"};return{name:"Orphaned directories",status:"warn",message:"orphaned worktree directories found",detail:o}}catch(o){return{name:"Orphaned directories",status:"fail",message:`Check failed: ${o.message}`}}}function Zl(t){let o=t.filter((r)=>r.isLocked);if(o.length===0)return{name:"Worktree locks",status:"pass",message:"all clear"};return{name:"Worktree locks",status:"warn",message:"locked worktrees present",detail:o.map((r)=>{let i=r.branch??"detached";if(!r.lockReason)return`${i} - ${r.path} (potential stale lock: no reason)`;return`${i} - ${r.path} (reason: ${r.lockReason})`})}}function Ql(t){let o=t.filter((n)=>n.isDirty&&!n.isMain);if(o.length===0)return{name:"Dirty worktrees",status:"pass",message:"none"};return{name:"Dirty worktrees",status:"warn",message:"dirty non-main worktrees found",detail:o.map((n)=>`${n.branch??"detached"} - ${n.path}`)}}async function Po(t){let e=await E.list(t).catch(()=>[]),o=[await Kl(),await Vl(),ql(e),Xl(e),Zl(e),Ql(e)];return{checks:o,healthy:o.every((n)=>n.status==="pass")}}async function Yl(t){try{return await E.prune(t),{action:"Prune stale worktrees",success:!0}}catch(e){return{action:"Prune stale worktrees",success:!1,detail:e.message}}}async function th(t){let e=[];try{let o=Gs(await E.list(t).catch(()=>[]));for(let n of o)try{zl(n,{recursive:!0,force:!0}),e.push({action:"Remove orphaned directory",success:!0,detail:n})}catch(r){e.push({action:"Remove orphaned directory",success:!1,detail:`${n}: ${r.message}`})}}catch(o){e.push({action:"Remove orphaned directories",success:!1,detail:o.message})}return e}async function eh(t){let e=[];try{let n=(await E.list(t)).filter((r)=>r.isLocked&&!r.lockReason);for(let r of n)try{await E.unlock(r.path,t),e.push({action:"Unlock stale lock",success:!0,detail:`${r.branch??"detached"} - ${r.path}`})}catch(i){e.push({action:"Unlock stale lock",success:!1,detail:`${r.path}: ${i.message}`})}}catch(o){e.push({action:"Fix stale locks",success:!1,detail:o.message})}return e}async function Mn(t){let e=[];return e.push(await Yl(t)),e.push(...await th(t)),e.push(...await eh(t)),e}var Pr=N(()=>{$t();ct();Zt()});import{useKeyboard as oh,useTerminalDimensions as nh}from"@opentui/solid";function Hs(){let t=Rt(),e=nh(),[o,n]=k(null),[r,i]=k(!0),[s,c]=k(""),[u,a]=k(!1),[l,h]=k([]),d=async()=>{i(!0),c(""),h([]);try{let G=await Po();n(G)}catch(G){c(G.message)}i(!1)},g=async()=>{if(o()?.healthy)return;a(!0);try{let G=await Mn();h(G);let ot=await Po();n(ot)}catch(G){c(G.message)}a(!1)};d(),oh((G)=>{if(t.activeTab()!=="doctor")return;if(t.showCommandPalette())return;let ot=G.name;if(ot==="r")d();if(ot==="f"&&!r()&&!u()&&!o()?.healthy)g()});let x=()=>e().width,m=()=>e().height,b=()=>Math.max(50,Math.min(80,x()-4)),S=()=>{let G=it()+st()+8+(st()>0?2:0);return Math.max(12,Math.min(G,m()-4))},R=()=>Math.max(b()-4,10),y=(G)=>{if(G==="pass")return"\u2713";if(G==="warn")return"\u26A0";return"\u2717"},M=(G)=>{if(G==="pass")return f.text.success;if(G==="warn")return f.text.warning;return f.text.error},it=()=>o()?.checks.length??0,st=()=>l().length;return React.createElement(Ie,{width:b(),height:S(),borderColor:o()?.healthy?f.text.success:o()?f.text.warning:f.border.default,backgroundColor:f.bg.surface,title:" Doctor ",footer:React.createElement(Jg,null,React.createElement("box",{height:1,width:R()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(R(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"r:recheck"),React.createElement(O,{when:!o()?.healthy},React.createElement("text",{fg:f.text.secondary},"f:fix")),React.createElement("text",{fg:f.text.secondary},"Esc:back")))},React.createElement(O,{when:r()},React.createElement("text",{fg:f.text.secondary},"Running health checks...")),React.createElement(O,{when:u()},React.createElement("text",{fg:f.text.accent},"Running auto-fix...")),React.createElement(O,{when:!r()&&!u()&&!!s()},React.createElement("text",{fg:f.text.error},"Error: ",s())),React.createElement(O,{when:!r()&&!u()&&!s()&&!!o()},React.createElement("text",{fg:f.text.accent},"Health Checks"),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(R())),React.createElement(St,{each:o().checks},(G)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:M(G.status)},y(G.status)),React.createElement("text",{x:2,y:0,fg:f.text.primary},G.name,":"),React.createElement("text",{x:G.name.length+4,y:0,fg:f.text.secondary},G.message))}),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(R())),React.createElement("text",{fg:o().healthy?f.text.success:f.text.warning},o().healthy?"\u2713 All checks passed":`${o().checks.filter((G)=>G.status==="fail").length} error(s), ${o().checks.filter((G)=>G.status==="warn").length} warning(s) found`),React.createElement(O,{when:st()>0},React.createElement("text",{fg:f.text.accent},"Fix Results"),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(R())),React.createElement(St,{each:l()},(G)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:G.success?f.text.success:f.text.error},G.success?"\u2713":"\u2717"),React.createElement("text",{x:2,y:0,fg:f.text.primary},G.action),React.createElement(O,{when:!!G.detail},React.createElement("text",{x:G.action.length+3,y:0,fg:f.text.secondary},"(",G.detail,")")))}))))}var Ns=N(()=>{Et();re();Pr();Ht();zo()});var vs={};xt(vs,{writePin:()=>Rr,removePin:()=>Er,readPin:()=>ko,listPinnedWorktrees:()=>Mr,isPinned:()=>je});import{readFileSync as Js,writeFileSync as rh,unlinkSync as ih,mkdirSync as sh,existsSync as yr}from"fs";import{join as ch,dirname as zs}from"path";function vo(t){return se(t,"omw-pin")}function ah(t){let e=vo(t),o=zs(e),n=ch(o,"HEAD"),r=Js(n,"utf-8").trim(),i=r.match(/^ref:\s+refs\/heads\/(.+)$/);return i?i[1]:r}function Rr(t,e){let o=vo(t),n={branch:ah(t),pinnedAt:new Date().toISOString(),...e?{reason:e}:{}};sh(zs(o),{recursive:!0}),rh(o,JSON.stringify(n),{encoding:"utf-8",mode:384})}function ko(t){let e=vo(t);if(!yr(e))return null;return JSON.parse(Js(e,"utf-8"))}function Er(t){let e=vo(t);if(!yr(e))return;ih(e)}function je(t){return yr(vo(t))}function Mr(t){return t.filter((e)=>je(e.path))}var yo=N(()=>{Oe()});import{useKeyboard as fh}from"@opentui/solid";function ks(){let t=Rt(),e=Ot(),o=()=>e.worktrees()??[],n=()=>t.selectedWorktreeIndex(),r=(l)=>{let h=Math.max(0,Math.min(l,Math.max(o().length-1,0))),d=o()[h];t.setSelectedWorktreeIndex(h),t.setSelectedWorktreePath(d?.path??null)},i=ne(()=>{let l=o(),h=e.isMultiRepo(),d=[];if(!h){for(let b=0;b<l.length;b++)d.push({type:"worktree",wt:l[b],flatIdx:b});return d}let g=new Map;for(let b of l){let S=g.get(b.repoName);if(S)S.push(b);else g.set(b.repoName,[b])}let x=0,m=!0;for(let[b,S]of g){if(!m)d.push({type:"separator"});m=!1,d.push({type:"header",repoName:b});for(let R of S)d.push({type:"worktree",wt:R,flatIdx:x}),x++}return d}),s=()=>t.selectedWorktrees().size;fh((l)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;let h=l.name,d=o();if(h==="j"||h==="down")r(Math.min(n()+1,d.length-1));if(h==="k"||h==="up")r(Math.max(n()-1,0));if(h==="space"){let g=n(),x=d[g];if(x&&!x.isMain)t.toggleWorktreeSelection(x.path)}if(l.ctrl&&h==="a")t.selectAllNonMain(d.filter((g)=>!g.isMain).map((g)=>g.path))});let c=(l)=>{if(l.isLocked)return"\uD83D\uDD12";if(l.isDirty)return"\u25CF";return"\u2713"},u=(l)=>{if(l.isLocked)return f.text.warning;if(l.isDirty)return f.text.error;return f.text.success},a=(l,h)=>{let d=l.branch??"(detached)",g=Math.max(8,Uo-(h?9:7));return d.length>g?d.slice(0,g-1)+"\u2026":d};return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:f.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:0},React.createElement(O,{when:e.loading()},React.createElement("text",{fg:f.text.secondary},"Loading...")),React.createElement(O,{when:!e.loading()},React.createElement(St,{each:i()},(l)=>{if(l.type==="header")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:f.text.accent},React.createElement("b",null,l.repoName)));if(l.type==="separator")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Uo)));let h=l.wt,d=()=>l.flatIdx===n(),g=()=>t.selectedWorktrees().has(h.path);return React.createElement("box",{width:"100%",height:1,backgroundColor:d()?f.select.focusedBg:g()?f.bg.elevated:f.bg.surface,paddingX:1,onMouseDown:()=>r(l.flatIdx)},React.createElement("text",{x:0,y:0,fg:u(h)},c(h)),React.createElement("text",{x:2,y:0,fg:d()?f.tab.active:f.text.primary},a(h,!1)),React.createElement(O,{when:g()},React.createElement("text",{x:Uo-1,y:0,fg:f.text.accent},"\u2713")),React.createElement(O,{when:!!Kt(h.path)},React.createElement("text",{x:Uo-(g()?3:1),y:0,fg:f.text.accent},"S")),React.createElement(O,{when:je(h.path)},React.createElement("text",{x:Uo-(g()?5:3)+(Kt(h.path)?0:2),y:0,fg:f.text.warning},"P")))}),React.createElement(O,{when:s()>0},React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:f.text.accent},`Selected: ${s()}`)))))}var Uo=24;var Us=N(()=>{Et();re();de();Ht();yo();De()});import{useKeyboard as lh,useTerminalDimensions as hh}from"@opentui/solid";function Ks(){let t=Rt(),e=Ot(),o=hh(),[n,r]=k(""),[i,s]=k(0),c=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let S=m.find((R)=>R.path===b);if(S)return S}return m[t.selectedWorktreeIndex()]},u=()=>{let m=process.env.VISUAL||process.env.EDITOR;if(m)return m;let b=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let S of b)try{if(Bun.spawnSync(["which",S],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return S}catch{}return null},a=ne(()=>[{id:"add",label:"Add Worktree",description:"Create a new git worktree",action:()=>{t.setActiveTab("add"),t.setShowCommandPalette(!1)}},{id:"delete",label:"Delete Worktree",description:"Remove the selected worktree",action:()=>{let m=c();if(!m||m.isMain)return;t.setShowRemove(!0),t.setShowCommandPalette(!1)}},{id:"open-editor",label:"Open in Editor",description:"Open selected worktree in IDE",action:()=>{let m=c();if(!m)return;let b=u();if(!b)return;t.setShowCommandPalette(!1),Bun.spawn([b,m.path],{stdout:"inherit",stderr:"inherit"})}},{id:"refresh",label:"Refresh",description:"Reload worktree list",action:()=>{e.refetch(),t.setShowCommandPalette(!1)}},{id:"config",label:"Open Config",description:"View configuration",action:()=>{t.setActiveTab("config"),t.setShowCommandPalette(!1)}},{id:"doctor",label:"Run Doctor",description:"Check worktree health",action:()=>{t.setActiveTab("doctor"),t.setShowCommandPalette(!1)}},...hn.map((m)=>({id:`theme:${m}`,label:`Theme: ${is[m]}`,description:"Switch color theme",action:()=>{un(m);try{let b=Nt(),S={...Y()};S.theme=m,No(b,JSON.stringify(S,null,2))}catch{}t.setShowCommandPalette(!1)}})),{id:"quit",label:"Quit",description:"Exit oh-my-worktree",action:()=>process.exit(0)}]),l=ne(()=>{let m=n().toLowerCase();if(!m)return a();return a().filter((b)=>b.label.toLowerCase().includes(m)||b.description.toLowerCase().includes(m))});lh((m)=>{if(!t.showCommandPalette())return;let b=m.name;if(b==="escape"){t.setShowCommandPalette(!1),r(""),s(0);return}if(b==="return"||b==="enter"){let S=l()[i()];if(S)S.action();r(""),s(0);return}if(b==="down"||b==="j"){s((S)=>Math.min(S+1,l().length-1));return}if(b==="up"||b==="k"){s((S)=>Math.max(S-1,0));return}if(b==="backspace"){r((S)=>S.slice(0,-1)),s(0);return}if(m.sequence&&m.sequence.length===1&&m.sequence.charCodeAt(0)>=32)r((S)=>S+m.sequence),s(0)});let h=()=>Math.max(50,Math.min(80,o().width-4)),d=()=>Math.max(10,Math.min(l().length+8,o().height-4)),g=()=>h()-4,x=()=>d()-8;return React.createElement(Ie,{width:h(),height:d(),borderColor:f.border.active,backgroundColor:f.bg.surface,title:" Command Palette ",footer:React.createElement(aw,null,React.createElement("box",{height:1,width:g()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(g(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"\u2191\u2193:navigate"),React.createElement("text",{fg:f.text.secondary},"Enter:run"),React.createElement("text",{fg:f.text.secondary},"Esc:close")))},React.createElement("box",{height:1,width:g(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.accent},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},n()),React.createElement("text",{x:3+n().length,y:0,fg:f.text.accent},"\u2588")),React.createElement("box",{height:1,width:g()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(g(),1)))),React.createElement("box",{width:g(),height:x(),backgroundColor:f.bg.surface,flexDirection:"column"},React.createElement(St,{each:l().slice(0,x())},(m,b)=>{let S=()=>b()===i();return React.createElement("box",{height:1,width:g(),backgroundColor:S()?f.select.focusedBg:f.bg.surface,onMouseDown:()=>{s(b()),m.action()}},React.createElement("text",{x:2,y:0,fg:S()?f.tab.active:f.text.primary},m.label),React.createElement("text",{x:Math.max(25,m.label.length+4),y:0,fg:f.text.secondary},m.description))}),React.createElement(O,{when:l().length===0},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:f.text.secondary},"No commands found")))))}var Vs=N(()=>{Et();re();de();Ht();zo();$t()});import{useTerminalDimensions as uh}from"@opentui/solid";function ph(t){if(t==="success")return"\u2713";if(t==="warning")return"\u26A0";if(t==="error")return"\u2717";return"\u2139"}function dh(t){if(t==="success")return f.text.success;if(t==="warning")return f.text.warning;if(t==="error")return f.text.error;return f.text.primary}function qs(){let t=uh(),e=()=>Math.min(60,Math.max(24,t().width-4));return React.createElement("box",{x:(()=>Math.max(0,t().width-e()-1))(),y:1,width:e(),height:5,flexDirection:"column"},React.createElement(St,{each:Rn().toasts()},(n,r)=>React.createElement("box",{x:0,y:r(),width:e(),height:1,backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:dh(n.type)},`${ph(n.type)} ${n.message}`))))}var Xs=N(()=>{Et();En();Ht()});var Ys={};xt(Ys,{launchTUI:()=>$h});import{render as mh,useKeyboard as xh,useTerminalDimensions as gh,useRenderer as wh}from"@opentui/solid";import{resolve as Zs}from"path";function bh(){let t=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let e of t)try{if(Bun.spawnSync(["which",e],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return e}catch{}return null}function Ch(t){let e=Rt(),o=Ot(),n=wh(),[r,i]=k(!1),s=gh(),c=()=>{let m=o.worktrees()??[],b=e.selectedWorktreePath();if(b){let S=m.find((R)=>R.path===b);if(S)return S}return m[e.selectedWorktreeIndex()]};pe(()=>{let m=o.worktrees()??[],b=m.map((M)=>M.path);if(e.pruneSelectedWorktrees(b),m.length===0){if(e.selectedWorktreeIndex()!==0)e.setSelectedWorktreeIndex(0);if(e.selectedWorktreePath()!==null)e.setSelectedWorktreePath(null);return}let S=e.selectedWorktreePath();if(S){let M=m.findIndex((it)=>it.path===S);if(M>=0){if(M!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(M);return}}let R=Math.min(e.selectedWorktreeIndex(),m.length-1),y=m[R]?.path??null;if(R!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(R);if(y!==e.selectedWorktreePath())e.setSelectedWorktreePath(y)}),xh((m)=>{if(e.showCommandPalette())return;let b=m.name;if(m.ctrl&&b==="p"){e.setShowCommandPalette(!0);return}if(b==="escape"){if(e.showBulkActions()){e.setShowBulkActions(!1);return}if(e.showDetailView()){e.setShowDetailView(!1);return}if(e.showRemove()){e.setShowRemove(!1);return}if(r()){i(!1);return}if(e.activeTab()!=="list"){e.setActiveTab("list");return}}if(e.showBulkActions())return;if(e.showRemove())return;if(e.activeTab()==="add")return;if(e.activeTab()==="list"){if(e.showDetailView())return;if(b==="a"){e.setActiveTab("add");return}if(b==="r"){o.refetch();return}if(b==="d"){let S=c();if(S&&!S.isMain)e.setShowRemove(!0);return}if(b==="o"){let S=c();if(S){let R=process.env.VISUAL||process.env.EDITOR||bh();if(R)Bun.spawn([R,S.path],{stdout:"inherit",stderr:"inherit"})}return}}if(b==="h"){e.setActiveTab("doctor");return}if(b==="q"||b==="Q")n.destroy();if(b==="?")i((S)=>!S)});let u=()=>s().width,a=()=>s().height,l=()=>t.repoPath.split("/").pop()??"",h=()=>{let m=o.repoNames();if(m.length<=1)return l();return`${m.length} repos`},d=()=>{let m=o.worktrees()??[];return`${l()} \xB7 ${m.length} worktrees`},g=()=>{return` Worktrees (${(o.worktrees()??[]).length}) `},x=()=>u()-Qs-1;return React.createElement("box",{width:u(),height:a(),backgroundColor:f.bg.base,flexDirection:"column"},React.createElement("box",{height:1,backgroundColor:f.bg.overlay},React.createElement("text",{x:1,y:0,fg:f.text.accent},"\uD83C\uDF33 oh-my-worktree"),React.createElement("text",{x:u()-h().length-2,y:0,fg:f.text.secondary},h())),React.createElement("box",{flexGrow:1,flexDirection:"row"},React.createElement("box",{width:Qs,flexShrink:0,backgroundColor:f.bg.surface,border:!0,borderStyle:"rounded",borderColor:f.border.default,title:g(),titleAlignment:"left"},React.createElement(ks,null)),React.createElement("box",{width:1}),React.createElement("box",{flexGrow:1,backgroundColor:f.bg.base},React.createElement(O,{when:e.activeTab()!=="config"&&!e.showRemove()&&!e.showBulkActions()},React.createElement(hs,null)),React.createElement(O,{when:e.activeTab()==="list"&&e.showBulkActions()},React.createElement(Ds,{w:x(),h:a()-3})),React.createElement(O,{when:e.activeTab()==="config"},React.createElement(Bs,null)))),React.createElement(qs,null),React.createElement("toaster",{position:"bottom-right"}),React.createElement("box",{height:1,backgroundColor:f.bg.overlay},React.createElement("text",{x:0,y:0,fg:f.border.subtle},"\u2500".repeat(u()))),React.createElement("box",{height:1,backgroundColor:f.bg.overlay},React.createElement("text",{x:1,y:0,fg:f.text.secondary},"d:delete a:add o:open r:refresh ^P:cmd h:health q:quit")),React.createElement(O,{when:r()&&!e.showCommandPalette()},React.createElement("box",{x:Math.max(0,Math.floor((u()-Math.max(40,Math.min(60,u()-4)))/2)),y:Math.max(0,Math.floor((a()-14)/2)),width:Math.max(40,Math.min(60,u()-4)),height:14,border:!0,borderStyle:"rounded",borderColor:f.border.active,backgroundColor:f.bg.elevated,title:" Keyboard Shortcuts ",titleAlignment:"left",flexDirection:"column",paddingX:1,paddingY:1,position:"absolute"},React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"q"),React.createElement("text",{x:8,fg:f.text.primary},"Quit")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"j/k"),React.createElement("text",{x:8,fg:f.text.primary},"Navigate list")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"a"),React.createElement("text",{x:8,fg:f.text.primary},"Add worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"d"),React.createElement("text",{x:8,fg:f.text.primary},"Delete worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"r"),React.createElement("text",{x:8,fg:f.text.primary},"Refresh list")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"Ctrl+P"),React.createElement("text",{x:8,fg:f.text.primary},"Command palette")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"?"),React.createElement("text",{x:8,fg:f.text.primary},"Toggle help")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.accent},"Press ? to close")))),React.createElement(O,{when:e.activeTab()==="add"},React.createElement(ys,null)),React.createElement(O,{when:e.activeTab()==="doctor"},React.createElement(Hs,null)),React.createElement(O,{when:e.showRemove()},React.createElement(Es,null)),React.createElement(O,{when:e.showCommandPalette()},React.createElement(Ks,null)))}async function $h(){if(process.stdout.isTTY)process.stdout.write("\x1B]0;Oh My Worktree\x07");let t=await E.getMainRepoPath().catch(()=>process.cwd()),e=[t];try{let o={...Y()},n=Be(o),r=new Set([Zs(t)]);for(let i of n){let s=Zs(i);if(!r.has(s))r.add(s),e.push(i)}if(o.theme&&hn.includes(o.theme))un(o.theme)}catch{}await mh(()=>React.createElement(es,{repoPath:t,repoPaths:e},React.createElement(rs,{repoPaths:e},React.createElement(Ws,null,React.createElement(Ch,{repoPath:t})))),{exitOnCtrlC:!0,useMouse:!0})}var Qs=28;var tc=N(()=>{Et();re();de();ct();us();Rs();Ms();Fs();Ls();Ns();Us();Ht();Vs();En();Xs();$t()});import*as ec from"readline";async function Te(t){let e=ec.createInterface({input:process.stdin,output:process.stdout});return new Promise((o)=>{e.question(t,(n)=>{e.close(),o(n.toLowerCase()==="y"||n.toLowerCase()==="yes")})})}async function at(){return E.getMainRepoPath().catch(()=>process.cwd())}function Vt(t,e){let o=t.find((n)=>n.branch===e||n.path===e||n.path.endsWith("/"+e));if(!o)console.error(`Error: no worktree found for '${e}'`),process.exit(1);return o}function wt(t){if(t instanceof Gt)console.error(`Git error: ${t.message}`);else console.error(`Error: ${t.message}`);process.exit(1)}var Dt=N(()=>{ct();Zt()});import{mkdirSync as Sh,writeFileSync as Ph}from"fs";import{dirname as yh}from"path";function Rh(t){return se(t,"omw-pr")}function oc(t,e){let o=Rh(t);Sh(yh(o),{recursive:!0}),Ph(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}var nc=N(()=>{Oe()});import{appendFileSync as Eh,existsSync as Mh,mkdirSync as Oh,readFileSync as rc,rmSync as Wh,writeFileSync as Dh}from"fs";import{dirname as Fh}from"path";function Or(t){return se(t,"omw-activity.log")}function qt(t,e){let o=Or(t);Oh(Fh(o),{recursive:!0}),Eh(o,`${JSON.stringify(e)}
16
+ `,{encoding:"utf-8",mode:384});let n=rc(o,"utf-8").split(/\r?\n/).filter(Boolean);if(n.length>Bh){let r=n.slice(-Lh);Dh(o,`${r.join(`
17
17
  `)}
18
- `,{encoding:"utf-8",mode:384})}}function rc(t,e){let o=Mr(t),n=e?.limit??50;if(!Fh(o))return[];return Rr(o,"utf-8").split(/\r?\n/).filter(Boolean).map((s)=>JSON.parse(s)).reverse().slice(0,n)}function ic(t){Lh(Mr(t),{force:!0})}var Th=1000,_h=500;var Fe=()=>{};var sc={};xt(sc,{default:()=>vh});import{basename as Nh,resolve as Hh}from"path";import{existsSync as Jh}from"fs";var zh,vh;var cc=H(()=>{at();Ct();$t();me();Cn();gn();le();nc();Fe();wr();Pe();zh={command:"add [branch] [path]",describe:"Create a new worktree for a branch",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).positional("path",{type:"string",describe:"Worktree directory path"}).option("create",{type:"boolean",alias:"c",describe:"Optional compatibility flag; missing branches are created automatically"}).option("base",{type:"string",alias:"b",describe:"Base branch/commit for new branch"}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("template",{type:"string",alias:"t",describe:"Use a named template from config"}).option("pr",{type:"number",describe:"Create worktree from a GitHub PR number (requires gh CLI)"}).option("session",{type:"boolean",alias:"s",describe:"Create a tmux session for this worktree"}).option("layout",{type:"string",describe:"Session layout name from config"}),handler:async(t)=>{let{branch:e,pr:o}=t,n=await E.getMainRepoPath().catch(()=>process.cwd()),r=Nh(n);if(!e&&!o)console.error("Error: specify a branch or use --pr <number>."),process.exit(1);if(o)try{let x=Bun.spawn(["gh","pr","view",String(o),"--json","headRefName","--jq",".headRefName"],{cwd:n,stdout:"pipe",stderr:"pipe"}),[m,b,S]=await Promise.all([new Response(x.stdout).text(),new Response(x.stderr).text(),x.exited]);if(S!==0)console.error(`Error: failed to resolve PR #${o}: ${b.trim()}`),console.error("Make sure 'gh' CLI is installed and authenticated."),process.exit(1);if(e=m.trim(),!e)console.error(`Error: PR #${o} has no branch name`),process.exit(1);console.log(`PR #${o} \u2192 branch '${e}'`)}catch{console.error("Error: 'gh' CLI not found. Install it from https://cli.github.com"),process.exit(1)}if(!e)console.error("Error: could not determine branch name."),process.exit(1);let i=e.replace(/\//g,"-"),s=Y(),c=Bt(s,n),f=t.template;if(f){let x=mn(s,f);if(!x){let m=Object.keys(s.templates??{});if(console.error(`Error: template '${f}' not found.`),m.length>0)console.error(`Available templates: ${m.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}if(c=xn(c,x),x.base&&!t.base)t.base=x.base;console.log(`Using template '${f}'`)}let a=t.path??c.worktreeDir,u=dn(a,{repo:r,branch:i}),h=Hh(n,u);console.log(`Creating worktree for branch '${e}'...`),console.log(` Target: ${h}`);let w=(await E.list(n)).find((x)=>x.branch===e);if(w)console.error(`Error: branch '${e}' is already checked out in ${w.path}`),process.exit(1);if(Jh(h))console.error(`Error: directory already exists: ${h}`),process.exit(1);try{await E.add(e,h,{createBranch:Boolean(t.create),base:t.base},n),console.log(" \u2713 Worktree created");try{Ut(n,{timestamp:new Date().toISOString(),event:"create",branch:e,path:h})}catch{}if(o)oc(h,{number:o,branch:e,createdAt:new Date().toISOString()}),console.log(` \u2713 PR #${o} metadata saved`)}catch(x){if(x instanceof it)console.error(`Error creating worktree: ${x.stderr||x.message}`);else console.error(`Error: ${x.message}`);process.exit(1)}if(c.autoUpstream)try{let x=await E.getDefaultRemote(n);if(await E.remoteBranchExists(e,x,n))await E.setUpstream(e,x,n),console.log(` \u2713 Upstream tracking set \u2192 ${x}/${e}`);else console.log(" \u2139 No remote branch found \u2014 upstream tracking skipped")}catch(x){console.warn(` \u26A0 Could not set upstream tracking: ${x.message}`)}try{if(c.copyFiles.length>0){console.log(` Copying files: ${c.copyFiles.join(", ")}`);let P=ho(n,h,c.copyFiles);for(let M of P.warnings)console.log(` \u26A0 ${M}`);if(P.copied.length>0)console.log(` \u2713 Copied: ${P.copied.join(", ")}`)}if(c.linkFiles.length>0){console.log(` Linking files: ${c.linkFiles.join(", ")}`);let P=uo(n,h,c.linkFiles);for(let M of P.warnings)console.log(` \u26A0 ${M}`);if(P.linked.length>0)console.log(` \u2713 Linked: ${P.linked.join(", ")}`)}if(c.sharedDeps&&c.sharedDeps.paths&&c.sharedDeps.paths.length>0){let P=c.sharedDeps.strategy??"symlink";console.log(` Sharing dependencies (${P}): ${c.sharedDeps.paths.join(", ")}`);let M=Ps(n,h,c.sharedDeps);for(let st of M.warnings)console.log(` \u26A0 ${st}`);if(M.linked.length>0)console.log(` \u2713 Shared (${P}): ${M.linked.join(", ")}`);if(M.copied.length>0)console.log(` \u2713 Copied: ${M.copied.join(", ")}`)}let x={OMW_BRANCH:e,OMW_WORKTREE_PATH:h,OMW_REPO_PATH:n},m=t.focus,b=[];if(m&&m.length>0)b=m.flatMap((P)=>P.split(/[,\s]+/)).map((P)=>P.trim()).filter(Boolean);if(b.length>0){let{valid:P,invalid:M}=bn(h,b);if(M.length>0)console.log(` \u26A0 Focus paths not found (will be skipped): ${M.join(", ")}`);if(P.length>0)so(h,P),console.log(` \u2713 Focus set: ${P.join(", ")}`);x.OMW_FOCUS_PATHS=P.join(",")}if(c.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(c.postCreate,{cwd:h,env:x,onOutput:(P)=>console.log(` ${P}`)}),console.log(" \u2713 Hooks completed");if(b.length>0&&c.monorepo?.hooks&&c.monorepo.hooks.length>0){let P=Xe(c.monorepo.hooks,b);if(P.length>0)console.log(" Running monorepo hooks..."),await xo(P,"postCreate",{cwd:h,env:x,repo:r,branch:e,focusPaths:b,mainRepoPath:n,onOutput:(M)=>console.log(` ${M}`)}),console.log(" \u2713 Monorepo hooks completed")}let S=Me(s);if(t.session||S.autoCreate)if(await ao()){let M=t.layout??S.defaultLayout,st=wn(s,M),ct=await ln(e,h,{layout:st,prefix:S.prefix,attach:!1,layoutName:M});console.log(` \u2713 Session created: ${ct}`)}else console.log(" \u26A0 tmux not found \u2014 session skipped");console.log(`
18
+ `,{encoding:"utf-8",mode:384})}}function ic(t,e){let o=Or(t),n=e?.limit??50;if(!Mh(o))return[];return rc(o,"utf-8").split(/\r?\n/).filter(Boolean).map((s)=>JSON.parse(s)).reverse().slice(0,n)}function sc(t){Wh(Or(t),{force:!0})}var Bh=1000,Lh=500;var _e=N(()=>{Oe()});var cc={};xt(cc,{default:()=>_h});import{basename as Ah,resolve as Ih}from"path";import{existsSync as jh}from"fs";var Th,_h;var ac=N(()=>{ct();Zt();$t();Dt();Ce();yn();Sn();me();nc();_e();Cr();De();Th={command:"add [branch] [path]",describe:"Create a new worktree for a branch",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).positional("path",{type:"string",describe:"Worktree directory path"}).option("create",{type:"boolean",alias:"c",describe:"Optional compatibility flag; missing branches are created automatically"}).option("base",{type:"string",alias:"b",describe:"Base branch/commit for new branch"}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("template",{type:"string",alias:"t",describe:"Use a named template from config"}).option("pr",{type:"number",describe:"Create worktree from a GitHub PR number (requires gh CLI)"}).option("session",{type:"boolean",alias:"s",describe:"Create a tmux session for this worktree"}).option("layout",{type:"string",describe:"Session layout name from config"}),handler:async(t)=>{let{branch:e,pr:o}=t,n=await at(),r=Ah(n);if(!e&&!o)console.error("Error: specify a branch or use --pr <number>."),process.exit(1);if(o)try{let x=Bun.spawn(["gh","pr","view",String(o),"--json","headRefName","--jq",".headRefName"],{cwd:n,stdout:"pipe",stderr:"pipe"}),[m,b,S]=await Promise.all([new Response(x.stdout).text(),new Response(x.stderr).text(),x.exited]);if(S!==0)console.error(`Error: failed to resolve PR #${o}: ${b.trim()}`),console.error("Make sure 'gh' CLI is installed and authenticated."),process.exit(1);if(e=m.trim(),!e)console.error(`Error: PR #${o} has no branch name`),process.exit(1);console.log(`PR #${o} \u2192 branch '${e}'`)}catch{console.error("Error: 'gh' CLI not found. Install it from https://cli.github.com"),process.exit(1)}if(!e)console.error("Error: could not determine branch name."),process.exit(1);let i=e.replace(/\//g,"-"),s=Y(),c=Lt(s,n),u=t.template;if(u){let x=bn(s,u);if(!x){let m=Object.keys(s.templates??{});if(console.error(`Error: template '${u}' not found.`),m.length>0)console.error(`Available templates: ${m.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}if(c=Cn(c,x),x.base&&!t.base)t.base=x.base;console.log(`Using template '${u}'`)}let a=t.path??c.worktreeDir,l=wn(a,{repo:r,branch:i}),h=Ih(n,l);console.log(`Creating worktree for branch '${e}'...`),console.log(` Target: ${h}`);let g=(await E.list(n)).find((x)=>x.branch===e);if(g)console.error(`Error: branch '${e}' is already checked out in ${g.path}`),process.exit(1);if(jh(h))console.error(`Error: directory already exists: ${h}`),process.exit(1);try{await E.add(e,h,{createBranch:Boolean(t.create),base:t.base},n),console.log(" \u2713 Worktree created");try{qt(n,{timestamp:new Date().toISOString(),event:"create",branch:e,path:h})}catch{}if(o)oc(h,{number:o,branch:e,createdAt:new Date().toISOString()}),console.log(` \u2713 PR #${o} metadata saved`)}catch(x){if(x instanceof Gt)console.error(`Error creating worktree: ${x.stderr||x.message}`);else console.error(`Error: ${x.message}`);process.exit(1)}if(c.autoUpstream)try{let x=await E.getDefaultRemote(n);if(await E.remoteBranchExists(e,x,n))await E.setUpstream(e,x,n),console.log(` \u2713 Upstream tracking set \u2192 ${x}/${e}`);else console.log(" \u2139 No remote branch found \u2014 upstream tracking skipped")}catch(x){console.warn(` \u26A0 Could not set upstream tracking: ${x.message}`)}try{if(c.copyFiles.length>0){console.log(` Copying files: ${c.copyFiles.join(", ")}`);let y=wo(n,h,c.copyFiles);for(let M of y.warnings)console.log(` \u26A0 ${M}`);if(y.copied.length>0)console.log(` \u2713 Copied: ${y.copied.join(", ")}`)}if(c.linkFiles.length>0){console.log(` Linking files: ${c.linkFiles.join(", ")}`);let y=bo(n,h,c.linkFiles);for(let M of y.warnings)console.log(` \u26A0 ${M}`);if(y.linked.length>0)console.log(` \u2713 Linked: ${y.linked.join(", ")}`)}if(c.sharedDeps&&c.sharedDeps.paths&&c.sharedDeps.paths.length>0){let y=c.sharedDeps.strategy??"symlink";console.log(` Sharing dependencies (${y}): ${c.sharedDeps.paths.join(", ")}`);let M=Ss(n,h,c.sharedDeps);for(let it of M.warnings)console.log(` \u26A0 ${it}`);if(M.linked.length>0)console.log(` \u2713 Shared (${y}): ${M.linked.join(", ")}`);if(M.copied.length>0)console.log(` \u2713 Copied: ${M.copied.join(", ")}`)}let x={OMW_BRANCH:e,OMW_WORKTREE_PATH:h,OMW_REPO_PATH:n},m=t.focus,b=[];if(m&&m.length>0)b=m.flatMap((y)=>y.split(/[,\s]+/)).map((y)=>y.trim()).filter(Boolean);if(b.length>0){let{valid:y,invalid:M}=Pn(h,b);if(M.length>0)console.log(` \u26A0 Focus paths not found (will be skipped): ${M.join(", ")}`);if(y.length>0)uo(h,y),console.log(` \u2713 Focus set: ${y.join(", ")}`);x.OMW_FOCUS_PATHS=y.join(",")}if(c.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(c.postCreate,{cwd:h,env:x,onOutput:(y)=>console.log(` ${y}`)}),console.log(" \u2713 Hooks completed");if(b.length>0&&c.monorepo?.hooks&&c.monorepo.hooks.length>0){let y=no(c.monorepo.hooks,b);if(y.length>0)console.log(" Running monorepo hooks..."),await So(y,"postCreate",{cwd:h,env:x,repo:r,branch:e,focusPaths:b,mainRepoPath:n,onOutput:(M)=>console.log(` ${M}`)}),console.log(" \u2713 Monorepo hooks completed")}let S=Le(s);if(t.session||S.autoCreate)if(await mo()){let M=t.layout??S.defaultLayout,it=$n(s,M),st=await dn(e,h,{layout:it,prefix:S.prefix,attach:!1,layoutName:M});console.log(` \u2713 Session created: ${st}`)}else console.log(" \u26A0 tmux not found \u2014 session skipped");console.log(`
19
19
  Worktree ready: ${h}`),process.exit(0)}catch(x){console.error(`
20
- Setup failed, rolling back...`);try{await E.remove(h,{force:!0},n),console.error("Rolled back worktree.")}catch{}if(x instanceof mo)console.error(`Error: hook timed out: ${x.command}`);else if(x instanceof po){if(console.error(`Error: hook failed (exit ${x.exitCode}): ${x.command}`),x.stderr)console.error(x.stderr)}else console.error(`Error: ${x.message}`);process.exit(1)}}},vh=zh});var ac={};xt(ac,{default:()=>Kh});import{relative as kh,resolve as Or}from"path";var Uh,Kh;var fc=H(()=>{at();Ct();$t();le();Uh={command:"list",aliases:["ls"],describe:"List all worktrees with their status",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("porcelain",{type:"boolean",alias:"p",describe:"Machine-readable output"}).option("all",{type:"boolean",alias:"a",describe:"List worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let s=Y(),c=await E.getMainRepoPath().catch(()=>process.cwd()),f=Re(s),a=new Set([Or(c)]),u=[c];for(let h of f){let d=Or(h);if(!a.has(d))a.add(d),u.push(h)}e=await E.listAll(u)}else e=await E.list();let o=await Promise.all(e.map(async(s)=>({...s,focus:qt(s.path)})));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);if(t.porcelain){for(let s of o){if(t.all)console.log(`repo ${s.repoName}`);if(console.log(`path ${s.path}`),console.log(`branch ${s.branch??"(detached)"}`),console.log(`head ${s.head}`),console.log(`dirty ${s.isDirty}`),console.log(`locked ${s.isLocked}`),s.focus&&s.focus.length>0)console.log(`focus ${s.focus.join(",")}`);console.log("")}process.exit(0)}if(e.length===0)console.log("No worktrees found."),process.exit(0);let n=Or(process.cwd()),r=t.all&&new Set(o.map((s)=>s.repoName)).size>1,i=o.map((s)=>({repo:s.repoName,branch:s.branch??"(detached)",path:s.path===n?s.path:kh(n,s.path)||s.path,status:s.isLocked?"locked":s.isDirty?"dirty":"clean",focus:s.focus?s.focus.join(", ").slice(0,40)+(s.focus.join(", ").length>40?"...":""):"\u2014"}));if(r){let s=Math.max(4,...i.map((h)=>h.repo.length)),c=Math.max(6,...i.map((h)=>h.branch.length)),f=Math.max(4,...i.map((h)=>h.path.length)),a=Math.max(6,...i.map((h)=>h.status.length)),u=Math.max(5,...i.map((h)=>h.focus.length));console.log(`${"Repo".padEnd(s)} ${"Branch".padEnd(c)} ${"Path".padEnd(f)} ${"Status".padEnd(a)} ${"Focus".padEnd(u)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(f)} ${"-".repeat(a)} ${"-".repeat(u)}`);for(let h of i)console.log(`${h.repo.padEnd(s)} ${h.branch.padEnd(c)} ${h.path.padEnd(f)} ${h.status.padEnd(a)} ${h.focus.padEnd(u)}`)}else{let s=Math.max(6,...i.map((u)=>u.branch.length)),c=Math.max(4,...i.map((u)=>u.path.length)),f=Math.max(6,...i.map((u)=>u.status.length)),a=Math.max(5,...i.map((u)=>u.focus.length));console.log(`${"Branch".padEnd(s)} ${"Path".padEnd(c)} ${"Status".padEnd(f)} ${"Focus".padEnd(a)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(f)} ${"-".repeat(a)}`);for(let u of i)console.log(`${u.branch.padEnd(s)} ${u.path.padEnd(c)} ${u.status.padEnd(f)} ${u.focus.padEnd(a)}`)}process.exit(0)}catch(e){if(e instanceof it)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}},Kh=Uh});var uc={};xt(uc,{default:()=>Xh});import{basename as lc}from"path";import*as hc from"readline";async function qh(t){let e=hc.createInterface({input:process.stdin,output:process.stdout});return new Promise((o)=>{e.question(t,(n)=>{e.close(),o(n.toLowerCase()==="y"||n.toLowerCase()==="yes")})})}var Vh,Xh;var pc=H(()=>{at();Ct();$t();me();le();Cn();Fe();Pe();Vh={command:"remove <branch-or-path>",aliases:["rm"],describe:"Remove a worktree",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}).option("force",{type:"boolean",alias:"f",describe:"Force removal even with uncommitted changes"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.force,n=!!t.yes;try{let r=await E.getMainRepoPath().catch(()=>process.cwd()),s=(await E.list(r)).find((d)=>d.branch===e||d.path===e||d.path.endsWith("/"+e));if(!s)console.error(`Error: no worktree found for '${e}'`),process.exit(1);if(s.isMain)console.error("Error: cannot remove the main worktree"),process.exit(1);if(await E.isDirty(s.path)&&!o)console.error(`Error: worktree has uncommitted changes: ${s.path}`),console.error("Use --force to remove anyway."),process.exit(1);if(s.isLocked){if(console.error(`Error: worktree is locked: ${s.path}`),s.lockReason)console.error(`Lock reason: ${s.lockReason}`);process.exit(1)}if(!n){if(!await qh(`Remove worktree '${s.branch??lc(s.path)}' at ${s.path}? [y/N] `))console.log("Cancelled."),process.exit(0)}let f=Y(),a=Bt(f,r);if(a.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(a.postRemove,{cwd:s.path,env:{OMW_BRANCH:s.branch??"",OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r},onOutput:(d)=>console.log(` ${d}`)}).catch((d)=>console.warn(`Warning: postRemove hook failed: ${d.message}`));let u=qt(s.path)??[];if(u.length>0&&a.monorepo?.hooks&&a.monorepo.hooks.length>0){let d=Xe(a.monorepo.hooks,u);if(d.length>0){let w=lc(r),x=s.branch??"unknown";console.log(" Running monorepo postRemove hooks..."),await xo(d,"postRemove",{cwd:s.path,env:{OMW_BRANCH:x,OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r,OMW_FOCUS_PATHS:u.join(",")},repo:w,branch:x,focusPaths:u,mainRepoPath:r,onOutput:(m)=>console.log(` ${m}`)}),console.log(" \u2713 Monorepo hooks completed")}}let h=Me(f);if(h.autoKill){if(await ao()){let w=s.branch??e;if(await hn(w,s.path,h.prefix))console.log(" \u2713 Session killed")}}await E.remove(s.path,{force:o},r),console.log(`Removed worktree: ${s.path}`);try{Ut(r,{timestamp:new Date().toISOString(),event:"delete",branch:s.branch??e,path:s.path})}catch{}process.exit(0)}catch(r){if(r instanceof it)console.error(`Git error: ${r.message}`);else console.error(`Error: ${r.message}`);process.exit(1)}}},Xh=Vh});var dc={};xt(dc,{default:()=>Yh});import{basename as Zh}from"path";var Qh,Yh;var mc=H(()=>{at();Ct();Fe();$t();Pe();Qh={command:"switch <branch-or-path>",aliases:["sw"],describe:"Switch to a worktree directory (outputs cd command for shell eval)",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}),handler:async(t)=>{let e=t["branch-or-path"];try{let o=await E.getMainRepoPath().catch(()=>process.cwd()),r=(await E.list(o)).find((c)=>c.branch===e||c.path===e||c.path.endsWith("/"+e));if(!r)console.error(`Error: no worktree for branch or path '${e}'`),process.exit(1);try{Ut(o,{timestamp:new Date().toISOString(),event:"switch",branch:r.branch??e,path:r.path})}catch{}let i=Y(),s=Me(i);if(s.enabled&&pr()){let c=r.branch??Zh(r.path),f=ye(c,s.prefix);if(await ue(f))try{await fn(f),process.exit(0)}catch{}}console.log(`cd ${JSON.stringify(r.path)}`),process.exit(0)}catch(o){if(o instanceof it)console.error(`Git error: ${o.message}`);else console.error(`Error: ${o.message}`);process.exit(1)}}},Yh=Qh});async function xc(t,e,o,n){let r=t.filter((u)=>!u.isMain),i=r.filter((u)=>De(u.path)),s=new Set(i.map((u)=>u.path)),c=[];if(e.autoCleanMerged)for(let u of r){if(s.has(u.path))continue;if(!u.branch)continue;if(await E.isMergedInto(u.branch,o,n)&&!u.isDirty)c.push(u)}let f=[];if(e.staleAfterDays&&e.staleAfterDays>0){let u=new Date;for(let h of r){if(s.has(h.path))continue;let d=await E.getWorktreeLastActivity(h.path),w=d?Math.floor((u.getTime()-d.getTime())/86400000):1/0;if(w>=e.staleAfterDays)f.push({worktree:h,lastActivity:d,daysSinceActivity:w===1/0?-1:w})}}let a=e.maxWorktrees?r.length>e.maxWorktrees:!1;return{merged:c,stale:f,pinProtected:i,overLimit:a,totalCount:r.length,maxWorktrees:e.maxWorktrees??null}}function wc(t){let e=[];if(t.pinProtected.length>0){e.push(`Pin-protected worktrees (${t.pinProtected.length}):`);for(let o of t.pinProtected)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.merged.length>0){e.push(`Merged worktrees (${t.merged.length}):`);for(let o of t.merged)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.stale.length>0){e.push(`Stale worktrees (${t.stale.length}):`);for(let o of t.stale){let n=o.daysSinceActivity<0?"unknown":`${o.daysSinceActivity} days`;e.push(` ${o.worktree.branch??"(detached)"} \u2014 inactive ${n}`)}}if(t.overLimit)e.push(`Worktree limit exceeded: ${t.totalCount}/${t.maxWorktrees}`);if(e.length===0)e.push("All worktrees are healthy.");return e.join(`
21
- `)}var gc=H(()=>{at();go()});var Cc={};xt(Cc,{default:()=>ou});import*as bc from"readline";async function tu(t){let e=bc.createInterface({input:process.stdin,output:process.stdout});return new Promise((o)=>{e.question(t,(n)=>{e.close(),o(n.toLowerCase()==="y"||n.toLowerCase()==="yes")})})}var eu,ou;var $c=H(()=>{at();Ct();$t();gc();go();eu={command:"clean",describe:"Remove merged worktrees and prune stale entries",builder:(t)=>t.option("dry-run",{type:"boolean",alias:"n",describe:"Show what would be removed"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation"}).option("stale",{type:"boolean",describe:"Also show stale worktrees (based on lifecycle config)"}),handler:async(t)=>{let e=!!(t["dry-run"]||t.n),o=!!t.yes;try{let n=await E.getMainRepoPath().catch(()=>process.cwd()),r=await E.list(n),s=(r.find((f)=>f.isMain)??r[0])?.branch??"main",c=[];for(let f of r){if(f.isMain)continue;if(De(f.path)){console.log(` Skipping (pinned): ${f.branch}`);continue}if(!f.branch)continue;if(!await E.isMergedInto(f.branch,s,n))continue;if(await E.isDirty(f.path)){console.log(` Skipping (dirty): ${f.branch}`);continue}c.push(f)}if(c.length===0)console.log("No merged worktrees to clean.");else{console.log(e?"Would remove:":"To remove:");for(let f of c)console.log(` ${f.branch} (${f.path})`)}if(!e&&c.length>0){if(!o){if(!await tu(`
22
- Remove ${c.length} worktree(s)? [y/N] `))console.log("Cancelled."),process.exit(0)}for(let f of c)await E.remove(f.path,{force:!1},n),console.log(` Removed: ${f.branch}`)}if(!e)await E.prune(n),console.log("Pruned stale worktree entries.");if(t.stale){let f=Y();if(f.lifecycle){let a=await xc(r,f.lifecycle,s,n);console.log(),console.log(wc(a))}else console.log(`
23
- No lifecycle config found. Add 'lifecycle' to your config to enable stale detection.`)}process.exit(0)}catch(n){if(n instanceof it)console.error(`Git error: ${n.message}`);else console.error(`Error: ${n.message}`);process.exit(1)}}},ou=eu});import{existsSync as nu,mkdirSync as ru,readFileSync as iu,writeFileSync as su}from"fs";import{dirname as cu}from"path";function Sc(){let t=_t();try{return Y(t)}catch{if(!nu(t))throw Error("Failed to load config");let e=iu(t,"utf-8");return JSON.parse(e)}}function yc(t){let e=_t(),o=cu(e);ru(o,{recursive:!0,mode:448});let n=`${JSON.stringify(t,null,2)}
24
- `;try{Lo(e,n)}catch{su(e,n,{encoding:"utf-8",mode:384})}}function Wr(t){return Object.keys(t.profiles??{})}function Pc(t){let e=Sc();yc({...e,activeProfile:t})}function Ec(t){return t.activeProfile??null}function Rc(t){let e=Sc(),o={...e.profiles??{}};delete o[t],yc({...e,profiles:o,activeProfile:e.activeProfile===t?void 0:e.activeProfile})}var Mc=H(()=>{$t()});var Oc={};xt(Oc,{default:()=>hu});import{spawnSync as au}from"child_process";import{readFileSync as fu}from"fs";var lu,hu;var Wc=H(()=>{$t();Mc();lu={command:"config",describe:"Manage oh-my-worktree configuration",builder:(t)=>t.option("init",{type:"boolean",describe:"Create default config file"}).option("show",{type:"boolean",alias:"s",describe:"Print current config as JSON"}).option("edit",{type:"boolean",alias:"e",describe:"Open config in $EDITOR"}).option("path",{type:"boolean",describe:"Print config file path"}).option("validate",{type:"boolean",describe:"Validate config against schema"}).option("profiles",{type:"boolean",describe:"List config profiles"}).option("profile",{type:"string",describe:"Profile name for activation/deletion"}).option("activate",{type:"boolean",describe:"Activate the specified profile"}).option("delete",{type:"boolean",describe:"Delete the specified profile"}),handler:async(t)=>{let e=_t();if(t.init){let o=ne();console.log(`Config initialized: ${o}`),process.exit(0)}if(t.path)console.log(e),process.exit(0);if(t.show){try{let o=Y();console.log(JSON.stringify(o,null,2))}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.edit){let o=process.env.EDITOR??process.env.VISUAL??"vi";ne();let n=au(o,[e],{stdio:"inherit"});process.exit(n.status??0)}if(t.validate)try{let o=fu(e,"utf-8"),n;try{n=JSON.parse(o)}catch{console.error(`Error: invalid JSON in config file: ${e}`),process.exit(1)}let r=Bo(n);if(r.length===0)console.log(`\u2713 Config is valid: ${e}`),process.exit(0);else{console.error(`Config validation failed (${r.length} error(s)):`);for(let i of r)console.error(` ${i.field}: ${i.message}`);process.exit(1)}}catch(o){console.error(`Error reading config: ${o.message}`),process.exit(1)}if(t.profiles){try{let o=Y(),n=Wr(o),r=Ec(o);for(let i of n)console.log(`${i}${i===r?" \u2605":""}`)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.activate){try{let o=Y(),n=t.profile;if(!Wr(o).includes(n))console.error(`Error: profile '${n}' does not exist.`),process.exit(1);Pc(n)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.delete)Rc(t.profile),process.exit(0);console.log("Usage: omw config [options]"),console.log(""),console.log("Options:"),console.log(" --init Create default config file"),console.log(" --show, -s Print current config as JSON"),console.log(" --edit, -e Open config in $EDITOR"),console.log(" --path Print config file path"),console.log(" --validate Validate config against schema"),console.log(" --profiles List config profiles"),console.log(" --profile Profile name for activation/deletion"),console.log(" --activate Activate the specified profile"),console.log(" --delete Delete the specified profile"),console.log(""),console.log(`Config path: ${e}`),process.exit(0)}},hu=lu});var Dc={};xt(Dc,{default:()=>pu});var uu,pu;var Fc=H(()=>{Cr();uu={command:"doctor",describe:"Check worktree health and diagnose issues",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("fix",{type:"boolean",describe:"Auto-fix issues (prune stale, remove orphans, unlock stale locks)"}),handler:async(t)=>{let e=process.cwd(),o=await wo(e);if(t.json&&!t.fix){let i={pass:o.checks.filter((s)=>s.status==="pass").length,warn:o.checks.filter((s)=>s.status==="warn").length,fail:o.checks.filter((s)=>s.status==="fail").length};console.log(JSON.stringify({healthy:o.healthy,checks:o.checks,summary:i},null,2)),process.exit(o.healthy?0:1)}console.log(`oh-my-worktree doctor
20
+ Setup failed, rolling back...`);try{await E.remove(h,{force:!0},n),console.error("Rolled back worktree.")}catch(m){console.error(`Warning: rollback failed: ${m.message}`)}if(x instanceof $o)console.error(`Error: hook timed out: ${x.command}`);else if(x instanceof Co){if(console.error(`Error: hook failed (exit ${x.exitCode}): ${x.command}`),x.stderr)console.error(x.stderr)}else console.error(`Error: ${x.message}`);process.exit(1)}}},_h=Th});var fc={};xt(fc,{default:()=>Nh});import{relative as Gh,resolve as Wr}from"path";var Hh,Nh;var lc=N(()=>{ct();Zt();$t();me();Dt();Hh={command:"list",aliases:["ls"],describe:"List all worktrees with their status",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("porcelain",{type:"boolean",alias:"p",describe:"Machine-readable output"}).option("all",{type:"boolean",alias:"a",describe:"List worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let s=Y(),c=await at(),u=Be(s),a=new Set([Wr(c)]),l=[c];for(let h of u){let d=Wr(h);if(!a.has(d))a.add(d),l.push(h)}e=await E.listAll(l)}else e=await E.list();let o=await Promise.all(e.map(async(s)=>({...s,focus:Qt(s.path)})));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);if(t.porcelain){for(let s of o){if(t.all)console.log(`repo ${s.repoName}`);if(console.log(`path ${s.path}`),console.log(`branch ${s.branch??"(detached)"}`),console.log(`head ${s.head}`),console.log(`dirty ${s.isDirty}`),console.log(`locked ${s.isLocked}`),s.focus&&s.focus.length>0)console.log(`focus ${s.focus.join(",")}`);console.log("")}process.exit(0)}if(e.length===0)console.log("No worktrees found."),process.exit(0);let n=Wr(process.cwd()),r=t.all&&new Set(o.map((s)=>s.repoName)).size>1,i=o.map((s)=>({repo:s.repoName,branch:s.branch??"(detached)",path:s.path===n?s.path:Gh(n,s.path)||s.path,status:s.isLocked?"locked":s.isDirty?"dirty":"clean",focus:s.focus?s.focus.join(", ").slice(0,40)+(s.focus.join(", ").length>40?"...":""):"\u2014"}));if(r){let s=Math.max(4,...i.map((h)=>h.repo.length)),c=Math.max(6,...i.map((h)=>h.branch.length)),u=Math.max(4,...i.map((h)=>h.path.length)),a=Math.max(6,...i.map((h)=>h.status.length)),l=Math.max(5,...i.map((h)=>h.focus.length));console.log(`${"Repo".padEnd(s)} ${"Branch".padEnd(c)} ${"Path".padEnd(u)} ${"Status".padEnd(a)} ${"Focus".padEnd(l)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(u)} ${"-".repeat(a)} ${"-".repeat(l)}`);for(let h of i)console.log(`${h.repo.padEnd(s)} ${h.branch.padEnd(c)} ${h.path.padEnd(u)} ${h.status.padEnd(a)} ${h.focus.padEnd(l)}`)}else{let s=Math.max(6,...i.map((l)=>l.branch.length)),c=Math.max(4,...i.map((l)=>l.path.length)),u=Math.max(6,...i.map((l)=>l.status.length)),a=Math.max(5,...i.map((l)=>l.focus.length));console.log(`${"Branch".padEnd(s)} ${"Path".padEnd(c)} ${"Status".padEnd(u)} ${"Focus".padEnd(a)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(u)} ${"-".repeat(a)}`);for(let l of i)console.log(`${l.branch.padEnd(s)} ${l.path.padEnd(c)} ${l.status.padEnd(u)} ${l.focus.padEnd(a)}`)}process.exit(0)}catch(e){if(e instanceof Gt)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}},Nh=Hh});var uc={};xt(uc,{default:()=>zh});import{basename as hc}from"path";var Jh,zh;var pc=N(()=>{ct();$t();Ce();me();yn();_e();De();Dt();Jh={command:"remove <branch-or-path>",aliases:["rm"],describe:"Remove a worktree",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}).option("force",{type:"boolean",alias:"f",describe:"Force removal even with uncommitted changes"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.force,n=!!t.yes;try{let r=await at(),i=await E.list(r),s=Vt(i,e);if(s.isMain)console.error("Error: cannot remove the main worktree"),process.exit(1);if(await E.isDirty(s.path)&&!o)console.error(`Error: worktree has uncommitted changes: ${s.path}`),console.error("Use --force to remove anyway."),process.exit(1);if(s.isLocked){if(console.error(`Error: worktree is locked: ${s.path}`),s.lockReason)console.error(`Lock reason: ${s.lockReason}`);process.exit(1)}if(!n){if(!await Te(`Remove worktree '${s.branch??hc(s.path)}' at ${s.path}? [y/N] `))console.log("Cancelled."),process.exit(0)}let u=Y(),a=Lt(u,r);if(a.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(a.postRemove,{cwd:s.path,env:{OMW_BRANCH:s.branch??"",OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r},onOutput:(d)=>console.log(` ${d}`)}).catch((d)=>console.warn(`Warning: postRemove hook failed: ${d.message}`));let l=Qt(s.path)??[];if(l.length>0&&a.monorepo?.hooks&&a.monorepo.hooks.length>0){let d=no(a.monorepo.hooks,l);if(d.length>0){let g=hc(r),x=s.branch??"unknown";console.log(" Running monorepo postRemove hooks..."),await So(d,"postRemove",{cwd:s.path,env:{OMW_BRANCH:x,OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r,OMW_FOCUS_PATHS:l.join(",")},repo:g,branch:x,focusPaths:l,mainRepoPath:r,onOutput:(m)=>console.log(` ${m}`)}),console.log(" \u2713 Monorepo hooks completed")}}let h=Le(u);if(h.autoKill){if(await mo()){let g=s.branch??e;if(await mn(g,s.path,h.prefix))console.log(" \u2713 Session killed")}}await E.remove(s.path,{force:o},r),console.log(`Removed worktree: ${s.path}`);try{qt(r,{timestamp:new Date().toISOString(),event:"delete",branch:s.branch??e,path:s.path})}catch{}process.exit(0)}catch(r){wt(r)}}},zh=Jh});var dc={};xt(dc,{default:()=>Uh});import{basename as vh}from"path";var kh,Uh;var mc=N(()=>{ct();_e();$t();De();Dt();kh={command:"switch <branch-or-path>",aliases:["sw"],describe:"Switch to a worktree directory (outputs cd command for shell eval)",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}),handler:async(t)=>{let e=t["branch-or-path"];try{let o=await at(),n=await E.list(o),r=Vt(n,e);try{qt(o,{timestamp:new Date().toISOString(),event:"switch",branch:r.branch??e,path:r.path})}catch{}let i=Y(),s=Le(i);if(s.enabled&&xr()){let c=r.branch??vh(r.path),u=We(c,s.prefix);if(await ge(u))try{await pn(u),process.exit(0)}catch{}}console.log(`cd ${JSON.stringify(r.path)}`),process.exit(0)}catch(o){wt(o)}}},Uh=kh});async function xc(t,e,o,n){let r=t.filter((l)=>!l.isMain),i=r.filter((l)=>je(l.path)),s=new Set(i.map((l)=>l.path)),c=[];if(e.autoCleanMerged)for(let l of r){if(s.has(l.path))continue;if(!l.branch)continue;if(await E.isMergedInto(l.branch,o,n)&&!l.isDirty)c.push(l)}let u=[];if(e.staleAfterDays&&e.staleAfterDays>0){let l=new Date;for(let h of r){if(s.has(h.path))continue;let d=await E.getWorktreeLastActivity(h.path),g=d?Math.floor((l.getTime()-d.getTime())/86400000):1/0;if(g>=e.staleAfterDays)u.push({worktree:h,lastActivity:d,daysSinceActivity:g===1/0?-1:g})}}let a=e.maxWorktrees?r.length>e.maxWorktrees:!1;return{merged:c,stale:u,pinProtected:i,overLimit:a,totalCount:r.length,maxWorktrees:e.maxWorktrees??null}}function gc(t){let e=[];if(t.pinProtected.length>0){e.push(`Pin-protected worktrees (${t.pinProtected.length}):`);for(let o of t.pinProtected)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.merged.length>0){e.push(`Merged worktrees (${t.merged.length}):`);for(let o of t.merged)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.stale.length>0){e.push(`Stale worktrees (${t.stale.length}):`);for(let o of t.stale){let n=o.daysSinceActivity<0?"unknown":`${o.daysSinceActivity} days`;e.push(` ${o.worktree.branch??"(detached)"} \u2014 inactive ${n}`)}}if(t.overLimit)e.push(`Worktree limit exceeded: ${t.totalCount}/${t.maxWorktrees}`);if(e.length===0)e.push("All worktrees are healthy.");return e.join(`
21
+ `)}var wc=N(()=>{ct();yo()});var bc={};xt(bc,{default:()=>Vh});var Kh,Vh;var Cc=N(()=>{ct();$t();wc();yo();Dt();Kh={command:"clean",describe:"Remove merged worktrees and prune stale entries",builder:(t)=>t.option("dry-run",{type:"boolean",alias:"n",describe:"Show what would be removed"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation"}).option("stale",{type:"boolean",describe:"Also show stale worktrees (based on lifecycle config)"}),handler:async(t)=>{let e=!!(t["dry-run"]||t.n),o=!!t.yes;try{let n=await at(),r=await E.list(n),s=(r.find((l)=>l.isMain)??r[0])?.branch??"main",c=r.filter((l)=>{if(l.isMain)return!1;if(je(l.path))return console.log(` Skipping (pinned): ${l.branch}`),!1;if(!l.branch)return!1;return!0}),u=await Promise.all(c.map(async(l)=>{let[h,d]=await Promise.all([E.isMergedInto(l.branch,s,n),E.isDirty(l.path)]);return{wt:l,merged:h,dirty:d}})),a=[];for(let{wt:l,merged:h,dirty:d}of u){if(!h)continue;if(d){console.log(` Skipping (dirty): ${l.branch}`);continue}a.push(l)}if(a.length===0)console.log("No merged worktrees to clean.");else{console.log(e?"Would remove:":"To remove:");for(let l of a)console.log(` ${l.branch} (${l.path})`)}if(!e&&a.length>0){if(!o){if(!await Te(`
22
+ Remove ${a.length} worktree(s)? [y/N] `))console.log("Cancelled."),process.exit(0)}for(let l of a)await E.remove(l.path,{force:!1},n),console.log(` Removed: ${l.branch}`)}if(!e)await E.prune(n),console.log("Pruned stale worktree entries.");if(t.stale){let l=Y();if(l.lifecycle){let h=await xc(r,l.lifecycle,s,n);console.log(),console.log(gc(h))}else console.log(`
23
+ No lifecycle config found. Add 'lifecycle' to your config to enable stale detection.`)}process.exit(0)}catch(n){wt(n)}}},Vh=Kh});import{existsSync as qh,mkdirSync as Xh,readFileSync as Zh,writeFileSync as Qh}from"fs";import{dirname as Yh}from"path";function $c(){let t=Nt();try{return Y(t)}catch{if(!qh(t))throw Error("Failed to load config");let e=Zh(t,"utf-8");return JSON.parse(e)}}function Sc(t){let e=Nt(),o=Yh(e);Xh(o,{recursive:!0,mode:448});let n=`${JSON.stringify(t,null,2)}
24
+ `;try{No(e,n)}catch{Qh(e,n,{encoding:"utf-8",mode:384})}}function Dr(t){return Object.keys(t.profiles??{})}function Pc(t){let e=$c();Sc({...e,activeProfile:t})}function yc(t){return t.activeProfile??null}function Rc(t){let e=$c(),o={...e.profiles??{}};delete o[t],Sc({...e,profiles:o,activeProfile:e.activeProfile===t?void 0:e.activeProfile})}var Ec=N(()=>{$t()});var Mc={};xt(Mc,{default:()=>nu});import{spawnSync as tu}from"child_process";import{readFileSync as eu}from"fs";var ou,nu;var Oc=N(()=>{$t();Ec();ou={command:"config",describe:"Manage oh-my-worktree configuration",builder:(t)=>t.option("init",{type:"boolean",describe:"Create default config file"}).option("show",{type:"boolean",alias:"s",describe:"Print current config as JSON"}).option("edit",{type:"boolean",alias:"e",describe:"Open config in $EDITOR"}).option("path",{type:"boolean",describe:"Print config file path"}).option("validate",{type:"boolean",describe:"Validate config against schema"}).option("profiles",{type:"boolean",describe:"List config profiles"}).option("profile",{type:"string",describe:"Profile name for activation/deletion"}).option("activate",{type:"boolean",describe:"Activate the specified profile"}).option("delete",{type:"boolean",describe:"Delete the specified profile"}),handler:async(t)=>{let e=Nt();if(t.init){let o=ae();console.log(`Config initialized: ${o}`),process.exit(0)}if(t.path)console.log(e),process.exit(0);if(t.show){try{let o=Y();console.log(JSON.stringify(o,null,2))}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.edit){let o=process.env.EDITOR??process.env.VISUAL??"vi";ae();let n=tu(o,[e],{stdio:"inherit"});process.exit(n.status??0)}if(t.validate)try{let o=eu(e,"utf-8"),n;try{n=JSON.parse(o)}catch{console.error(`Error: invalid JSON in config file: ${e}`),process.exit(1)}let r=Ho(n);if(r.length===0)console.log(`\u2713 Config is valid: ${e}`),process.exit(0);else{console.error(`Config validation failed (${r.length} error(s)):`);for(let i of r)console.error(` ${i.field}: ${i.message}`);process.exit(1)}}catch(o){console.error(`Error reading config: ${o.message}`),process.exit(1)}if(t.profiles){try{let o=Y(),n=Dr(o),r=yc(o);for(let i of n)console.log(`${i}${i===r?" \u2605":""}`)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.activate){try{let o=Y(),n=t.profile;if(!Dr(o).includes(n))console.error(`Error: profile '${n}' does not exist.`),process.exit(1);Pc(n)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.delete)Rc(t.profile),process.exit(0);console.log("Usage: omw config [options]"),console.log(""),console.log("Options:"),console.log(" --init Create default config file"),console.log(" --show, -s Print current config as JSON"),console.log(" --edit, -e Open config in $EDITOR"),console.log(" --path Print config file path"),console.log(" --validate Validate config against schema"),console.log(" --profiles List config profiles"),console.log(" --profile Profile name for activation/deletion"),console.log(" --activate Activate the specified profile"),console.log(" --delete Delete the specified profile"),console.log(""),console.log(`Config path: ${e}`),process.exit(0)}},nu=ou});var Wc={};xt(Wc,{default:()=>iu});var ru,iu;var Dc=N(()=>{Pr();ru={command:"doctor",describe:"Check worktree health and diagnose issues",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("fix",{type:"boolean",describe:"Auto-fix issues (prune stale, remove orphans, unlock stale locks)"}),handler:async(t)=>{let e=process.cwd(),o=await Po(e);if(t.json&&!t.fix){let i={pass:o.checks.filter((s)=>s.status==="pass").length,warn:o.checks.filter((s)=>s.status==="warn").length,fail:o.checks.filter((s)=>s.status==="fail").length};console.log(JSON.stringify({healthy:o.healthy,checks:o.checks,summary:i},null,2)),process.exit(o.healthy?0:1)}console.log(`oh-my-worktree doctor
25
25
  `);for(let i of o.checks){let s=i.status==="pass"?"\u2713":i.status==="warn"?"\u26A0":"\u2717";if(console.log(`${s} ${i.name}: ${i.message}`),i.detail)for(let c of i.detail)console.log(` \u2192 ${c}`)}let n=o.checks.filter((i)=>i.status==="warn").length,r=o.checks.filter((i)=>i.status==="fail").length;if(o.healthy)console.log(`
26
26
  All checks passed.`);else{let i=[];if(r>0)i.push(`${r} error(s)`);if(n>0)i.push(`${n} warning(s)`);console.log(`
27
27
  ${i.join(", ")} found.`)}if(t.fix){if(o.healthy)console.log(`
28
28
  Nothing to fix.`),process.exit(0);console.log(`
29
29
  Running auto-fix...
30
- `);let i=await yn(e);if(i.length===0)console.log("No auto-fixable issues found.");else{for(let a of i){let u=a.success?"\u2713":"\u2717",h=a.detail?` (${a.detail})`:"";console.log(`${u} ${a.action}${h}`)}let c=i.filter((a)=>a.success).length,f=i.filter((a)=>!a.success).length;console.log(`
31
- Fixed ${c} issue(s)${f>0?`, ${f} failed`:""}.`)}let s=await wo(e);if(s.healthy)console.log("All checks now pass.");process.exit(s.healthy?0:1)}process.exit(o.healthy?0:1)}},pu=uu});var Ac={};xt(Ac,{default:()=>Cu});function du(t){if(t?.includes("fish"))return"fish";if(t?.includes("bash"))return"bash";return"zsh"}function Bc(){return`omw() {
30
+ `);let i=await Mn(e);if(i.length===0)console.log("No auto-fixable issues found.");else{for(let a of i){let l=a.success?"\u2713":"\u2717",h=a.detail?` (${a.detail})`:"";console.log(`${l} ${a.action}${h}`)}let c=i.filter((a)=>a.success).length,u=i.filter((a)=>!a.success).length;console.log(`
31
+ Fixed ${c} issue(s)${u>0?`, ${u} failed`:""}.`)}let s=await Po(e);if(s.healthy)console.log("All checks now pass.");process.exit(s.healthy?0:1)}process.exit(o.healthy?0:1)}},iu=ru});var Lc={};xt(Lc,{default:()=>uu});function su(t){if(t?.includes("fish"))return"fish";if(t?.includes("bash"))return"bash";return"zsh"}function Fc(){return`omw() {
32
32
  if [ "$1" = "switch" ] || [ "$1" = "sw" ]; then
33
33
  local output
34
34
  output=$(command omw "$@" 2>/dev/null)
@@ -46,7 +46,7 @@ Fixed ${c} issue(s)${f>0?`, ${f} failed`:""}.`)}let s=await wo(e);if(s.healthy)c
46
46
  else
47
47
  command omw "$@"
48
48
  fi
49
- }`}function Lc(){return`function omw
49
+ }`}function Bc(){return`function omw
50
50
  if test "$argv[1]" = "switch"; or test "$argv[1]" = "sw"
51
51
  set output (command omw $argv 2>/dev/null)
52
52
  set status_code $status
@@ -63,7 +63,7 @@ Fixed ${c} issue(s)${f>0?`, ${f} failed`:""}.`)}let s=await wo(e);if(s.healthy)c
63
63
  else
64
64
  command omw $argv
65
65
  end
66
- end`}function mu(){return`_omw_completions() {
66
+ end`}function cu(){return`_omw_completions() {
67
67
  local cur="\${COMP_WORDS[COMP_CWORD]}"
68
68
  local prev="\${COMP_WORDS[COMP_CWORD-1]}"
69
69
  local commands="add list remove switch clean config doctor pin log archive rename clone import exec diff open status shell-init"
@@ -87,7 +87,7 @@ end`}function mu(){return`_omw_completions() {
87
87
  ;;
88
88
  esac
89
89
  }
90
- complete -F _omw_completions omw`}function xu(){return`_omw() {
90
+ complete -F _omw_completions omw`}function au(){return`_omw() {
91
91
  local -a commands
92
92
  commands=(
93
93
  'add:Add a new worktree'
@@ -124,7 +124,7 @@ complete -F _omw_completions omw`}function xu(){return`_omw() {
124
124
  esac
125
125
  fi
126
126
  }
127
- compdef _omw omw`}function wu(){return`complete -c omw -f
127
+ compdef _omw omw`}function fu(){return`complete -c omw -f
128
128
  complete -c omw -n '__fish_use_subcommand' -a 'add' -d 'Add a new worktree'
129
129
  complete -c omw -n '__fish_use_subcommand' -a 'list' -d 'List worktrees'
130
130
  complete -c omw -n '__fish_use_subcommand' -a 'remove' -d 'Remove a worktree'
@@ -142,29 +142,29 @@ complete -c omw -n '__fish_use_subcommand' -a 'exec' -d 'Run command'
142
142
  complete -c omw -n '__fish_use_subcommand' -a 'diff' -d 'Show diff'
143
143
  complete -c omw -n '__fish_use_subcommand' -a 'open' -d 'Open in editor'
144
144
  complete -c omw -n '__fish_use_subcommand' -a 'status' -d 'Show status'
145
- complete -c omw -n '__fish_seen_subcommand_from add switch rename pin archive' -a '(git branch --format="%(refname:short)" 2>/dev/null)'`}function gu(t){switch(t){case"bash":return mu();case"zsh":return xu();case"fish":return wu()}}var bu,Cu;var Ic=H(()=>{bu={command:"shell-init [shell]",describe:"Print shell integration code for omw switch",builder:(t)=>t.positional("shell",{type:"string",choices:["bash","zsh","fish"],describe:"Shell to generate integration for (auto-detected if omitted)"}).option("completions",{type:"string",describe:"Generate shell completions (bash, zsh, fish)",coerce:(e)=>e===!0?void 0:e}),handler:async(t)=>{let e="completions"in t,o=t.shell,n=t.completions,r=o??n??du(process.env.SHELL);if(e){let i=r==="fish"?Lc():Bc(),s=gu(r);console.log(i+`
146
- `+s),process.exit(0)}if(r==="fish")console.log(Lc()),process.exit(0);console.log(Bc()),process.exit(0)}},Cu=bu});var Gc={};xt(Gc,{default:()=>Su});import{resolve as Rn}from"path";function jc(t,e){if(t.length<=e)return t;return t.slice(0,e-3)+"..."}var $u,Su;var Tc=H(()=>{at();Ct();$t();le();$u={command:"status",aliases:["st"],describe:"Show status overview of all worktrees",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("all",{type:"boolean",alias:"a",describe:"Show worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let c=Y(),f=await E.getMainRepoPath().catch(()=>process.cwd()),a=Re(c),u=new Set([Rn(f)]),h=[f];for(let d of a){let w=Rn(d);if(!u.has(w))u.add(w),h.push(d)}e=await E.listAll(h)}else e=await E.list();if(e.length===0)console.log("No worktrees found."),process.exit(0);let o=await Promise.all(e.map(async(c)=>{let[f,a,u,h]=await Promise.all([c.branch?E.getAheadBehind(c.branch,c.path):Promise.resolve({ahead:0,behind:0}),E.getLastCommit(c.path),E.getDirtyCount(c.path),Promise.resolve(qt(c.path))]);return{...c,aheadBehind:f,lastCommit:a,dirtyCount:u,focus:h}}));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);let n=Rn(process.cwd()),r=t.all&&new Set(o.map((c)=>c.repoName)).size>1,i=o.map((c)=>{let a=(Rn(c.path)===n?"* ":" ")+(c.branch??"(detached)"),u;if(c.isLocked)u="locked";else if(c.dirtyCount>0)u=`${c.dirtyCount} dirty`;else u="clean";let h=[];if(c.aheadBehind.ahead>0)h.push(`+${c.aheadBehind.ahead}`);if(c.aheadBehind.behind>0)h.push(`-${c.aheadBehind.behind}`);let d=h.length>0?h.join(" "):"=",w=c.lastCommit?`${c.lastCommit.relativeDate} ${jc(c.lastCommit.message,30)}`:"\u2014",x=c.focus&&c.focus.length>0?jc(c.focus.join(", "),30):"\u2014";return{repo:c.repoName,branch:a,dirty:u,sync:d,lastCommit:w,focus:x}}),s={branch:Math.max(6,...i.map((c)=>c.branch.length)),dirty:Math.max(6,...i.map((c)=>c.dirty.length)),sync:Math.max(4,...i.map((c)=>c.sync.length)),lastCommit:Math.max(11,...i.map((c)=>c.lastCommit.length)),focus:Math.max(5,...i.map((c)=>c.focus.length)),repo:Math.max(4,...i.map((c)=>c.repo.length))};if(r){let c=`${"Repo".padEnd(s.repo)} ${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,f=`${"-".repeat(s.repo)} ${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(f);for(let a of i)console.log(`${a.repo.padEnd(s.repo)} ${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}else{let c=`${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,f=`${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(f);for(let a of i)console.log(`${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}process.exit(0)}catch(e){if(e instanceof it)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}};Su=$u});var Nc={};xt(Nc,{default:()=>Ru});import{existsSync as yu}from"fs";function Pu(t){if(t)return t;let e=process.env.VISUAL||process.env.EDITOR;if(e)return e;for(let o of _c)try{if(Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return o}catch{continue}return null}var _c,Eu,Ru;var Hc=H(()=>{at();Ct();_c=["code","cursor","vim","nvim","emacs","nano","subl","zed","idea","webstorm"];Eu={command:"open [branch-or-path]",describe:"Open a worktree in your editor/IDE",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path (defaults to current worktree)"}).option("editor",{type:"string",alias:"e",describe:"Editor command to use (overrides $VISUAL/$EDITOR)"}).option("list-editors",{type:"boolean",describe:"List detected editors"}),handler:async(t)=>{if(t["list-editors"]){let e=process.env.VISUAL||process.env.EDITOR;if(e)console.log(`$VISUAL/$EDITOR: ${e}`);for(let o of _c)try{let n=Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0){let r=new TextDecoder().decode(n.stdout).trim();console.log(` ${o}: ${r}`)}}catch{}process.exit(0)}try{let e=t["branch-or-path"],o;if(!e)o=process.cwd();else{let i=await E.getMainRepoPath().catch(()=>process.cwd()),c=(await E.list(i)).find((f)=>f.branch===e||f.path===e||f.path.endsWith("/"+e));if(!c)console.error(`Error: no worktree found for '${e}'`),process.exit(1);o=c.path}if(!yu(o))console.error(`Error: worktree path does not exist: ${o}`),process.exit(1);let n=Pu(t.editor);if(!n)console.error("Error: no editor detected."),console.error("Set $VISUAL or $EDITOR, or use --editor <command>."),console.error("Detected editors can be listed with: omw open --list-editors"),process.exit(1);console.log(`Opening ${o} with ${n}...`),await Bun.spawn([n,o],{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited,process.exit(0)}catch(e){if(e instanceof it)console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}},Ru=Eu});var zc={};xt(zc,{default:()=>Ou});import{resolve as Jc}from"path";var Mu,Ou;var vc=H(()=>{at();Ct();$t();Mu={command:"exec <command>",describe:"Run a command in each worktree",builder:(t)=>t.positional("command",{type:"string",describe:"Shell command to execute",demandOption:!0}).option("all",{type:"boolean",alias:"a",describe:"Run across all configured repos"}).option("dirty",{type:"boolean",describe:"Only run in dirty worktrees"}).option("clean",{type:"boolean",describe:"Only run in clean worktrees"}).option("behind",{type:"boolean",describe:"Only run in worktrees behind upstream"}).option("parallel",{type:"boolean",alias:"p",describe:"Run commands in parallel (default: sequential)"}).option("json",{type:"boolean",alias:"j",describe:"Output results as JSON"}),handler:async(t)=>{let e=t.command,o=!!t.parallel,n=!!t.json;try{let r;if(t.all){let a=Y(),u=await E.getMainRepoPath().catch(()=>process.cwd()),h=Re(a),d=new Set([Jc(u)]),w=[u];for(let x of h){let m=Jc(x);if(!d.has(m))d.add(m),w.push(x)}r=await E.listAll(w)}else r=await E.list();let i=r.filter((a)=>!a.isMain);if(t.dirty)i=i.filter((a)=>a.isDirty);if(t.clean)i=i.filter((a)=>!a.isDirty);if(t.behind)i=(await Promise.all(i.map(async(u)=>{if(!u.branch)return{wt:u,behind:!1};let h=await E.getAheadBehind(u.branch,u.path);return{wt:u,behind:h.behind>0}}))).filter((u)=>u.behind).map((u)=>u.wt);if(i.length===0)console.log("No matching worktrees found."),process.exit(0);if(!n)console.log(`Running '${e}' in ${i.length} worktree(s)...
147
- `);let s=async(a)=>{let u=Bun.spawn(["sh","-c",e],{cwd:a.path,stdout:"pipe",stderr:"pipe",env:{...Bun.env,OMW_BRANCH:a.branch??"",OMW_WORKTREE_PATH:a.path,OMW_REPO_PATH:a.repoPath}}),[h,d,w]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);return{branch:a.branch??"(detached)",path:a.path,exitCode:w,stdout:h.trim(),stderr:d.trim()}},c;if(o)c=await Promise.all(i.map(s));else{c=[];for(let a of i)c.push(await s(a))}if(n)console.log(JSON.stringify(c,null,2));else{for(let h of c){let d=h.exitCode===0?"\u2713":"\u2717";if(console.log(`${d} ${h.branch} (exit ${h.exitCode})`),h.stdout)for(let w of h.stdout.split(`
148
- `))console.log(` ${w}`);if(h.stderr)for(let w of h.stderr.split(`
149
- `))console.log(` ${w}`);console.log()}let a=c.filter((h)=>h.exitCode===0).length,u=c.length-a;console.log(`Done: ${a} passed, ${u} failed`)}let f=c.some((a)=>a.exitCode!==0);process.exit(f?1:0)}catch(r){if(r instanceof it)console.error(`Git error: ${r.message}`);else console.error(`Error: ${r.message}`);process.exit(1)}}},Ou=Mu});var kc={};xt(kc,{default:()=>Du});var Wu,Du;var Uc=H(()=>{at();Ct();Wu={command:"diff <ref1> [ref2]",describe:"Show diff between two worktrees or branches",builder:(t)=>t.positional("ref1",{type:"string",describe:"First worktree branch or ref",demandOption:!0}).positional("ref2",{type:"string",describe:"Second worktree branch or ref (default: current HEAD)"}).option("stat",{type:"boolean",alias:"s",describe:"Show diffstat summary only"}).option("name-only",{type:"boolean",alias:"n",describe:"Show only names of changed files"}),handler:async(t)=>{let e=t.ref1,o=t.ref2??"HEAD",n=!!t.stat,r=!!t["name-only"];try{let i=await E.getMainRepoPath().catch(()=>process.cwd()),s=await E.list(i),c=(h)=>{return s.find((w)=>w.branch===h)?.branch??h},f=c(e),a=c(o),u=await E.diffBetween(f,a,{stat:n,nameOnly:r},i);if(!u)console.log(`No differences between ${e} and ${o==="HEAD"?"current HEAD":o}`);else console.log(u);process.exit(0)}catch(i){if(i instanceof it)console.error(`Git error: ${i.message}`);else console.error(`Error: ${i.message}`);process.exit(1)}}},Du=Wu});var Kc={};xt(Kc,{default:()=>Bu});var Fu,Bu;var qc=H(()=>{at();Ct();go();Fu={command:"pin [branch]",aliases:["unpin"],describe:"Pin or unpin a worktree",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).option("reason",{type:"string",describe:"Reason for pinning"}).option("list",{type:"boolean",describe:"List pinned worktrees"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("unpin",{type:"boolean",describe:"Unpin instead of pinning"}),handler:async(t)=>{try{let e=t;if(t.list){let c=await E.list(),f=Er(c).map((w)=>({...w,pin:To(w.path)}));if(t.json)console.log(JSON.stringify(f,null,2)),process.exit(0);if(f.length===0)console.log("No pinned worktrees found."),process.exit(0);let a=Math.max(6,...f.map((w)=>(w.branch??"(detached)").length)),u=Math.max(4,...f.map((w)=>w.path.length)),h=Math.max(6,...f.map((w)=>(w.pin?.reason??"\u2014").length)),d=Math.max(9,...f.map((w)=>(w.pin?.pinnedAt??"\u2014").length));console.log(`${"Branch".padEnd(a)} ${"Path".padEnd(u)} ${"Reason".padEnd(h)} ${"Pinned At".padEnd(d)}`),console.log(`${"-".repeat(a)} ${"-".repeat(u)} ${"-".repeat(h)} ${"-".repeat(d)}`);for(let w of f)console.log(`${(w.branch??"(detached)").padEnd(a)} ${w.path.padEnd(u)} ${(w.pin?.reason??"\u2014").padEnd(h)} ${(w.pin?.pinnedAt??"\u2014").padEnd(d)}`);process.exit(0)}let o=t._[0]==="unpin"||!!t.unpin,n=typeof e.branch==="string"?e.branch:typeof t._[1]==="string"?t._[1]:void 0;if(!n)console.error("Error: branch is required"),process.exit(1);let i=(await E.list()).find((c)=>c.branch===n);if(!i)console.error(`Error: no worktree found for '${n}'`),process.exit(1);if(o){if(!To(i.path))console.warn(`Warning: worktree is not pinned: ${i.path}`),process.exit(0);Pr(i.path),console.log(`Unpinned worktree: ${i.path}`),process.exit(0)}if(To(i.path))console.warn(`Warning: worktree is already pinned: ${i.path}`),process.exit(0);let s=typeof e.reason==="string"?e.reason:void 0;yr(i.path,s),console.log(`Pinned worktree: ${i.path}`),process.exit(0)}catch(e){if(e instanceof it)console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}},Bu=Fu});var Xc={};xt(Xc,{default:()=>ju});import*as Vc from"readline";function Lu(t){let e={create:"\x1B[32m",delete:"\x1B[31m",switch:"\x1B[34m",rename:"\x1B[33m",archive:"\x1B[35m",import:"\x1B[36m",reset:"\x1B[0m"};return`${e[t]??e.reset}${t}${e.reset}`}async function Au(t){let e=Vc.createInterface({input:process.stdin,output:process.stdout});return new Promise((o)=>{e.question(t,(n)=>{e.close(),o(n.toLowerCase()==="y"||n.toLowerCase()==="yes")})})}var Iu,ju;var Zc=H(()=>{at();Ct();Fe();Iu={command:"log",aliases:["logs"],describe:"Show worktree activity log",builder:(t)=>t.option("limit",{type:"number",default:20,describe:"Show the last N entries"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("clear",{type:"boolean",describe:"Clear the activity log"}),handler:async(t)=>{try{let e=await E.getMainRepoPath().catch(()=>process.cwd());if(t.clear){if(!await Au("Clear activity log? [y/N] "))console.log("Cancelled."),process.exit(0);ic(e),console.log("Activity log cleared."),process.exit(0)}let o=typeof t.limit==="number"?t.limit:20,n=rc(e,{limit:o});if(t.json)console.log(JSON.stringify(n,null,2)),process.exit(0);for(let r of n){let i=Lu(r.event),s=r.branch??"(unknown)",c=r.details?Object.entries(r.details).map(([f,a])=>`${f}=${a}`).join(" "):"";console.log(`[${r.timestamp}] ${i} ${s}${c?` (${c})`:""}`)}process.exit(0)}catch(e){if(e instanceof it)console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}},ju=Iu});import{existsSync as ta,mkdirSync as Gu,readFileSync as Dr,statSync as Tu,writeFileSync as Qc}from"fs";import{homedir as _u}from"os";import{basename as Nu,join as No,resolve as Hu}from"path";function Ju(t){let e=No(t,".git"),o=Tu(e,{throwIfNoEntry:!1});if(!o)return null;let n=e;if(!o.isDirectory()){let f=Dr(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim();n=Hu(t,f)}let r=No(n,"HEAD");if(!ta(r))return null;let s=Dr(r,"utf-8").trim().match(/^ref:\s+(.+)$/);if(!s)return null;return s[1]?.replace(/^refs\/heads\//,"")??null}async function Yc(t,e){let o=Bun.spawn(["git",...t],{cwd:e,stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[n,r,i]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(i!==0)throw Error(`git ${t.join(" ")} failed: ${r.trim()}`);return n}function ea(){let t=Bun.env.HOME??_u();return No(t,".omw","archives")}async function oa(t,e){let o=Nu(e),n=await E.getBranchForWorktree(t)??Ju(t)??"detached-head",r=n.replaceAll("/","-"),i=new Date().toISOString(),s=i.replaceAll(":","-"),c=No(ea(),o);Gu(c,{recursive:!0});let f=No(c,`${r}-${s}`),a=`${f}.patch`,u=`${f}.json`;try{let[h,d,w]=await Promise.all([Yc(["diff"],t),Yc(["format-patch","-5","HEAD","--stdout"],t),E.getLastCommit(t)]),x=["# OMW archive",`# repo: ${o}`,`# branch: ${n}`,`# archivedAt: ${i}`,"","# Uncommitted diff",h||"# (no uncommitted changes)","","# Recent commits (git format-patch -5 HEAD --stdout)",d||"# (no recent commits)"].join(`
150
- `);Qc(a,x,"utf-8");let m={branch:n,repo:o,archivedAt:i,patchPath:a,commitHash:w?.hash??"",message:w?.message??""};return Qc(u,JSON.stringify(m,null,2),"utf-8"),m}catch(h){let d=h instanceof Error?h.message:"Unknown archive error";throw new ar(`Failed to archive worktree: ${d}`,n,"archive_failed")}}async function na(t){let e=ea();if(!ta(e))return[];let o=t?`${t}/*.json`:"**/*.json",n=new Bun.Glob(o),r=[];for await(let i of n.scan({cwd:e,absolute:!0}))try{let s=Dr(i,"utf-8");r.push(JSON.parse(s))}catch{}return r.sort((i,s)=>{let c=Date.parse(i.archivedAt);return Date.parse(s.archivedAt)-c})}var ra=H(()=>{at();Ct()});var sa={};xt(sa,{default:()=>Uu});import{basename as zu}from"path";import*as ia from"readline";async function vu(t){let e=ia.createInterface({input:process.stdin,output:process.stdout});return new Promise((o)=>{e.question(t,(n)=>{e.close(),o(n.toLowerCase()==="y"||n.toLowerCase()==="yes")})})}var ku,Uu;var ca=H(()=>{at();Fe();Ct();ra();$t();me();ku={command:"archive [branch]",describe:"Archive worktree changes and optionally remove",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name or worktree path"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}).option("keep",{type:"boolean",describe:"Archive without removing the worktree"}).option("list",{type:"boolean",describe:"List all archives"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON (with --list)"}),handler:async(t)=>{let e=t.branch,o=!!t.yes,n=!!t.keep,r=!!t.list,i=!!t.json;try{if(r){let h=await na();if(i)console.log(JSON.stringify(h,null,2));else if(h.length===0)console.log("No archives found.");else{console.log(`Archives:
151
- `);for(let d of h){let w=new Date(d.archivedAt).toLocaleString();console.log(` ${d.repo}/${d.branch}`),console.log(` Date: ${w}`),console.log(` Commit: ${d.commitHash.slice(0,8)} ${d.message}`),console.log(` Patch: ${d.patchPath}`),console.log()}}process.exit(0)}if(!e)console.error("Error: branch name is required (or use --list to view archives)"),process.exit(1);let s=await E.getMainRepoPath().catch(()=>process.cwd()),f=(await E.list(s)).find((h)=>h.branch===e||h.path===e||h.path.endsWith("/"+e));if(!f)console.error(`Error: no worktree found for '${e}'`),process.exit(1);if(f.isMain)console.error("Error: cannot archive the main worktree"),process.exit(1);let a=n?"Archive":"Archive and remove";if(!o){if(!await vu(`${a} worktree '${f.branch??zu(f.path)}'? [y/N] `))console.log("Cancelled."),process.exit(0)}let u=await oa(f.path,s);console.log(`Archived: ${u.patchPath}`);try{Ut(s,{timestamp:new Date().toISOString(),event:"archive",branch:u.branch,path:u.patchPath})}catch{}if(!n){let h=Y(),d=Bt(h,s);if(d.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(d.postRemove,{cwd:f.path,env:{OMW_BRANCH:f.branch??"",OMW_WORKTREE_PATH:f.path,OMW_REPO_PATH:s},onOutput:(w)=>console.log(` ${w}`)}).catch((w)=>console.warn(`Warning: postRemove hook failed: ${w.message}`));await E.remove(f.path,{force:!1},s),Mt(),console.log(`Removed worktree: ${f.path}`)}process.exit(0)}catch(s){if(s instanceof it)console.error(`Git error: ${s.message}`);else console.error(`Error: ${s.message}`);process.exit(1)}}},Uu=ku});var aa={};xt(aa,{default:()=>Zu});import{dirname as Ku,basename as qu,join as Vu}from"path";var Xu,Zu;var fa=H(()=>{at();Fe();Ct();Xu={command:"rename <old> <new>",describe:"Rename worktree branch",builder:(t)=>t.positional("old",{type:"string",demandOption:!0,describe:"Current branch name"}).positional("new",{type:"string",demandOption:!0,describe:"New branch name"}).option("move-path",{type:"boolean",describe:"Also rename the worktree directory path"}),handler:async(t)=>{let{old:e,new:o}=t,n=!!t["move-path"];try{let r=await E.getMainRepoPath().catch(()=>process.cwd()),i=await E.list(r),s=i.find((u)=>u.branch===e||u.path===e||u.path.endsWith("/"+e));if(!s)console.error(`Error: no worktree found for '${e}'`),process.exit(1);if(s.isMain)console.error("Error: cannot rename the main worktree branch"),process.exit(1);if(i.find((u)=>u.branch===o))console.error(`Error: branch '${o}' already exists`),process.exit(1);let f=Bun.spawn(["git","branch","-m",e,o],{cwd:r,stdout:"pipe",stderr:"pipe",env:{...process.env,LC_ALL:"C"}}),a=await f.exited;if(a!==0){let u=await new Response(f.stderr).text();throw new it(`Failed to rename branch: ${u.trim()}`,a,u,`git branch -m ${e} ${o}`)}if(Mt(),n){let u=o.replace(/\//g,"-"),h=Ku(s.path),d=qu(s.path),w=e.replace(/\//g,"-"),x=d.replace(w,u),m=Vu(h,x);if(m!==s.path)await E.move(s.path,m,r),Mt(),console.log(`Moved worktree: ${s.path} \u2192 ${m}`)}console.log(`Renamed branch: ${e} \u2192 ${o}`);try{Ut(r,{timestamp:new Date().toISOString(),event:"rename",branch:o,details:{oldBranch:e}})}catch{}process.exit(0)}catch(r){if(r instanceof it)console.error(`Git error: ${r.message}`);else console.error(`Error: ${r.message}`);process.exit(1)}}},Zu=Xu});var la={};xt(la,{default:()=>ep});import{basename as Qu,resolve as Yu}from"path";var tp,ep;var ha=H(()=>{Ct();$t();me();tp={command:"clone <url> [path]",describe:"Clone a repository and initialize omw config",builder:(t)=>t.positional("url",{type:"string",describe:"Repository URL to clone",demandOption:!0}).positional("path",{type:"string",describe:"Target directory path"}).option("template",{type:"string",alias:"t",describe:"Apply a named template after cloning"}).option("init-config",{type:"boolean",describe:"Initialize omw config after cloning",default:!0}),handler:async(t)=>{let{url:e,template:o}=t,n=t["init-config"],r=t.path;if(!r)try{let i=new URL(e);r=Qu(i.pathname).replace(/\.git$/,"")}catch{r=(e.split("/").pop()??e.split(":").pop()??e).replace(/\.git$/,"")}if(!r)console.error("Error: could not determine target directory from URL"),process.exit(1);console.log(`Cloning ${e}...`);try{let i=Bun.spawn(["git","clone",e,r],{stdout:"pipe",stderr:"pipe",env:{...process.env,LC_ALL:"C"}}),[,s,c]=await Promise.all([new Response(i.stdout).text(),new Response(i.stderr).text(),i.exited]);if(c!==0)throw new it(`git clone failed: ${s.trim()}`,c,s.trim(),`git clone ${e} ${r}`)}catch(i){if(i instanceof it)console.error(`Error: ${i.stderr||i.message}`);else console.error(`Error: ${i.message}`);process.exit(1)}if(n)try{let i=ne();console.log(` \u2713 Config initialized: ${i}`)}catch(i){console.warn(` \u26A0 Could not initialize config: ${i.message}`)}if(o)try{let i=Y(),s=mn(i,o);if(!s){let u=Object.keys(i.templates??{});if(console.error(`Error: template '${o}' not found.`),u.length>0)console.error(`Available templates: ${u.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}console.log(` Using template '${o}'`);let c=Yu(r),f=Bt(i,c),a=xn(f,s);if(a.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(a.postCreate,{cwd:c,env:{OMW_REPO_PATH:c},onOutput:(u)=>console.log(` ${u}`)}),console.log(" \u2713 Hooks completed");console.log(` \u2713 Template '${o}' applied`)}catch(i){if(i instanceof mo)console.error(`Error: hook timed out: ${i.command}`);else if(i instanceof po){if(console.error(`Error: hook failed (exit ${i.exitCode}): ${i.command}`),i.stderr)console.error(i.stderr)}else console.error(`Error applying template: ${i.message}`);process.exit(1)}console.log(`
152
- Cloned: ${e} \u2192 ${r}`),process.exit(0)}},ep=tp});import{existsSync as ua,readFileSync as Br,statSync as Mn}from"fs";import{basename as op,join as On,resolve as Ye}from"path";async function Fr(t,e){let o=Bun.spawn(["git",...t],{cwd:e,stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[n,r,i]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(i!==0)throw Error(`git ${t.join(" ")} failed: ${r.trim()}`);return n.trim()}function np(t){let e=On(t,"HEAD");if(!ua(e))return null;let n=Br(e,"utf-8").trim().match(/^ref:\s+refs\/heads\/(.+)$/);return n?n[1]:null}function pa(t){let e=Ye(t),o=On(e,".git"),n=Mn(o,{throwIfNoEntry:!1});if(!n)throw Error(`Missing .git at ${o}`);if(n.isDirectory())return o;let i=Br(o,"utf-8").trim().match(/^gitdir:\s*(.+)$/);if(!i)throw Error(`Invalid .git file format at ${o}`);return Ye(e,i[1].trim())}function Lr(t){let e=Ye(t),o=Mn(e,{throwIfNoEntry:!1});if(!o)return{valid:!1,reason:`Path does not exist: ${e}`};if(!o.isDirectory())return{valid:!1,reason:`Path is not a directory: ${e}`};let n=On(e,".git"),r=Mn(n,{throwIfNoEntry:!1});if(!r)return{valid:!1,reason:`Target is missing .git: ${e}`};if(r.isDirectory())return{valid:!1,reason:`Target is not a linked git worktree (.git is a directory): ${e}`};if(!r.isFile())return{valid:!1,reason:`Target has invalid .git entry: ${e}`};let i="";try{i=pa(e)}catch{return{valid:!1,reason:`Cannot resolve gitdir from .git file: ${e}`}}if(!Mn(i,{throwIfNoEntry:!1})?.isDirectory())return{valid:!1,reason:`Resolved gitdir does not exist: ${i}`};let c=np(i);if(!c)return{valid:!1,reason:`Cannot resolve branch name from HEAD: ${e}`};return{valid:!0,branch:c}}async function da(t,e){let o=Ye(t),n=Lr(o);if(!n.valid)throw new Wo(`Cannot import worktree: ${n.reason??"invalid target"}`,o,n.reason??"invalid target");let[r,i,s]=await Promise.all([Fr(["rev-parse","HEAD"],o),Fr(["status","--porcelain"],o),Fr(["rev-parse","--git-common-dir"],o)]),c=Ye(o,s),f=c.endsWith("/.git")||c.endsWith("\\.git")?c.slice(0,-5):c,a=op(f),u=Ye(o)===Ye(f),h=pa(o),d=On(h,"locked"),w=ua(d),x=w?Br(d,"utf-8").trim()||void 0:void 0;if(e?.focus&&e.focus.length>0)so(o,e.focus);if(e?.pin)try{(await Promise.resolve().then(() => (go(),ks))).writePin(o)}catch{}return{path:o,branch:n.branch??null,head:r,isMain:u,isDirty:i.length>0,isLocked:w,lockReason:x,repoName:a,repoPath:f}}var ma=H(()=>{le();Ct()});var xa={};xt(xa,{default:()=>sp});import{resolve as rp}from"path";var ip,sp;var wa=H(()=>{ma();at();Fe();Ct();ip={command:"import <path>",describe:"Adopt a worktree with omw metadata",builder:(t)=>t.positional("path",{type:"string",describe:"Existing worktree directory path",demandOption:!0}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("pin",{type:"boolean",describe:"Pin the worktree"}),handler:async(t)=>{let e=rp(t.path),o=Lr(e);if(!o.valid)console.error(`Error: ${o.reason??"invalid import target"}`),process.exit(1);let r=t.focus?.flatMap((s)=>s.split(/[,\s]+/)).map((s)=>s.trim()).filter(Boolean)??[],i=!!t.pin;try{let s=await da(e,{focus:r,pin:i});Mt();let c=s.branch??o.branch??"unknown",f=s.repoPath??await E.getMainRepoPath().catch(()=>process.cwd());console.log(`Imported worktree: ${c} at ${s.path}`);try{Ut(f,{timestamp:new Date().toISOString(),event:"import",branch:s.branch??o.branch??"unknown",path:s.path})}catch{}if(r.length>0)console.log(` Focus: ${r.join(", ")}`);if(i)console.log(" Pinned");process.exit(0)}catch(s){if(s instanceof Wo)console.error(`Error: ${s.reason}`);else console.error(`Error: ${s.message}`);process.exit(1)}}},sp=ip});var ga={};xt(ga,{default:()=>lp});import{basename as Wn}from"path";async function ap(t,e,o){let[n,r]=await Promise.all([mr(e),E.list(t)]);if(o){let i=n.map((s)=>{let c=r.find((a)=>{let u=a.branch??Wn(a.path);return ye(u,e)===s.name}),f=c?kt(c.path):null;return{...s,branch:c?.branch??null,worktreePath:c?.path??null,layout:f?.layout??null}});console.log(JSON.stringify(i,null,2));return}if(n.length===0){console.log("No active omw sessions.");return}console.log(`Active sessions (${n.length}):
153
- `);for(let i of n){let s=r.find((h)=>{let d=h.branch??Wn(h.path);return ye(d,e)===i.name}),c=s?kt(s.path):null,f=i.attached?" (attached)":"",a=c?.layout?` [${c.layout}]`:"",u=s?.branch?` ${s.branch}`:"";console.log(` ${i.name}${u} ${i.windows} windows${a}${f}`)}}async function fp(t,e){let[o,n]=await Promise.all([mr(e),E.list(t)]);if(o.length===0){console.log("No active omw sessions.");return}let r=0;for(let i of o){let s=n.find((c)=>{let f=kt(c.path),a=c.branch??Wn(c.path);return f?.name===i.name||ye(a,e)===i.name});if(await dr(i.name),s)ur(s.path);r++,console.log(` \u2713 Killed ${i.name}`)}console.log(`
154
- Killed ${r} session${r!==1?"s":""}.`)}var cp,lp;var ba=H(()=>{at();Ct();$t();Pe();cp={command:"session [branch-or-path]",aliases:["ss"],describe:"Manage tmux sessions for worktrees",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path to open session for"}).option("list",{type:"boolean",alias:"l",describe:"List active omw tmux sessions"}).option("kill",{type:"boolean",alias:"k",describe:"Kill the session for the specified worktree"}).option("kill-all",{type:"boolean",describe:"Kill all omw tmux sessions"}).option("layout",{type:"string",describe:"Use a named layout from config"}).option("json",{type:"boolean",alias:"j",describe:"Output in JSON format"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.list,n=!!t.kill,r=!!t["kill-all"],i=t.layout,s=!!t.json;if(!await ao())console.error("Error: tmux is not installed or not in PATH."),console.error("Install tmux to use session management."),process.exit(1);try{let c=await E.getMainRepoPath().catch(()=>process.cwd()),f=Y(),a=Me(f);if(o)await ap(c,a.prefix,s),process.exit(0);if(r)await fp(c,a.prefix),process.exit(0);if(!e)console.error("Error: specify a branch or worktree path, or use --list."),process.exit(1);let h=(await E.list(c)).find((m)=>m.branch===e||m.path===e||m.path.endsWith("/"+e));if(!h)console.error(`Error: no worktree found for '${e}'`),process.exit(1);let d=h.branch??Wn(h.path);if(n){if(await hn(d,h.path,a.prefix))console.log(`Killed session for '${d}'`);else console.log(`No active session for '${d}'`);process.exit(0)}let w=wn(f,i),x=await ln(d,h.path,{layout:w,prefix:a.prefix,attach:!0,layoutName:i??a.defaultLayout});console.log(`Session: ${x}`),process.exit(0)}catch(c){if(c instanceof it)console.error(`Git error: ${c.message}`);else console.error(`Error: ${c.message}`);process.exit(1)}}};lp=cp});import{existsSync as Ar,mkdirSync as Ca,writeFileSync as $a}from"fs";import{dirname as Sa,join as bo}from"path";function hp(t){let e=process.env.HOME||process.env.USERPROFILE||"~";switch(t){case"claude-code":return bo(e,".claude","skills","omw");case"codex":return bo(e,".agents","skills","omw");case"opencode":return bo(e,".config","opencode","skill","omw")}}function up(t){return bo(hp(t),"SKILL.md")}function mp(t){return["| Flag | Type | Alias | Description |","|------|------|-------|-------------|",...t.length>0?t.map((o)=>`| ${o.flag} | ${o.type} | ${o.alias} | ${o.description} |`):["| - | - | - | No options |"]].join(`
155
- `)}function xp(){let t=dp.map((o)=>`| \`${o.command}\` | ${o.aliases} | ${o.description} |`),e=ya.map((o)=>`- [\`omw ${o.command}\`](references/${o.command}.md)`);return["---","name: omw",`description: ${pp}`,"metadata:"," author: getsolaris",' version: "1.0.0"',"---","","# oh-my-worktree (omw)","","## Quick Start","","### Create a feature worktree","","```bash","omw add feature/my-feature --base main","```","","### List and check status","","```bash","omw list","omw status","```","","### Clean up merged worktrees","","```bash","omw clean --dry-run","omw clean --yes","```","","### Run commands across worktrees","","```bash",'omw exec "bun test" --parallel',"```","","### Review a GitHub PR","","```bash","omw add pr-review --pr 42","omw open pr-review","```","","### Use templates","","```bash","# Create worktree with predefined template (hooks, base branch, settings)","omw add feature/new --template frontend","```","","### Tmux session management","","```bash","# Create worktree with tmux session","omw add feature/api --session --layout dev","","# List active sessions","omw session --list","","# Attach to existing session","omw session feature/api","```","","### Shell integration setup","","```bash","# Add to ~/.zshrc or ~/.bashrc",'eval "$(omw shell-init)"',"","# Then switch worktrees with cd","omw switch feature/auth","```","","## Command Overview","","| Command | Aliases | Description |","|---------|---------|-------------|",...t,"","## Monorepo Workflows","","Use focus paths to target packages and trigger matching monorepo hooks.","","```bash","omw add feature/web-auth --focus apps/web,apps/api","omw import /path/to/worktree --focus packages/core --pin","omw list --json","```","","Focus accepts comma-separated values, space-separated values, or repeated --focus flags.","","## Configuration","","- Config path: `~/.config/oh-my-worktree/config.json`","- Use `--json` output flags for scripting and automation","- Environment variables in `omw exec`: `OMW_BRANCH`, `OMW_WORKTREE_PATH`, `OMW_REPO_PATH`","","## Command Reference","","For detailed options and examples for each command:","",...e,"- [`Configuration Schema`](references/config-schema.md)",""].join(`
156
- `)}function wp(){let t=new Map;for(let o of ya){let n=[`# omw ${o.command}`,"",o.summary,"","## Synopsis","","```",o.synopsis,"```","","## Options","",mp(o.options),"","## Examples","","```bash",`# ${o.examples[0][0]}`,o.examples[0][1],"",`# ${o.examples[1][0]}`,o.examples[1][1],"```","","## Notes","",...o.notes.map((r)=>`- ${r}`),"",...o.configKeys.length>0?["## Configuration","","Related config keys in `~/.config/oh-my-worktree/config.json`:","",...o.configKeys.map((r)=>`- ${r}`),""]:[]];t.set(`${o.command}.md`,n.join(`
157
- `))}let e=gp();return t.set("config-schema.md",e),t}function gp(){return["# Configuration Schema","","Config file path: `~/.config/oh-my-worktree/config.json`","","## Minimal Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env", ".env.local"],',' "linkFiles": ["node_modules"],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true'," }","}","```","","## Full Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env"],',' "linkFiles": [],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true,',' "sharedDeps": {',' "strategy": "symlink",',' "paths": ["node_modules"]'," }"," },",' "repos": ['," {",' "path": "/path/to/repo",',' "copyFiles": [".env", ".env.local"],',' "monorepo": {',' "autoDetect": true,',' "hooks": ['," {",' "glob": "apps/*",',' "postCreate": ["bun install"]'," }"," ]"," }"," }"," ],",' "templates": {',' "frontend": {',' "base": "main",',' "copyFiles": [".env"],',' "postCreate": ["bun install", "bun run build"]'," },",' "review": {',' "base": "main",',' "postCreate": ["bun install"]'," }"," },",' "sessions": {',' "enabled": true,',' "autoCreate": false,',' "autoKill": true,',' "prefix": "omw",',' "defaultLayout": "dev",',' "layouts": {',' "dev": {',' "windows": [',' { "name": "editor", "command": "nvim ." },',' { "name": "server", "command": "bun run dev" },',' { "name": "shell" }'," ]"," }"," }"," },",' "lifecycle": {',' "autoCleanMerged": false,',' "staleAfterDays": 30,',' "maxWorktrees": 10'," },",' "theme": "default"',"}","```","","## Key Reference","","### defaults","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `worktreeDir` | string | `~/.omw/worktrees/{repo}-{branch}` | Directory pattern. Supports `{repo}` and `{branch}` variables |","| `copyFiles` | string[] | `[]` | Files to copy from main worktree on creation |","| `linkFiles` | string[] | `[]` | Files to symlink from main worktree on creation |","| `postCreate` | string[] | `[]` | Shell commands to run after worktree creation |","| `postRemove` | string[] | `[]` | Shell commands to run before worktree removal |","| `autoUpstream` | boolean | `false` | Automatically set upstream tracking branch |","| `sharedDeps.strategy` | string | `symlink` | Strategy for sharing deps: `symlink`, `hardlink`, or `copy` |","| `sharedDeps.paths` | string[] | `[]` | Paths to share between worktrees |","","### repos[]","","Per-repository overrides. Same keys as `defaults` plus:","","| Key | Type | Description |","|-----|------|-------------|","| `path` | string | **Required.** Absolute path to the repository |","| `monorepo.autoDetect` | boolean | Auto-detect monorepo tools (pnpm, turbo, nx, lerna) |","| `monorepo.extraPatterns` | string[] | Additional glob patterns for package discovery |","| `monorepo.hooks[]` | object[] | Per-package hooks matched by glob pattern |","| `monorepo.hooks[].glob` | string | Glob to match against focus paths |","| `monorepo.hooks[].copyFiles` | string[] | Package-level files to copy |","| `monorepo.hooks[].linkFiles` | string[] | Package-level files to symlink |","| `monorepo.hooks[].postCreate` | string[] | Package-level post-create hooks |","| `monorepo.hooks[].postRemove` | string[] | Package-level post-remove hooks |","","### templates","","Named presets applied via `omw add --template <name>` or `omw clone --template <name>`.","","| Key | Type | Description |","|-----|------|-------------|","| `base` | string | Default base branch for new worktrees |","| `worktreeDir` | string | Override directory pattern |","| `copyFiles` | string[] | Override files to copy |","| `linkFiles` | string[] | Override files to symlink |","| `postCreate` | string[] | Override post-create hooks |","| `postRemove` | string[] | Override post-remove hooks |","| `autoUpstream` | boolean | Override upstream tracking |","","### sessions","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `enabled` | boolean | `false` | Enable tmux session integration |","| `autoCreate` | boolean | `false` | Auto-create session on `omw add` |","| `autoKill` | boolean | `false` | Auto-kill session on `omw remove` |","| `prefix` | string | `omw` | Prefix for tmux session names |","| `defaultLayout` | string | - | Default layout name |","| `layouts.<name>.windows[]` | object[] | - | Window definitions |","| `layouts.<name>.windows[].name` | string | **Required.** | Window name |","| `layouts.<name>.windows[].command` | string | - | Command to run in window |","","### lifecycle","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `autoCleanMerged` | boolean | `false` | Auto-clean merged worktrees |","| `staleAfterDays` | number | `30` | Days until a worktree is considered stale |","| `maxWorktrees` | number | `10` | Maximum number of worktrees |",""].join(`
158
- `)}function Pa(t){let e=up(t),o=bo(Sa(e),"references"),n=xp(),r=wp(),i=Sa(e);if(!Ar(i))Ca(i,{recursive:!0});if(!Ar(o))Ca(o,{recursive:!0});let s=Ar(e);$a(e,n,"utf-8");for(let[c,f]of r.entries())$a(bo(o,c),f,"utf-8");return{filePath:e,referenceDir:o,referenceCount:r.size,platform:t,action:s?"updated":"created"}}var Ir,pp="Git worktree manager. Use when working with git worktrees \u2014 creating, switching, removing, listing, or managing worktrees across repositories. Also use for monorepo focus, tmux sessions, and worktree health checks.",dp,ya;var Ea=H(()=>{Ir=["claude-code","codex","opencode"];dp=[{command:"add",aliases:"-",description:"Create a new worktree from a branch, template, or PR."},{command:"remove",aliases:"rm",description:"Remove a worktree by branch or path."},{command:"list",aliases:"ls",description:"List worktrees with branch, path, status, and focus."},{command:"switch",aliases:"sw",description:"Print shell cd command for a target worktree."},{command:"status",aliases:"st",description:"Show status summary for worktrees."},{command:"clean",aliases:"-",description:"Clean merged worktrees and optionally report stale ones."},{command:"doctor",aliases:"-",description:"Run worktree health checks and optional auto-fixes."},{command:"exec",aliases:"-",description:"Run commands across non-main worktrees."},{command:"diff",aliases:"-",description:"Compare two refs or worktree branches."},{command:"pin",aliases:"unpin",description:"Pin or unpin worktrees and inspect pin metadata."},{command:"log",aliases:"logs",description:"Read or clear the activity log."},{command:"archive",aliases:"-",description:"Archive worktree changes as patch files."},{command:"rename",aliases:"-",description:"Rename a worktree branch and optionally move its path."},{command:"clone",aliases:"-",description:"Clone a repository and initialize omw setup."},{command:"import",aliases:"-",description:"Import an existing worktree into omw metadata."},{command:"session",aliases:"ss",description:"Manage tmux sessions for worktrees."},{command:"config",aliases:"-",description:"Initialize, inspect, validate, and manage config profiles."},{command:"open",aliases:"-",description:"Open a worktree path in your preferred editor."},{command:"shell-init",aliases:"-",description:"Generate shell integration and completions."},{command:"init",aliases:"-",description:"Initialize config or install/update omw AI agent skill files."}],ya=[{command:"add",summary:"Create a new worktree from a branch, template, or GitHub PR.",synopsis:"omw add [branch] [path]",options:[{flag:"--create",type:"boolean",alias:"-c",description:"Optional compatibility flag; missing branches are created automatically"},{flag:"--base",type:"string",alias:"-b",description:"Base branch/commit for new branch"},{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--template",type:"string",alias:"-t",description:"Use a named template from config"},{flag:"--pr",type:"number",alias:"-",description:"Create worktree from a GitHub PR number"},{flag:"--session",type:"boolean",alias:"-s",description:"Create a tmux session for this worktree"},{flag:"--layout",type:"string",alias:"-",description:"Session layout name from config"}],examples:[["Create a feature branch worktree","omw add feature/auth --base main"],["Create from PR with session layout","omw add feature/review --pr 123 --session --layout dev"]],notes:["Creates the branch automatically when it does not already exist.","Existing branches are reused as-is; --base only applies when a new branch is created.","Runs copyFiles, linkFiles, sharedDeps, postCreate hooks, monorepo hooks after creation.","Rolls back on hook failure.","Requires gh CLI for --pr.","Supports comma/space separated focus paths."],configKeys:["`defaults.worktreeDir` \u2014 Directory pattern for new worktrees","`defaults.copyFiles` \u2014 Files to copy from main worktree","`defaults.linkFiles` \u2014 Files to symlink from main worktree","`defaults.sharedDeps` \u2014 Shared dependency strategy and paths","`defaults.postCreate` \u2014 Hooks to run after worktree creation","`defaults.autoUpstream` \u2014 Auto-set upstream tracking branch","`templates.*` \u2014 Named template overrides","`sessions.autoCreate` \u2014 Auto-create tmux session on add","`sessions.layouts` \u2014 Tmux session layout definitions"]},{command:"remove",summary:"Remove a worktree by branch name or path.",synopsis:"omw remove <branch-or-path>",options:[{flag:"--force",type:"boolean",alias:"-f",description:"Force removal even with uncommitted changes"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"}],examples:[["Remove a branch worktree","omw remove feature/auth"],["Force remove without prompt","omw remove feature/auth --force --yes"]],notes:["Runs postRemove hooks and monorepo postRemove hooks before removal.","Cannot remove main worktree.","Cannot remove locked worktrees.","Auto-kills tmux session if sessions.autoKill is enabled."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal","`sessions.autoKill` \u2014 Auto-kill tmux session on remove"]},{command:"list",summary:"List worktrees with branch, path, status, and focus details.",synopsis:"omw list",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--porcelain",type:"boolean",alias:"-p",description:"Machine-readable output"},{flag:"--all",type:"boolean",alias:"-a",description:"List worktrees from all configured repos"}],examples:[["Show all worktrees","omw list"],["Get machine-readable output","omw list --porcelain"]],notes:["Shows branch, path, status (clean/dirty/locked), focus paths.","Focus column truncated to 40 chars."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"switch",summary:"Switch shell context to a worktree by branch or path.",synopsis:"omw switch <branch-or-path>",options:[],examples:[["Switch using branch name","omw switch feature/auth"],["Switch using path","omw switch ~/.omw/worktrees/repo-feature-auth"]],notes:["Outputs cd command for shell eval.","Requires shell integration (omw shell-init).","Auto-switches tmux session if sessions.enabled and inside tmux.","Logs switch activity."],configKeys:["`sessions.enabled` \u2014 Enable tmux session switching","`sessions.prefix` \u2014 Tmux session name prefix"]},{command:"status",summary:"Show branch health, sync state, commit info, and focus.",synopsis:"omw status",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--all",type:"boolean",alias:"-a",description:"Show worktrees from all configured repos"}],examples:[["Print status table","omw status"],["Parse status in scripts","omw status --json"]],notes:["Shows branch, dirty count, sync status (ahead/behind), last commit info, focus paths.","Marks current worktree with *."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"clean",summary:"Remove merged worktrees and optionally inspect stale candidates.",synopsis:"omw clean",options:[{flag:"--dry-run",type:"boolean",alias:"-n",description:"Show what would be removed"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation"},{flag:"--stale",type:"boolean",alias:"-",description:"Also show stale worktrees based on lifecycle config"}],examples:[["Preview merged cleanup","omw clean --dry-run"],["Run cleanup without prompts","omw clean --yes"]],notes:["Only removes merged worktrees.","Skips pinned and dirty worktrees.","Runs git worktree prune after cleanup.","--stale uses lifecycle config (staleAfterDays, maxWorktrees)."],configKeys:["`lifecycle.staleAfterDays` \u2014 Days until a worktree is considered stale","`lifecycle.maxWorktrees` \u2014 Maximum allowed worktrees","`lifecycle.autoCleanMerged` \u2014 Auto-clean merged worktrees"]},{command:"doctor",summary:"Run health checks for worktree state and configuration.",synopsis:"omw doctor",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--fix",type:"boolean",alias:"-",description:"Auto-fix issues"}],examples:[["Run health checks","omw doctor"],["Auto-fix detectable issues","omw doctor --fix"]],notes:["Checks: git version (>=2.17), config validity, stale worktrees, orphaned directories, lock status, dirty worktrees.","Auto-fix: prune stale, remove orphans, unlock stale locks.","Exit code 0 if healthy, 1 if warnings/errors."],configKeys:[]},{command:"exec",summary:"Run a shell command across filtered non-main worktrees.",synopsis:"omw exec <command>",options:[{flag:"--all",type:"boolean",alias:"-a",description:"Run across all configured repos"},{flag:"--dirty",type:"boolean",alias:"-",description:"Only run in dirty worktrees"},{flag:"--clean",type:"boolean",alias:"-",description:"Only run in clean worktrees"},{flag:"--behind",type:"boolean",alias:"-",description:"Only run in worktrees behind upstream"},{flag:"--parallel",type:"boolean",alias:"-p",description:"Run commands in parallel"},{flag:"--json",type:"boolean",alias:"-j",description:"Output results as JSON"}],examples:[["Run tests in parallel",'omw exec "bun test" --parallel'],["Pull only behind worktrees",'omw exec "git pull" --behind']],notes:["Runs in non-main worktrees only.","Sets env vars: OMW_BRANCH, OMW_WORKTREE_PATH, OMW_REPO_PATH.","Exit code 1 if any command fails."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"diff",summary:"Diff two refs or worktree branches.",synopsis:"omw diff <ref1> [ref2]",options:[{flag:"--stat",type:"boolean",alias:"-s",description:"Show diffstat summary only"},{flag:"--name-only",type:"boolean",alias:"-n",description:"Show only names of changed files"}],examples:[["Show diffstat only","omw diff feature/a feature/b --stat"],["List changed file names","omw diff feature/a --name-only"]],notes:["ref2 defaults to HEAD.","Resolves worktree branch names to refs automatically."],configKeys:[]},{command:"pin",summary:"Pin or unpin worktrees and inspect pin metadata.",synopsis:"omw pin [branch]",options:[{flag:"--reason",type:"string",alias:"-",description:"Reason for pinning"},{flag:"--list",type:"boolean",alias:"-",description:"List pinned worktrees"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--unpin",type:"boolean",alias:"-",description:"Unpin instead of pinning"}],examples:[["Pin with a reason",'omw pin feature/auth --reason "active sprint"'],["Unpin a branch","omw pin feature/auth --unpin"]],notes:["Pinned worktrees are excluded from omw clean.","Also invokable as omw unpin <branch>.","Pin metadata stored in git internals."],configKeys:[]},{command:"log",summary:"View or clear activity log events.",synopsis:"omw log",options:[{flag:"--limit",type:"number",alias:"-",description:"default 20, Show the last N entries"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--clear",type:"boolean",alias:"-",description:"Clear the activity log"}],examples:[["Show recent entries","omw log --limit 50"],["Clear the log","omw log --clear"]],notes:["Events: create (green), delete (red), switch (blue), rename (yellow), archive (magenta), import (cyan).","Color-coded in terminal."],configKeys:[]},{command:"archive",summary:"Archive worktree changes as patch files before optional removal.",synopsis:"omw archive [branch]",options:[{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"},{flag:"--keep",type:"boolean",alias:"-",description:"Archive without removing the worktree"},{flag:"--list",type:"boolean",alias:"-",description:"List all archives"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON with --list"}],examples:[["Archive and remove","omw archive feature/done --yes"],["List archive records","omw archive --list --json"]],notes:["Archives stored as patch files in ~/.omw/archives/.","Cannot archive main worktree.","Runs postRemove hooks before removal unless --keep."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal"]},{command:"rename",summary:"Rename a worktree branch and optionally move its directory path.",synopsis:"omw rename <old> <new>",options:[{flag:"--move-path",type:"boolean",alias:"-",description:"Also rename the worktree directory path"}],examples:[["Rename a worktree branch","omw rename feature/old feature/new"],["Rename branch and directory","omw rename feature/old feature/new --move-path"]],notes:["Cannot rename main worktree.","Checks for branch name conflicts.","Logs rename activity.","--move-path replaces old branch slug with new one in directory name."],configKeys:[]},{command:"clone",summary:"Clone a repository and optionally apply omw template setup.",synopsis:"omw clone <url> [path]",options:[{flag:"--template",type:"string",alias:"-t",description:"Apply a named template after cloning"},{flag:"--init-config",type:"boolean",alias:"-",description:"default true, Initialize omw config after cloning"}],examples:[["Clone and initialize","omw clone https://github.com/user/repo.git"],["Clone with template and no config init","omw clone https://github.com/user/repo.git --template review --no-init-config"]],notes:["Auto-detects target path from URL.","Runs template postCreate hooks if template specified.","Use --no-init-config to skip config initialization."],configKeys:["`templates.*` \u2014 Named template overrides"]},{command:"import",summary:"Import an existing git worktree into omw metadata.",synopsis:"omw import <path>",options:[{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--pin",type:"boolean",alias:"-",description:"Pin the worktree"}],examples:[["Import a worktree path","omw import /path/to/worktree"],["Import with focus and pin","omw import /path/to/worktree --focus apps/web,apps/api --pin"]],notes:["Validates that path is a valid git worktree.","Logs import activity.","Supports comma/space separated focus paths."],configKeys:[]},{command:"session",summary:"Manage tmux sessions for worktrees.",synopsis:"omw session [branch-or-path]",options:[{flag:"--list",type:"boolean",alias:"-l",description:"List active omw tmux sessions"},{flag:"--kill",type:"boolean",alias:"-k",description:"Kill the session for the specified worktree"},{flag:"--kill-all",type:"boolean",alias:"-",description:"Kill all omw tmux sessions"},{flag:"--layout",type:"string",alias:"-",description:"Use a named layout from config"},{flag:"--json",type:"boolean",alias:"-j",description:"Output in JSON format"}],examples:[["Attach or create a session","omw session feature/auth"],["List sessions as JSON","omw session --list --json"]],notes:["Requires tmux.","Session naming: branch feat/auth-token \u2192 tmux session omw_feat-auth-token.","Supports layout templates with multiple windows."],configKeys:["`sessions.enabled` \u2014 Enable tmux session integration","`sessions.autoCreate` \u2014 Auto-create session on worktree add","`sessions.autoKill` \u2014 Auto-kill session on worktree remove","`sessions.prefix` \u2014 Tmux session name prefix","`sessions.defaultLayout` \u2014 Default layout name","`sessions.layouts` \u2014 Layout definitions with windows"]},{command:"config",summary:"Initialize, inspect, edit, validate, and manage profiles.",synopsis:"omw config",options:[{flag:"--init",type:"boolean",alias:"-",description:"Create default config file"},{flag:"--show",type:"boolean",alias:"-s",description:"Print current config as JSON"},{flag:"--edit",type:"boolean",alias:"-e",description:"Open config in $EDITOR"},{flag:"--path",type:"boolean",alias:"-",description:"Print config file path"},{flag:"--validate",type:"boolean",alias:"-",description:"Validate config against schema"},{flag:"--profiles",type:"boolean",alias:"-",description:"List config profiles"},{flag:"--profile",type:"string",alias:"-",description:"Profile name for activation/deletion"},{flag:"--activate",type:"boolean",alias:"-",description:"Activate the specified profile"},{flag:"--delete",type:"boolean",alias:"-",description:"Delete the specified profile"}],examples:[["Initialize config","omw config --init"],["Activate a profile","omw config --profile work --activate"]],notes:["Config path: ~/.config/oh-my-worktree/config.json.","XDG-compliant."],configKeys:[]},{command:"open",summary:"Open the target or current worktree in an editor.",synopsis:"omw open [branch-or-path]",options:[{flag:"--editor",type:"string",alias:"-e",description:"Editor command to use"},{flag:"--list-editors",type:"boolean",alias:"-",description:"List detected editors"}],examples:[["Open current worktree","omw open"],["Open with specific editor","omw open feature/auth --editor nvim"]],notes:["Auto-detects editors: code, cursor, vim, nvim, emacs, nano, subl, zed, idea, webstorm.","Uses $VISUAL or $EDITOR env vars.","Defaults to current worktree if no branch specified."],configKeys:[]},{command:"shell-init",summary:"Generate shell integration wrappers and completions.",synopsis:"omw shell-init [shell]",options:[{flag:"--completions",type:"string",alias:"-",description:"Generate shell completions: bash, zsh, fish"}],examples:[["Generate shell wrapper","omw shell-init zsh"],["Generate completion script","omw shell-init --completions fish"]],notes:["Shell arg is auto-detected if omitted.","Generates wrapper function for omw switch to work with shell cd.","Supports bash, zsh, fish."],configKeys:[]},{command:"init",summary:"Initialize omw config or install AI agent skill files.",synopsis:"omw init",options:[{flag:"--skill",type:"string",alias:"-s",description:"Install AI agent skill: claude-code, codex, opencode"}],examples:[["Initialize config","omw init"],["Install Claude Code skill","omw init --skill claude-code"],["Install Codex skill","omw init --skill codex"]],notes:["Without --skill, reuses config initialization and creates only config.json.","With --skill, installs or updates SKILL.md + references/ directory.","Idempotent \u2014 running again updates existing files without breaking existing setup."],configKeys:[]}]});var Ra={};xt(Ra,{default:()=>$p});import{dirname as bp}from"path";var Cp,$p;var Ma=H(()=>{$t();Ea();Cp={command:"init",describe:"Initialize config or install omw integrations",builder:(t)=>t.option("skill",{type:"string",alias:"s",describe:`Install AI agent skill (${Ir.join(", ")})`,choices:Ir}),handler:async(t)=>{let e=t.skill;try{if(!e){let r=ne();console.log(`\u2713 Initialized config \u2192 ${r}`),process.exit(0)}let o=Pa(e),n=o.action==="created"?"Installed":"Updated";console.log(`\u2713 ${n} \u2192 ${bp(o.filePath)}/`),console.log(" SKILL.md"),console.log(` references/ (${o.referenceCount} commands)`),process.exit(0)}catch(o){console.error(`Error: ${o.message}`),process.exit(1)}}},$p=Cp});import"@opentui/solid/preload";import{notStrictEqual as Qa,strictEqual as Ya}from"assert";var Fa={right:Aa,center:Ia};class Gr{constructor(t){var e;this.width=t.width,this.wrap=(e=t.wrap)!==null&&e!==void 0?e:!0,this.rows=[]}span(...t){let e=this.div(...t);e.span=!0}resetOutput(){this.rows=[]}div(...t){if(t.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...t)&&typeof t[0]==="string")return this.applyLayoutDSL(t[0]);let e=t.map((o)=>{if(typeof o==="string")return this.colFromString(o);return o});return this.rows.push(e),e}shouldApplyLayoutDSL(...t){return t.length===1&&typeof t[0]==="string"&&/[\t\n]/.test(t[0])}applyLayoutDSL(t){let e=t.split(`
159
- `).map((n)=>n.split("\t")),o=0;return e.forEach((n)=>{if(n.length>1&&At.stringWidth(n[0])>o)o=Math.min(Math.floor(this.width*0.5),At.stringWidth(n[0]))}),e.forEach((n)=>{this.div(...n.map((r,i)=>{return{text:r.trim(),padding:this.measurePadding(r),width:i===0&&n.length>1?o:void 0}}))}),this.rows[this.rows.length-1]}colFromString(t){return{text:t,padding:this.measurePadding(t)}}measurePadding(t){let e=At.stripAnsi(t);return[0,e.match(/\s*$/)[0].length,0,e.match(/^\s*/)[0].length]}toString(){let t=[];return this.rows.forEach((e)=>{this.rowToString(e,t)}),t.filter((e)=>!e.hidden).map((e)=>e.text).join(`
160
- `)}rowToString(t,e){return this.rasterize(t).forEach((o,n)=>{let r="";o.forEach((i,s)=>{let{width:c}=t[s],f=this.negatePadding(t[s]),a=i;if(f>At.stringWidth(i))a+=" ".repeat(f-At.stringWidth(i));if(t[s].align&&t[s].align!=="left"&&this.wrap){let h=Fa[t[s].align];if(a=h(a,f),At.stringWidth(a)<f)a+=" ".repeat((c||0)-At.stringWidth(a)-1)}let u=t[s].padding||[0,0,0,0];if(u[3])r+=" ".repeat(u[3]);if(r+=jr(t[s],a,"| "),r+=a,r+=jr(t[s],a," |"),u[1])r+=" ".repeat(u[1]);if(n===0&&e.length>0)r=this.renderInline(r,e[e.length-1])}),e.push({text:r.replace(/ +$/,""),span:t.span})}),e}renderInline(t,e){let o=t.match(/^ */),n=o?o[0].length:0,r=e.text,i=At.stringWidth(r.trimRight());if(!e.span)return t;if(!this.wrap)return e.hidden=!0,r+t;if(n<i)return t;return e.hidden=!0,r.trimRight()+" ".repeat(n-i)+t.trimLeft()}rasterize(t){let e=[],o=this.columnWidths(t),n;return t.forEach((r,i)=>{if(r.width=o[i],this.wrap)n=At.wrap(r.text,this.negatePadding(r),{hard:!0}).split(`
145
+ complete -c omw -n '__fish_seen_subcommand_from add switch rename pin archive' -a '(git branch --format="%(refname:short)" 2>/dev/null)'`}function lu(t){switch(t){case"bash":return cu();case"zsh":return au();case"fish":return fu()}}var hu,uu;var Ac=N(()=>{hu={command:"shell-init [shell]",describe:"Print shell integration code for omw switch",builder:(t)=>t.positional("shell",{type:"string",choices:["bash","zsh","fish"],describe:"Shell to generate integration for (auto-detected if omitted)"}).option("completions",{type:"string",describe:"Generate shell completions (bash, zsh, fish)",coerce:(e)=>e===!0?void 0:e}),handler:async(t)=>{let e="completions"in t,o=t.shell,n=t.completions,r=o??n??su(process.env.SHELL);if(e){let i=r==="fish"?Bc():Fc(),s=lu(r);console.log(i+`
146
+ `+s),process.exit(0)}if(r==="fish")console.log(Bc()),process.exit(0);console.log(Fc()),process.exit(0)}},uu=hu});var jc={};xt(jc,{default:()=>du});import{resolve as On}from"path";function Ic(t,e){if(t.length<=e)return t;return t.slice(0,e-3)+"..."}var pu,du;var Tc=N(()=>{ct();Zt();$t();me();Dt();pu={command:"status",aliases:["st"],describe:"Show status overview of all worktrees",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("all",{type:"boolean",alias:"a",describe:"Show worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let c=Y(),u=await at(),a=Be(c),l=new Set([On(u)]),h=[u];for(let d of a){let g=On(d);if(!l.has(g))l.add(g),h.push(d)}e=await E.listAll(h)}else e=await E.list();if(e.length===0)console.log("No worktrees found."),process.exit(0);let o=await Promise.all(e.map(async(c)=>{let[u,a,l,h]=await Promise.all([c.branch?E.getAheadBehind(c.branch,c.path):Promise.resolve({ahead:0,behind:0}),E.getLastCommit(c.path),E.getDirtyCount(c.path),Promise.resolve(Qt(c.path))]);return{...c,aheadBehind:u,lastCommit:a,dirtyCount:l,focus:h}}));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);let n=On(process.cwd()),r=t.all&&new Set(o.map((c)=>c.repoName)).size>1,i=o.map((c)=>{let a=(On(c.path)===n?"* ":" ")+(c.branch??"(detached)"),l;if(c.isLocked)l="locked";else if(c.dirtyCount>0)l=`${c.dirtyCount} dirty`;else l="clean";let h=[];if(c.aheadBehind.ahead>0)h.push(`+${c.aheadBehind.ahead}`);if(c.aheadBehind.behind>0)h.push(`-${c.aheadBehind.behind}`);let d=h.length>0?h.join(" "):"=",g=c.lastCommit?`${c.lastCommit.relativeDate} ${Ic(c.lastCommit.message,30)}`:"\u2014",x=c.focus&&c.focus.length>0?Ic(c.focus.join(", "),30):"\u2014";return{repo:c.repoName,branch:a,dirty:l,sync:d,lastCommit:g,focus:x}}),s={branch:Math.max(6,...i.map((c)=>c.branch.length)),dirty:Math.max(6,...i.map((c)=>c.dirty.length)),sync:Math.max(4,...i.map((c)=>c.sync.length)),lastCommit:Math.max(11,...i.map((c)=>c.lastCommit.length)),focus:Math.max(5,...i.map((c)=>c.focus.length)),repo:Math.max(4,...i.map((c)=>c.repo.length))};if(r){let c=`${"Repo".padEnd(s.repo)} ${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,u=`${"-".repeat(s.repo)} ${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(u);for(let a of i)console.log(`${a.repo.padEnd(s.repo)} ${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}else{let c=`${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,u=`${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(u);for(let a of i)console.log(`${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}process.exit(0)}catch(e){if(e instanceof Gt)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}};du=pu});var Gc={};xt(Gc,{default:()=>wu});import{existsSync as mu}from"fs";function xu(t){if(t)return t;let e=process.env.VISUAL||process.env.EDITOR;if(e)return e;for(let o of _c)try{if(Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return o}catch{continue}return null}var _c,gu,wu;var Hc=N(()=>{ct();Dt();_c=["code","cursor","vim","nvim","emacs","nano","subl","zed","idea","webstorm"];gu={command:"open [branch-or-path]",describe:"Open a worktree in your editor/IDE",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path (defaults to current worktree)"}).option("editor",{type:"string",alias:"e",describe:"Editor command to use (overrides $VISUAL/$EDITOR)"}).option("list-editors",{type:"boolean",describe:"List detected editors"}),handler:async(t)=>{if(t["list-editors"]){let e=process.env.VISUAL||process.env.EDITOR;if(e)console.log(`$VISUAL/$EDITOR: ${e}`);for(let o of _c)try{let n=Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0){let r=new TextDecoder().decode(n.stdout).trim();console.log(` ${o}: ${r}`)}}catch{}process.exit(0)}try{let e=t["branch-or-path"],o;if(!e)o=process.cwd();else{let i=await at(),s=await E.list(i);o=Vt(s,e).path}if(!mu(o))console.error(`Error: worktree path does not exist: ${o}`),process.exit(1);let n=xu(t.editor);if(!n)console.error("Error: no editor detected."),console.error("Set $VISUAL or $EDITOR, or use --editor <command>."),console.error("Detected editors can be listed with: omw open --list-editors"),process.exit(1);console.log(`Opening ${o} with ${n}...`),await Bun.spawn([n,o],{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited,process.exit(0)}catch(e){wt(e)}}},wu=gu});var Jc={};xt(Jc,{default:()=>Cu});import{resolve as Nc}from"path";var bu,Cu;var zc=N(()=>{ct();$t();Dt();bu={command:"exec <command>",describe:"Run a command in each worktree",builder:(t)=>t.positional("command",{type:"string",describe:"Shell command to execute",demandOption:!0}).option("all",{type:"boolean",alias:"a",describe:"Run across all configured repos"}).option("dirty",{type:"boolean",describe:"Only run in dirty worktrees"}).option("clean",{type:"boolean",describe:"Only run in clean worktrees"}).option("behind",{type:"boolean",describe:"Only run in worktrees behind upstream"}).option("parallel",{type:"boolean",alias:"p",describe:"Run commands in parallel (default: sequential)"}).option("json",{type:"boolean",alias:"j",describe:"Output results as JSON"}),handler:async(t)=>{let e=t.command,o=!!t.parallel,n=!!t.json;try{let r;if(t.all){let a=Y(),l=await at(),h=Be(a),d=new Set([Nc(l)]),g=[l];for(let x of h){let m=Nc(x);if(!d.has(m))d.add(m),g.push(x)}r=await E.listAll(g)}else r=await E.list();let i=r.filter((a)=>!a.isMain);if(t.dirty)i=i.filter((a)=>a.isDirty);if(t.clean)i=i.filter((a)=>!a.isDirty);if(t.behind)i=(await Promise.all(i.map(async(l)=>{if(!l.branch)return{wt:l,behind:!1};let h=await E.getAheadBehind(l.branch,l.path);return{wt:l,behind:h.behind>0}}))).filter((l)=>l.behind).map((l)=>l.wt);if(i.length===0)console.log("No matching worktrees found."),process.exit(0);if(!n)console.log(`Running '${e}' in ${i.length} worktree(s)...
147
+ `);let s=async(a)=>{let l=Bun.spawn(["sh","-c",e],{cwd:a.path,stdout:"pipe",stderr:"pipe",env:{...Bun.env,OMW_BRANCH:a.branch??"",OMW_WORKTREE_PATH:a.path,OMW_REPO_PATH:a.repoPath}}),[h,d,g]=await Promise.all([new Response(l.stdout).text(),new Response(l.stderr).text(),l.exited]);return{branch:a.branch??"(detached)",path:a.path,exitCode:g,stdout:h.trim(),stderr:d.trim()}},c;if(o)c=await Promise.all(i.map(s));else{c=[];for(let a of i)c.push(await s(a))}if(n)console.log(JSON.stringify(c,null,2));else{for(let h of c){let d=h.exitCode===0?"\u2713":"\u2717";if(console.log(`${d} ${h.branch} (exit ${h.exitCode})`),h.stdout)for(let g of h.stdout.split(`
148
+ `))console.log(` ${g}`);if(h.stderr)for(let g of h.stderr.split(`
149
+ `))console.log(` ${g}`);console.log()}let a=c.filter((h)=>h.exitCode===0).length,l=c.length-a;console.log(`Done: ${a} passed, ${l} failed`)}let u=c.some((a)=>a.exitCode!==0);process.exit(u?1:0)}catch(r){wt(r)}}},Cu=bu});var vc={};xt(vc,{default:()=>Su});var $u,Su;var kc=N(()=>{ct();Dt();$u={command:"diff <ref1> [ref2]",describe:"Show diff between two worktrees or branches",builder:(t)=>t.positional("ref1",{type:"string",describe:"First worktree branch or ref",demandOption:!0}).positional("ref2",{type:"string",describe:"Second worktree branch or ref (default: current HEAD)"}).option("stat",{type:"boolean",alias:"s",describe:"Show diffstat summary only"}).option("name-only",{type:"boolean",alias:"n",describe:"Show only names of changed files"}),handler:async(t)=>{let e=t.ref1,o=t.ref2??"HEAD",n=!!t.stat,r=!!t["name-only"];try{let i=await at(),s=await E.list(i),c=(h)=>{return s.find((g)=>g.branch===h)?.branch??h},u=c(e),a=c(o),l=await E.diffBetween(u,a,{stat:n,nameOnly:r},i);if(!l)console.log(`No differences between ${e} and ${o==="HEAD"?"current HEAD":o}`);else console.log(l);process.exit(0)}catch(i){wt(i)}}},Su=$u});var Uc={};xt(Uc,{default:()=>yu});var Pu,yu;var Kc=N(()=>{ct();yo();Dt();Pu={command:"pin [branch]",aliases:["unpin"],describe:"Pin or unpin a worktree",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).option("reason",{type:"string",describe:"Reason for pinning"}).option("list",{type:"boolean",describe:"List pinned worktrees"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("unpin",{type:"boolean",describe:"Unpin instead of pinning"}),handler:async(t)=>{try{let e=t,o=await E.list();if(t.list){let c=Mr(o).map((d)=>({...d,pin:ko(d.path)}));if(t.json)console.log(JSON.stringify(c,null,2)),process.exit(0);if(c.length===0)console.log("No pinned worktrees found."),process.exit(0);let u=Math.max(6,...c.map((d)=>(d.branch??"(detached)").length)),a=Math.max(4,...c.map((d)=>d.path.length)),l=Math.max(6,...c.map((d)=>(d.pin?.reason??"\u2014").length)),h=Math.max(9,...c.map((d)=>(d.pin?.pinnedAt??"\u2014").length));console.log(`${"Branch".padEnd(u)} ${"Path".padEnd(a)} ${"Reason".padEnd(l)} ${"Pinned At".padEnd(h)}`),console.log(`${"-".repeat(u)} ${"-".repeat(a)} ${"-".repeat(l)} ${"-".repeat(h)}`);for(let d of c)console.log(`${(d.branch??"(detached)").padEnd(u)} ${d.path.padEnd(a)} ${(d.pin?.reason??"\u2014").padEnd(l)} ${(d.pin?.pinnedAt??"\u2014").padEnd(h)}`);process.exit(0)}let n=t._[0]==="unpin"||!!t.unpin,r=typeof e.branch==="string"?e.branch:typeof t._[1]==="string"?t._[1]:void 0;if(!r)console.error("Error: branch is required"),process.exit(1);let i=o.find((c)=>c.branch===r);if(!i)console.error(`Error: no worktree found for '${r}'`),process.exit(1);if(n){if(!ko(i.path))console.warn(`Warning: worktree is not pinned: ${i.path}`),process.exit(0);Er(i.path),console.log(`Unpinned worktree: ${i.path}`),process.exit(0)}if(ko(i.path))console.warn(`Warning: worktree is already pinned: ${i.path}`),process.exit(0);let s=typeof e.reason==="string"?e.reason:void 0;Rr(i.path,s),console.log(`Pinned worktree: ${i.path}`),process.exit(0)}catch(e){wt(e)}}},yu=Pu});var Vc={};xt(Vc,{default:()=>Mu});function Ru(t){let e={create:"\x1B[32m",delete:"\x1B[31m",switch:"\x1B[34m",rename:"\x1B[33m",archive:"\x1B[35m",import:"\x1B[36m",reset:"\x1B[0m"};return`${e[t]??e.reset}${t}${e.reset}`}var Eu,Mu;var qc=N(()=>{_e();Dt();Eu={command:"log",aliases:["logs"],describe:"Show worktree activity log",builder:(t)=>t.option("limit",{type:"number",default:20,describe:"Show the last N entries"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("clear",{type:"boolean",describe:"Clear the activity log"}),handler:async(t)=>{try{let e=await at();if(t.clear){if(!await Te("Clear activity log? [y/N] "))console.log("Cancelled."),process.exit(0);sc(e),console.log("Activity log cleared."),process.exit(0)}let o=typeof t.limit==="number"?t.limit:20,n=ic(e,{limit:o});if(t.json)console.log(JSON.stringify(n,null,2)),process.exit(0);for(let r of n){let i=Ru(r.event),s=r.branch??"(unknown)",c=r.details?Object.entries(r.details).map(([u,a])=>`${u}=${a}`).join(" "):"";console.log(`[${r.timestamp}] ${i} ${s}${c?` (${c})`:""}`)}process.exit(0)}catch(e){wt(e)}}},Mu=Eu});import{existsSync as Qc,mkdirSync as Ou,readFileSync as Yc,writeFileSync as Xc}from"fs";import{homedir as Wu}from"os";import{basename as Du,join as Wn}from"path";function Fu(t){let e=_o(t),o=Wn(e,"HEAD");if(!Qc(o))return null;let r=Yc(o,"utf-8").trim().match(/^ref:\s+(.+)$/);if(!r)return null;return r[1]?.replace(/^refs\/heads\//,"")??null}async function Zc(t,e){return E.exec(t,e)}function ta(){let t=Bun.env.HOME??Wu();return Wn(t,".omw","archives")}async function ea(t,e){let o=Du(e),n=await E.getBranchForWorktree(t)??Fu(t)??"detached-head",r=n.replaceAll("/","-"),i=new Date().toISOString(),s=i.replaceAll(":","-"),c=Wn(ta(),o);Ou(c,{recursive:!0});let u=Wn(c,`${r}-${s}`),a=`${u}.patch`,l=`${u}.json`;try{let[h,d,g]=await Promise.all([Zc(["diff"],t),Zc(["format-patch","-5","HEAD","--stdout"],t),E.getLastCommit(t)]),x=["# OMW archive",`# repo: ${o}`,`# branch: ${n}`,`# archivedAt: ${i}`,"","# Uncommitted diff",h||"# (no uncommitted changes)","","# Recent commits (git format-patch -5 HEAD --stdout)",d||"# (no recent commits)"].join(`
150
+ `);Xc(a,x,"utf-8");let m={branch:n,repo:o,archivedAt:i,patchPath:a,commitHash:g?.hash??"",message:g?.message??""};return Xc(l,JSON.stringify(m,null,2),"utf-8"),m}catch(h){let d=h instanceof Error?h.message:"Unknown archive error";throw new hr(`Failed to archive worktree: ${d}`,n,"archive_failed")}}async function oa(t){let e=ta();if(!Qc(e))return[];let o=t?`${t}/*.json`:"**/*.json",n=new Bun.Glob(o),r=[];for await(let i of n.scan({cwd:e,absolute:!0}))try{let s=Yc(i,"utf-8");r.push(JSON.parse(s))}catch{}return r.sort((i,s)=>{let c=Date.parse(i.archivedAt);return Date.parse(s.archivedAt)-c})}var na=N(()=>{ct();Zt();Oe()});var ra={};xt(ra,{default:()=>Au});import{basename as Bu}from"path";var Lu,Au;var ia=N(()=>{ct();_e();na();$t();Ce();Dt();Lu={command:"archive [branch]",describe:"Archive worktree changes and optionally remove",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name or worktree path"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}).option("keep",{type:"boolean",describe:"Archive without removing the worktree"}).option("list",{type:"boolean",describe:"List all archives"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON (with --list)"}),handler:async(t)=>{let e=t.branch,o=!!t.yes,n=!!t.keep,r=!!t.list,i=!!t.json;try{if(r){let h=await oa();if(i)console.log(JSON.stringify(h,null,2));else if(h.length===0)console.log("No archives found.");else{console.log(`Archives:
151
+ `);for(let d of h){let g=new Date(d.archivedAt).toLocaleString();console.log(` ${d.repo}/${d.branch}`),console.log(` Date: ${g}`),console.log(` Commit: ${d.commitHash.slice(0,8)} ${d.message}`),console.log(` Patch: ${d.patchPath}`),console.log()}}process.exit(0)}if(!e)console.error("Error: branch name is required (or use --list to view archives)"),process.exit(1);let s=await at(),c=await E.list(s),u=Vt(c,e);if(u.isMain)console.error("Error: cannot archive the main worktree"),process.exit(1);let a=n?"Archive":"Archive and remove";if(!o){if(!await Te(`${a} worktree '${u.branch??Bu(u.path)}'? [y/N] `))console.log("Cancelled."),process.exit(0)}let l=await ea(u.path,s);console.log(`Archived: ${l.patchPath}`);try{qt(s,{timestamp:new Date().toISOString(),event:"archive",branch:l.branch,path:l.patchPath})}catch{}if(!n){let h=Y(),d=Lt(h,s);if(d.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(d.postRemove,{cwd:u.path,env:{OMW_BRANCH:u.branch??"",OMW_WORKTREE_PATH:u.path,OMW_REPO_PATH:s},onOutput:(g)=>console.log(` ${g}`)}).catch((g)=>console.warn(`Warning: postRemove hook failed: ${g.message}`));await E.remove(u.path,{force:!1},s),Mt(),console.log(`Removed worktree: ${u.path}`)}process.exit(0)}catch(s){wt(s)}}},Au=Lu});var sa={};xt(sa,{default:()=>Gu});import{dirname as Iu,basename as ju,join as Tu}from"path";var _u,Gu;var ca=N(()=>{ct();_e();Dt();_u={command:"rename <old> <new>",describe:"Rename worktree branch",builder:(t)=>t.positional("old",{type:"string",demandOption:!0,describe:"Current branch name"}).positional("new",{type:"string",demandOption:!0,describe:"New branch name"}).option("move-path",{type:"boolean",describe:"Also rename the worktree directory path"}),handler:async(t)=>{let{old:e,new:o}=t,n=!!t["move-path"];try{let r=await at(),i=await E.list(r),s=Vt(i,e);if(s.isMain)console.error("Error: cannot rename the main worktree branch"),process.exit(1);if(i.find((u)=>u.branch===o))console.error(`Error: branch '${o}' already exists`),process.exit(1);if(await E.exec(["branch","-m",e,o],r),Mt(),n){let u=o.replace(/\//g,"-"),a=Iu(s.path),l=ju(s.path),h=e.replace(/\//g,"-"),d=l.replace(h,u),g=Tu(a,d);if(g!==s.path)await E.move(s.path,g,r),Mt(),console.log(`Moved worktree: ${s.path} \u2192 ${g}`)}console.log(`Renamed branch: ${e} \u2192 ${o}`);try{qt(r,{timestamp:new Date().toISOString(),event:"rename",branch:o,details:{oldBranch:e}})}catch{}process.exit(0)}catch(r){wt(r)}}},Gu=_u});var aa={};xt(aa,{default:()=>zu});import{basename as Hu,resolve as Nu}from"path";var Ju,zu;var fa=N(()=>{ct();Zt();$t();Ce();Ju={command:"clone <url> [path]",describe:"Clone a repository and initialize omw config",builder:(t)=>t.positional("url",{type:"string",describe:"Repository URL to clone",demandOption:!0}).positional("path",{type:"string",describe:"Target directory path"}).option("template",{type:"string",alias:"t",describe:"Apply a named template after cloning"}).option("init-config",{type:"boolean",describe:"Initialize omw config after cloning",default:!0}),handler:async(t)=>{let{url:e,template:o}=t,n=t["init-config"],r=t.path;if(!r)try{let i=new URL(e);r=Hu(i.pathname).replace(/\.git$/,"")}catch{r=(e.split("/").pop()??e.split(":").pop()??e).replace(/\.git$/,"")}if(!r)console.error("Error: could not determine target directory from URL"),process.exit(1);console.log(`Cloning ${e}...`);try{await E.exec(["clone",e,r])}catch(i){if(i instanceof Gt)console.error(`Error: ${i.stderr||i.message}`);else console.error(`Error: ${i.message}`);process.exit(1)}if(n)try{let i=ae();console.log(` \u2713 Config initialized: ${i}`)}catch(i){console.warn(` \u26A0 Could not initialize config: ${i.message}`)}if(o)try{let i=Y(),s=bn(i,o);if(!s){let l=Object.keys(i.templates??{});if(console.error(`Error: template '${o}' not found.`),l.length>0)console.error(`Available templates: ${l.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}console.log(` Using template '${o}'`);let c=Nu(r),u=Lt(i,c),a=Cn(u,s);if(a.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(a.postCreate,{cwd:c,env:{OMW_REPO_PATH:c},onOutput:(l)=>console.log(` ${l}`)}),console.log(" \u2713 Hooks completed");console.log(` \u2713 Template '${o}' applied`)}catch(i){if(i instanceof $o)console.error(`Error: hook timed out: ${i.command}`);else if(i instanceof Co){if(console.error(`Error: hook failed (exit ${i.exitCode}): ${i.command}`),i.stderr)console.error(i.stderr)}else console.error(`Error applying template: ${i.message}`);process.exit(1)}console.log(`
152
+ Cloned: ${e} \u2192 ${r}`),process.exit(0)}},zu=Ju});import{existsSync as la,readFileSync as ha,statSync as Dn}from"fs";import{basename as vu,join as Fn,resolve as Ro}from"path";async function Fr(t,e){return E.exec(t,e)}function ku(t){let e=Fn(t,"HEAD");if(!la(e))return null;let n=ha(e,"utf-8").trim().match(/^ref:\s+refs\/heads\/(.+)$/);return n?n[1]:null}function ua(t){let e=Ro(t),o=Fn(e,".git");if(!Dn(o,{throwIfNoEntry:!1}))throw Error(`Missing .git at ${o}`);return _o(e)}function Br(t){let e=Ro(t),o=Dn(e,{throwIfNoEntry:!1});if(!o)return{valid:!1,reason:`Path does not exist: ${e}`};if(!o.isDirectory())return{valid:!1,reason:`Path is not a directory: ${e}`};let n=Fn(e,".git"),r=Dn(n,{throwIfNoEntry:!1});if(!r)return{valid:!1,reason:`Target is missing .git: ${e}`};if(r.isDirectory())return{valid:!1,reason:`Target is not a linked git worktree (.git is a directory): ${e}`};if(!r.isFile())return{valid:!1,reason:`Target has invalid .git entry: ${e}`};let i="";try{i=ua(e)}catch{return{valid:!1,reason:`Cannot resolve gitdir from .git file: ${e}`}}if(!Dn(i,{throwIfNoEntry:!1})?.isDirectory())return{valid:!1,reason:`Resolved gitdir does not exist: ${i}`};let c=ku(i);if(!c)return{valid:!1,reason:`Cannot resolve branch name from HEAD: ${e}`};return{valid:!0,branch:c}}async function pa(t,e){let o=Ro(t),n=Br(o);if(!n.valid)throw new jo(`Cannot import worktree: ${n.reason??"invalid target"}`,o,n.reason??"invalid target");let[r,i,s]=await Promise.all([Fr(["rev-parse","HEAD"],o),Fr(["status","--porcelain"],o),Fr(["rev-parse","--git-common-dir"],o)]),c=Ro(o,s),u=c.endsWith("/.git")||c.endsWith("\\.git")?c.slice(0,-5):c,a=vu(u),l=Ro(o)===Ro(u),h=ua(o),d=Fn(h,"locked"),g=la(d),x=g?ha(d,"utf-8").trim()||void 0:void 0;if(e?.focus&&e.focus.length>0)uo(o,e.focus);if(e?.pin)try{(await Promise.resolve().then(() => (yo(),vs))).writePin(o)}catch(m){console.warn(`Warning: failed to pin worktree: ${m.message}`)}return{path:o,branch:n.branch??null,head:r,isMain:l,isDirty:i.length>0,isLocked:g,lockReason:x,repoName:a,repoPath:u}}var da=N(()=>{ct();me();Zt();Oe()});var ma={};xt(ma,{default:()=>Vu});import{resolve as Uu}from"path";var Ku,Vu;var xa=N(()=>{da();ct();_e();Zt();Dt();Ku={command:"import <path>",describe:"Adopt a worktree with omw metadata",builder:(t)=>t.positional("path",{type:"string",describe:"Existing worktree directory path",demandOption:!0}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("pin",{type:"boolean",describe:"Pin the worktree"}),handler:async(t)=>{let e=Uu(t.path),o=Br(e);if(!o.valid)console.error(`Error: ${o.reason??"invalid import target"}`),process.exit(1);let r=t.focus?.flatMap((s)=>s.split(/[,\s]+/)).map((s)=>s.trim()).filter(Boolean)??[],i=!!t.pin;try{let s=await pa(e,{focus:r,pin:i});Mt();let c=s.branch??o.branch??"unknown",u=s.repoPath??await at();console.log(`Imported worktree: ${c} at ${s.path}`);try{qt(u,{timestamp:new Date().toISOString(),event:"import",branch:s.branch??o.branch??"unknown",path:s.path})}catch{}if(r.length>0)console.log(` Focus: ${r.join(", ")}`);if(i)console.log(" Pinned");process.exit(0)}catch(s){if(s instanceof jo)console.error(`Error: ${s.reason}`);else console.error(`Error: ${s.message}`);process.exit(1)}}},Vu=Ku});var ga={};xt(ga,{default:()=>Qu});import{basename as Bn}from"path";async function Xu(t,e,o){let[n,r]=await Promise.all([wr(e),E.list(t)]);if(o){let i=n.map((s)=>{let c=r.find((a)=>{let l=a.branch??Bn(a.path);return We(l,e)===s.name}),u=c?Kt(c.path):null;return{...s,branch:c?.branch??null,worktreePath:c?.path??null,layout:u?.layout??null}});console.log(JSON.stringify(i,null,2));return}if(n.length===0){console.log("No active omw sessions.");return}console.log(`Active sessions (${n.length}):
153
+ `);for(let i of n){let s=r.find((h)=>{let d=h.branch??Bn(h.path);return We(d,e)===i.name}),c=s?Kt(s.path):null,u=i.attached?" (attached)":"",a=c?.layout?` [${c.layout}]`:"",l=s?.branch?` ${s.branch}`:"";console.log(` ${i.name}${l} ${i.windows} windows${a}${u}`)}}async function Zu(t,e){let[o,n]=await Promise.all([wr(e),E.list(t)]);if(o.length===0){console.log("No active omw sessions.");return}let r=0;for(let i of o){let s=n.find((c)=>{let u=Kt(c.path),a=c.branch??Bn(c.path);return u?.name===i.name||We(a,e)===i.name});if(await gr(i.name),s)mr(s.path);r++,console.log(` \u2713 Killed ${i.name}`)}console.log(`
154
+ Killed ${r} session${r!==1?"s":""}.`)}var qu,Qu;var wa=N(()=>{ct();$t();De();Dt();qu={command:"session [branch-or-path]",aliases:["ss"],describe:"Manage tmux sessions for worktrees",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path to open session for"}).option("list",{type:"boolean",alias:"l",describe:"List active omw tmux sessions"}).option("kill",{type:"boolean",alias:"k",describe:"Kill the session for the specified worktree"}).option("kill-all",{type:"boolean",describe:"Kill all omw tmux sessions"}).option("layout",{type:"string",describe:"Use a named layout from config"}).option("json",{type:"boolean",alias:"j",describe:"Output in JSON format"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.list,n=!!t.kill,r=!!t["kill-all"],i=t.layout,s=!!t.json;if(!await mo())console.error("Error: tmux is not installed or not in PATH."),console.error("Install tmux to use session management."),process.exit(1);try{let c=await at(),u=Y(),a=Le(u);if(o)await Xu(c,a.prefix,s),process.exit(0);if(r)await Zu(c,a.prefix),process.exit(0);if(!e)console.error("Error: specify a branch or worktree path, or use --list."),process.exit(1);let l=await E.list(c),h=Vt(l,e),d=h.branch??Bn(h.path);if(n){if(await mn(d,h.path,a.prefix))console.log(`Killed session for '${d}'`);else console.log(`No active session for '${d}'`);process.exit(0)}let g=$n(u,i),x=await dn(d,h.path,{layout:g,prefix:a.prefix,attach:!0,layoutName:i??a.defaultLayout});console.log(`Session: ${x}`),process.exit(0)}catch(c){wt(c)}}};Qu=qu});import{existsSync as Lr,mkdirSync as ba,writeFileSync as Ca}from"fs";import{dirname as $a,join as Eo}from"path";function Yu(t){let e=process.env.HOME||process.env.USERPROFILE||"~";switch(t){case"claude-code":return Eo(e,".claude","skills","omw");case"codex":return Eo(e,".agents","skills","omw");case"opencode":return Eo(e,".config","opencode","skill","omw")}}function tp(t){return Eo(Yu(t),"SKILL.md")}function np(t){return["| Flag | Type | Alias | Description |","|------|------|-------|-------------|",...t.length>0?t.map((o)=>`| ${o.flag} | ${o.type} | ${o.alias} | ${o.description} |`):["| - | - | - | No options |"]].join(`
155
+ `)}function rp(){let t=op.map((o)=>`| \`${o.command}\` | ${o.aliases} | ${o.description} |`),e=Sa.map((o)=>`- [\`omw ${o.command}\`](references/${o.command}.md)`);return["---","name: omw",`description: ${ep}`,"metadata:"," author: getsolaris",' version: "1.0.0"',"---","","# oh-my-worktree (omw)","","## Quick Start","","### Create a feature worktree","","```bash","omw add feature/my-feature --base main","```","","### List and check status","","```bash","omw list","omw status","```","","### Clean up merged worktrees","","```bash","omw clean --dry-run","omw clean --yes","```","","### Run commands across worktrees","","```bash",'omw exec "bun test" --parallel',"```","","### Review a GitHub PR","","```bash","omw add pr-review --pr 42","omw open pr-review","```","","### Use templates","","```bash","# Create worktree with predefined template (hooks, base branch, settings)","omw add feature/new --template frontend","```","","### Tmux session management","","```bash","# Create worktree with tmux session","omw add feature/api --session --layout dev","","# List active sessions","omw session --list","","# Attach to existing session","omw session feature/api","```","","### Shell integration setup","","```bash","# Add to ~/.zshrc or ~/.bashrc",'eval "$(omw shell-init)"',"","# Then switch worktrees with cd","omw switch feature/auth","```","","## Command Overview","","| Command | Aliases | Description |","|---------|---------|-------------|",...t,"","## Monorepo Workflows","","Use focus paths to target packages and trigger matching monorepo hooks.","","```bash","omw add feature/web-auth --focus apps/web,apps/api","omw import /path/to/worktree --focus packages/core --pin","omw list --json","```","","Focus accepts comma-separated values, space-separated values, or repeated --focus flags.","","## Configuration","","- Config path: `~/.config/oh-my-worktree/config.json`","- Use `--json` output flags for scripting and automation","- Environment variables in `omw exec`: `OMW_BRANCH`, `OMW_WORKTREE_PATH`, `OMW_REPO_PATH`","","## Command Reference","","For detailed options and examples for each command:","",...e,"- [`Configuration Schema`](references/config-schema.md)",""].join(`
156
+ `)}function ip(){let t=new Map;for(let o of Sa){let n=[`# omw ${o.command}`,"",o.summary,"","## Synopsis","","```",o.synopsis,"```","","## Options","",np(o.options),"","## Examples","","```bash",`# ${o.examples[0][0]}`,o.examples[0][1],"",`# ${o.examples[1][0]}`,o.examples[1][1],"```","","## Notes","",...o.notes.map((r)=>`- ${r}`),"",...o.configKeys.length>0?["## Configuration","","Related config keys in `~/.config/oh-my-worktree/config.json`:","",...o.configKeys.map((r)=>`- ${r}`),""]:[]];t.set(`${o.command}.md`,n.join(`
157
+ `))}let e=sp();return t.set("config-schema.md",e),t}function sp(){return["# Configuration Schema","","Config file path: `~/.config/oh-my-worktree/config.json`","","## Minimal Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env", ".env.local"],',' "linkFiles": ["node_modules"],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true'," }","}","```","","## Full Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env"],',' "linkFiles": [],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true,',' "sharedDeps": {',' "strategy": "symlink",',' "paths": ["node_modules"]'," }"," },",' "repos": ['," {",' "path": "/path/to/repo",',' "copyFiles": [".env", ".env.local"],',' "monorepo": {',' "autoDetect": true,',' "hooks": ['," {",' "glob": "apps/*",',' "postCreate": ["bun install"]'," }"," ]"," }"," }"," ],",' "templates": {',' "frontend": {',' "base": "main",',' "copyFiles": [".env"],',' "postCreate": ["bun install", "bun run build"]'," },",' "review": {',' "base": "main",',' "postCreate": ["bun install"]'," }"," },",' "sessions": {',' "enabled": true,',' "autoCreate": false,',' "autoKill": true,',' "prefix": "omw",',' "defaultLayout": "dev",',' "layouts": {',' "dev": {',' "windows": [',' { "name": "editor", "command": "nvim ." },',' { "name": "server", "command": "bun run dev" },',' { "name": "shell" }'," ]"," }"," }"," },",' "lifecycle": {',' "autoCleanMerged": false,',' "staleAfterDays": 30,',' "maxWorktrees": 10'," },",' "theme": "default"',"}","```","","## Key Reference","","### defaults","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `worktreeDir` | string | `~/.omw/worktrees/{repo}-{branch}` | Directory pattern. Supports `{repo}` and `{branch}` variables |","| `copyFiles` | string[] | `[]` | Files to copy from main worktree on creation |","| `linkFiles` | string[] | `[]` | Files to symlink from main worktree on creation |","| `postCreate` | string[] | `[]` | Shell commands to run after worktree creation |","| `postRemove` | string[] | `[]` | Shell commands to run before worktree removal |","| `autoUpstream` | boolean | `false` | Automatically set upstream tracking branch |","| `sharedDeps.strategy` | string | `symlink` | Strategy for sharing deps: `symlink`, `hardlink`, or `copy` |","| `sharedDeps.paths` | string[] | `[]` | Paths to share between worktrees |","","### repos[]","","Per-repository overrides. Same keys as `defaults` plus:","","| Key | Type | Description |","|-----|------|-------------|","| `path` | string | **Required.** Absolute path to the repository |","| `monorepo.autoDetect` | boolean | Auto-detect monorepo tools (pnpm, turbo, nx, lerna) |","| `monorepo.extraPatterns` | string[] | Additional glob patterns for package discovery |","| `monorepo.hooks[]` | object[] | Per-package hooks matched by glob pattern |","| `monorepo.hooks[].glob` | string | Glob to match against focus paths |","| `monorepo.hooks[].copyFiles` | string[] | Package-level files to copy |","| `monorepo.hooks[].linkFiles` | string[] | Package-level files to symlink |","| `monorepo.hooks[].postCreate` | string[] | Package-level post-create hooks |","| `monorepo.hooks[].postRemove` | string[] | Package-level post-remove hooks |","","### templates","","Named presets applied via `omw add --template <name>` or `omw clone --template <name>`.","","| Key | Type | Description |","|-----|------|-------------|","| `base` | string | Default base branch for new worktrees |","| `worktreeDir` | string | Override directory pattern |","| `copyFiles` | string[] | Override files to copy |","| `linkFiles` | string[] | Override files to symlink |","| `postCreate` | string[] | Override post-create hooks |","| `postRemove` | string[] | Override post-remove hooks |","| `autoUpstream` | boolean | Override upstream tracking |","","### sessions","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `enabled` | boolean | `false` | Enable tmux session integration |","| `autoCreate` | boolean | `false` | Auto-create session on `omw add` |","| `autoKill` | boolean | `false` | Auto-kill session on `omw remove` |","| `prefix` | string | `omw` | Prefix for tmux session names |","| `defaultLayout` | string | - | Default layout name |","| `layouts.<name>.windows[]` | object[] | - | Window definitions |","| `layouts.<name>.windows[].name` | string | **Required.** | Window name |","| `layouts.<name>.windows[].command` | string | - | Command to run in window |","","### lifecycle","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `autoCleanMerged` | boolean | `false` | Auto-clean merged worktrees |","| `staleAfterDays` | number | `30` | Days until a worktree is considered stale |","| `maxWorktrees` | number | `10` | Maximum number of worktrees |",""].join(`
158
+ `)}function Pa(t){let e=tp(t),o=Eo($a(e),"references"),n=rp(),r=ip(),i=$a(e);if(!Lr(i))ba(i,{recursive:!0});if(!Lr(o))ba(o,{recursive:!0});let s=Lr(e);Ca(e,n,"utf-8");for(let[c,u]of r.entries())Ca(Eo(o,c),u,"utf-8");return{filePath:e,referenceDir:o,referenceCount:r.size,platform:t,action:s?"updated":"created"}}var Ar,ep="Git worktree manager. Use when working with git worktrees \u2014 creating, switching, removing, listing, or managing worktrees across repositories. Also use for monorepo focus, tmux sessions, and worktree health checks.",op,Sa;var ya=N(()=>{Ar=["claude-code","codex","opencode"];op=[{command:"add",aliases:"-",description:"Create a new worktree from a branch, template, or PR."},{command:"remove",aliases:"rm",description:"Remove a worktree by branch or path."},{command:"list",aliases:"ls",description:"List worktrees with branch, path, status, and focus."},{command:"switch",aliases:"sw",description:"Print shell cd command for a target worktree."},{command:"status",aliases:"st",description:"Show status summary for worktrees."},{command:"clean",aliases:"-",description:"Clean merged worktrees and optionally report stale ones."},{command:"doctor",aliases:"-",description:"Run worktree health checks and optional auto-fixes."},{command:"exec",aliases:"-",description:"Run commands across non-main worktrees."},{command:"diff",aliases:"-",description:"Compare two refs or worktree branches."},{command:"pin",aliases:"unpin",description:"Pin or unpin worktrees and inspect pin metadata."},{command:"log",aliases:"logs",description:"Read or clear the activity log."},{command:"archive",aliases:"-",description:"Archive worktree changes as patch files."},{command:"rename",aliases:"-",description:"Rename a worktree branch and optionally move its path."},{command:"clone",aliases:"-",description:"Clone a repository and initialize omw setup."},{command:"import",aliases:"-",description:"Import an existing worktree into omw metadata."},{command:"session",aliases:"ss",description:"Manage tmux sessions for worktrees."},{command:"config",aliases:"-",description:"Initialize, inspect, validate, and manage config profiles."},{command:"open",aliases:"-",description:"Open a worktree path in your preferred editor."},{command:"shell-init",aliases:"-",description:"Generate shell integration and completions."},{command:"init",aliases:"-",description:"Initialize config or install/update omw AI agent skill files."}],Sa=[{command:"add",summary:"Create a new worktree from a branch, template, or GitHub PR.",synopsis:"omw add [branch] [path]",options:[{flag:"--create",type:"boolean",alias:"-c",description:"Optional compatibility flag; missing branches are created automatically"},{flag:"--base",type:"string",alias:"-b",description:"Base branch/commit for new branch"},{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--template",type:"string",alias:"-t",description:"Use a named template from config"},{flag:"--pr",type:"number",alias:"-",description:"Create worktree from a GitHub PR number"},{flag:"--session",type:"boolean",alias:"-s",description:"Create a tmux session for this worktree"},{flag:"--layout",type:"string",alias:"-",description:"Session layout name from config"}],examples:[["Create a feature branch worktree","omw add feature/auth --base main"],["Create from PR with session layout","omw add feature/review --pr 123 --session --layout dev"]],notes:["Creates the branch automatically when it does not already exist.","Existing branches are reused as-is; --base only applies when a new branch is created.","Runs copyFiles, linkFiles, sharedDeps, postCreate hooks, monorepo hooks after creation.","Rolls back on hook failure.","Requires gh CLI for --pr.","Supports comma/space separated focus paths."],configKeys:["`defaults.worktreeDir` \u2014 Directory pattern for new worktrees","`defaults.copyFiles` \u2014 Files to copy from main worktree","`defaults.linkFiles` \u2014 Files to symlink from main worktree","`defaults.sharedDeps` \u2014 Shared dependency strategy and paths","`defaults.postCreate` \u2014 Hooks to run after worktree creation","`defaults.autoUpstream` \u2014 Auto-set upstream tracking branch","`templates.*` \u2014 Named template overrides","`sessions.autoCreate` \u2014 Auto-create tmux session on add","`sessions.layouts` \u2014 Tmux session layout definitions"]},{command:"remove",summary:"Remove a worktree by branch name or path.",synopsis:"omw remove <branch-or-path>",options:[{flag:"--force",type:"boolean",alias:"-f",description:"Force removal even with uncommitted changes"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"}],examples:[["Remove a branch worktree","omw remove feature/auth"],["Force remove without prompt","omw remove feature/auth --force --yes"]],notes:["Runs postRemove hooks and monorepo postRemove hooks before removal.","Cannot remove main worktree.","Cannot remove locked worktrees.","Auto-kills tmux session if sessions.autoKill is enabled."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal","`sessions.autoKill` \u2014 Auto-kill tmux session on remove"]},{command:"list",summary:"List worktrees with branch, path, status, and focus details.",synopsis:"omw list",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--porcelain",type:"boolean",alias:"-p",description:"Machine-readable output"},{flag:"--all",type:"boolean",alias:"-a",description:"List worktrees from all configured repos"}],examples:[["Show all worktrees","omw list"],["Get machine-readable output","omw list --porcelain"]],notes:["Shows branch, path, status (clean/dirty/locked), focus paths.","Focus column truncated to 40 chars."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"switch",summary:"Switch shell context to a worktree by branch or path.",synopsis:"omw switch <branch-or-path>",options:[],examples:[["Switch using branch name","omw switch feature/auth"],["Switch using path","omw switch ~/.omw/worktrees/repo-feature-auth"]],notes:["Outputs cd command for shell eval.","Requires shell integration (omw shell-init).","Auto-switches tmux session if sessions.enabled and inside tmux.","Logs switch activity."],configKeys:["`sessions.enabled` \u2014 Enable tmux session switching","`sessions.prefix` \u2014 Tmux session name prefix"]},{command:"status",summary:"Show branch health, sync state, commit info, and focus.",synopsis:"omw status",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--all",type:"boolean",alias:"-a",description:"Show worktrees from all configured repos"}],examples:[["Print status table","omw status"],["Parse status in scripts","omw status --json"]],notes:["Shows branch, dirty count, sync status (ahead/behind), last commit info, focus paths.","Marks current worktree with *."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"clean",summary:"Remove merged worktrees and optionally inspect stale candidates.",synopsis:"omw clean",options:[{flag:"--dry-run",type:"boolean",alias:"-n",description:"Show what would be removed"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation"},{flag:"--stale",type:"boolean",alias:"-",description:"Also show stale worktrees based on lifecycle config"}],examples:[["Preview merged cleanup","omw clean --dry-run"],["Run cleanup without prompts","omw clean --yes"]],notes:["Only removes merged worktrees.","Skips pinned and dirty worktrees.","Runs git worktree prune after cleanup.","--stale uses lifecycle config (staleAfterDays, maxWorktrees)."],configKeys:["`lifecycle.staleAfterDays` \u2014 Days until a worktree is considered stale","`lifecycle.maxWorktrees` \u2014 Maximum allowed worktrees","`lifecycle.autoCleanMerged` \u2014 Auto-clean merged worktrees"]},{command:"doctor",summary:"Run health checks for worktree state and configuration.",synopsis:"omw doctor",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--fix",type:"boolean",alias:"-",description:"Auto-fix issues"}],examples:[["Run health checks","omw doctor"],["Auto-fix detectable issues","omw doctor --fix"]],notes:["Checks: git version (>=2.17), config validity, stale worktrees, orphaned directories, lock status, dirty worktrees.","Auto-fix: prune stale, remove orphans, unlock stale locks.","Exit code 0 if healthy, 1 if warnings/errors."],configKeys:[]},{command:"exec",summary:"Run a shell command across filtered non-main worktrees.",synopsis:"omw exec <command>",options:[{flag:"--all",type:"boolean",alias:"-a",description:"Run across all configured repos"},{flag:"--dirty",type:"boolean",alias:"-",description:"Only run in dirty worktrees"},{flag:"--clean",type:"boolean",alias:"-",description:"Only run in clean worktrees"},{flag:"--behind",type:"boolean",alias:"-",description:"Only run in worktrees behind upstream"},{flag:"--parallel",type:"boolean",alias:"-p",description:"Run commands in parallel"},{flag:"--json",type:"boolean",alias:"-j",description:"Output results as JSON"}],examples:[["Run tests in parallel",'omw exec "bun test" --parallel'],["Pull only behind worktrees",'omw exec "git pull" --behind']],notes:["Runs in non-main worktrees only.","Sets env vars: OMW_BRANCH, OMW_WORKTREE_PATH, OMW_REPO_PATH.","Exit code 1 if any command fails."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"diff",summary:"Diff two refs or worktree branches.",synopsis:"omw diff <ref1> [ref2]",options:[{flag:"--stat",type:"boolean",alias:"-s",description:"Show diffstat summary only"},{flag:"--name-only",type:"boolean",alias:"-n",description:"Show only names of changed files"}],examples:[["Show diffstat only","omw diff feature/a feature/b --stat"],["List changed file names","omw diff feature/a --name-only"]],notes:["ref2 defaults to HEAD.","Resolves worktree branch names to refs automatically."],configKeys:[]},{command:"pin",summary:"Pin or unpin worktrees and inspect pin metadata.",synopsis:"omw pin [branch]",options:[{flag:"--reason",type:"string",alias:"-",description:"Reason for pinning"},{flag:"--list",type:"boolean",alias:"-",description:"List pinned worktrees"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--unpin",type:"boolean",alias:"-",description:"Unpin instead of pinning"}],examples:[["Pin with a reason",'omw pin feature/auth --reason "active sprint"'],["Unpin a branch","omw pin feature/auth --unpin"]],notes:["Pinned worktrees are excluded from omw clean.","Also invokable as omw unpin <branch>.","Pin metadata stored in git internals."],configKeys:[]},{command:"log",summary:"View or clear activity log events.",synopsis:"omw log",options:[{flag:"--limit",type:"number",alias:"-",description:"default 20, Show the last N entries"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--clear",type:"boolean",alias:"-",description:"Clear the activity log"}],examples:[["Show recent entries","omw log --limit 50"],["Clear the log","omw log --clear"]],notes:["Events: create (green), delete (red), switch (blue), rename (yellow), archive (magenta), import (cyan).","Color-coded in terminal."],configKeys:[]},{command:"archive",summary:"Archive worktree changes as patch files before optional removal.",synopsis:"omw archive [branch]",options:[{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"},{flag:"--keep",type:"boolean",alias:"-",description:"Archive without removing the worktree"},{flag:"--list",type:"boolean",alias:"-",description:"List all archives"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON with --list"}],examples:[["Archive and remove","omw archive feature/done --yes"],["List archive records","omw archive --list --json"]],notes:["Archives stored as patch files in ~/.omw/archives/.","Cannot archive main worktree.","Runs postRemove hooks before removal unless --keep."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal"]},{command:"rename",summary:"Rename a worktree branch and optionally move its directory path.",synopsis:"omw rename <old> <new>",options:[{flag:"--move-path",type:"boolean",alias:"-",description:"Also rename the worktree directory path"}],examples:[["Rename a worktree branch","omw rename feature/old feature/new"],["Rename branch and directory","omw rename feature/old feature/new --move-path"]],notes:["Cannot rename main worktree.","Checks for branch name conflicts.","Logs rename activity.","--move-path replaces old branch slug with new one in directory name."],configKeys:[]},{command:"clone",summary:"Clone a repository and optionally apply omw template setup.",synopsis:"omw clone <url> [path]",options:[{flag:"--template",type:"string",alias:"-t",description:"Apply a named template after cloning"},{flag:"--init-config",type:"boolean",alias:"-",description:"default true, Initialize omw config after cloning"}],examples:[["Clone and initialize","omw clone https://github.com/user/repo.git"],["Clone with template and no config init","omw clone https://github.com/user/repo.git --template review --no-init-config"]],notes:["Auto-detects target path from URL.","Runs template postCreate hooks if template specified.","Use --no-init-config to skip config initialization."],configKeys:["`templates.*` \u2014 Named template overrides"]},{command:"import",summary:"Import an existing git worktree into omw metadata.",synopsis:"omw import <path>",options:[{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--pin",type:"boolean",alias:"-",description:"Pin the worktree"}],examples:[["Import a worktree path","omw import /path/to/worktree"],["Import with focus and pin","omw import /path/to/worktree --focus apps/web,apps/api --pin"]],notes:["Validates that path is a valid git worktree.","Logs import activity.","Supports comma/space separated focus paths."],configKeys:[]},{command:"session",summary:"Manage tmux sessions for worktrees.",synopsis:"omw session [branch-or-path]",options:[{flag:"--list",type:"boolean",alias:"-l",description:"List active omw tmux sessions"},{flag:"--kill",type:"boolean",alias:"-k",description:"Kill the session for the specified worktree"},{flag:"--kill-all",type:"boolean",alias:"-",description:"Kill all omw tmux sessions"},{flag:"--layout",type:"string",alias:"-",description:"Use a named layout from config"},{flag:"--json",type:"boolean",alias:"-j",description:"Output in JSON format"}],examples:[["Attach or create a session","omw session feature/auth"],["List sessions as JSON","omw session --list --json"]],notes:["Requires tmux.","Session naming: branch feat/auth-token \u2192 tmux session omw_feat-auth-token.","Supports layout templates with multiple windows."],configKeys:["`sessions.enabled` \u2014 Enable tmux session integration","`sessions.autoCreate` \u2014 Auto-create session on worktree add","`sessions.autoKill` \u2014 Auto-kill session on worktree remove","`sessions.prefix` \u2014 Tmux session name prefix","`sessions.defaultLayout` \u2014 Default layout name","`sessions.layouts` \u2014 Layout definitions with windows"]},{command:"config",summary:"Initialize, inspect, edit, validate, and manage profiles.",synopsis:"omw config",options:[{flag:"--init",type:"boolean",alias:"-",description:"Create default config file"},{flag:"--show",type:"boolean",alias:"-s",description:"Print current config as JSON"},{flag:"--edit",type:"boolean",alias:"-e",description:"Open config in $EDITOR"},{flag:"--path",type:"boolean",alias:"-",description:"Print config file path"},{flag:"--validate",type:"boolean",alias:"-",description:"Validate config against schema"},{flag:"--profiles",type:"boolean",alias:"-",description:"List config profiles"},{flag:"--profile",type:"string",alias:"-",description:"Profile name for activation/deletion"},{flag:"--activate",type:"boolean",alias:"-",description:"Activate the specified profile"},{flag:"--delete",type:"boolean",alias:"-",description:"Delete the specified profile"}],examples:[["Initialize config","omw config --init"],["Activate a profile","omw config --profile work --activate"]],notes:["Config path: ~/.config/oh-my-worktree/config.json.","XDG-compliant."],configKeys:[]},{command:"open",summary:"Open the target or current worktree in an editor.",synopsis:"omw open [branch-or-path]",options:[{flag:"--editor",type:"string",alias:"-e",description:"Editor command to use"},{flag:"--list-editors",type:"boolean",alias:"-",description:"List detected editors"}],examples:[["Open current worktree","omw open"],["Open with specific editor","omw open feature/auth --editor nvim"]],notes:["Auto-detects editors: code, cursor, vim, nvim, emacs, nano, subl, zed, idea, webstorm.","Uses $VISUAL or $EDITOR env vars.","Defaults to current worktree if no branch specified."],configKeys:[]},{command:"shell-init",summary:"Generate shell integration wrappers and completions.",synopsis:"omw shell-init [shell]",options:[{flag:"--completions",type:"string",alias:"-",description:"Generate shell completions: bash, zsh, fish"}],examples:[["Generate shell wrapper","omw shell-init zsh"],["Generate completion script","omw shell-init --completions fish"]],notes:["Shell arg is auto-detected if omitted.","Generates wrapper function for omw switch to work with shell cd.","Supports bash, zsh, fish."],configKeys:[]},{command:"init",summary:"Initialize omw config or install AI agent skill files.",synopsis:"omw init",options:[{flag:"--skill",type:"string",alias:"-s",description:"Install AI agent skill: claude-code, codex, opencode"}],examples:[["Initialize config","omw init"],["Install Claude Code skill","omw init --skill claude-code"],["Install Codex skill","omw init --skill codex"]],notes:["Without --skill, reuses config initialization and creates only config.json.","With --skill, installs or updates SKILL.md + references/ directory.","Idempotent \u2014 running again updates existing files without breaking existing setup."],configKeys:[]}]});var Ra={};xt(Ra,{default:()=>fp});import{dirname as cp}from"path";var ap,fp;var Ea=N(()=>{$t();ya();ap={command:"init",describe:"Initialize config or install omw integrations",builder:(t)=>t.option("skill",{type:"string",alias:"s",describe:`Install AI agent skill (${Ar.join(", ")})`,choices:Ar}),handler:async(t)=>{let e=t.skill;try{if(!e){let r=ae();console.log(`\u2713 Initialized config \u2192 ${r}`),process.exit(0)}let o=Pa(e),n=o.action==="created"?"Installed":"Updated";console.log(`\u2713 ${n} \u2192 ${cp(o.filePath)}/`),console.log(" SKILL.md"),console.log(` references/ (${o.referenceCount} commands)`),process.exit(0)}catch(o){console.error(`Error: ${o.message}`),process.exit(1)}}},fp=ap});import"@opentui/solid/preload";import{notStrictEqual as Za,strictEqual as Qa}from"assert";var Da={right:La,center:Aa};class jr{constructor(t){var e;this.width=t.width,this.wrap=(e=t.wrap)!==null&&e!==void 0?e:!0,this.rows=[]}span(...t){let e=this.div(...t);e.span=!0}resetOutput(){this.rows=[]}div(...t){if(t.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...t)&&typeof t[0]==="string")return this.applyLayoutDSL(t[0]);let e=t.map((o)=>{if(typeof o==="string")return this.colFromString(o);return o});return this.rows.push(e),e}shouldApplyLayoutDSL(...t){return t.length===1&&typeof t[0]==="string"&&/[\t\n]/.test(t[0])}applyLayoutDSL(t){let e=t.split(`
159
+ `).map((n)=>n.split("\t")),o=0;return e.forEach((n)=>{if(n.length>1&&It.stringWidth(n[0])>o)o=Math.min(Math.floor(this.width*0.5),It.stringWidth(n[0]))}),e.forEach((n)=>{this.div(...n.map((r,i)=>{return{text:r.trim(),padding:this.measurePadding(r),width:i===0&&n.length>1?o:void 0}}))}),this.rows[this.rows.length-1]}colFromString(t){return{text:t,padding:this.measurePadding(t)}}measurePadding(t){let e=It.stripAnsi(t);return[0,e.match(/\s*$/)[0].length,0,e.match(/^\s*/)[0].length]}toString(){let t=[];return this.rows.forEach((e)=>{this.rowToString(e,t)}),t.filter((e)=>!e.hidden).map((e)=>e.text).join(`
160
+ `)}rowToString(t,e){return this.rasterize(t).forEach((o,n)=>{let r="";o.forEach((i,s)=>{let{width:c}=t[s],u=this.negatePadding(t[s]),a=i;if(u>It.stringWidth(i))a+=" ".repeat(u-It.stringWidth(i));if(t[s].align&&t[s].align!=="left"&&this.wrap){let h=Da[t[s].align];if(a=h(a,u),It.stringWidth(a)<u)a+=" ".repeat((c||0)-It.stringWidth(a)-1)}let l=t[s].padding||[0,0,0,0];if(l[3])r+=" ".repeat(l[3]);if(r+=Ir(t[s],a,"| "),r+=a,r+=Ir(t[s],a," |"),l[1])r+=" ".repeat(l[1]);if(n===0&&e.length>0)r=this.renderInline(r,e[e.length-1])}),e.push({text:r.replace(/ +$/,""),span:t.span})}),e}renderInline(t,e){let o=t.match(/^ */),n=o?o[0].length:0,r=e.text,i=It.stringWidth(r.trimRight());if(!e.span)return t;if(!this.wrap)return e.hidden=!0,r+t;if(n<i)return t;return e.hidden=!0,r.trimRight()+" ".repeat(n-i)+t.trimLeft()}rasterize(t){let e=[],o=this.columnWidths(t),n;return t.forEach((r,i)=>{if(r.width=o[i],this.wrap)n=It.wrap(r.text,this.negatePadding(r),{hard:!0}).split(`
161
161
  `);else n=r.text.split(`
162
- `);if(r.border)n.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),n.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)n.unshift(...Array(r.padding[0]||0).fill("")),n.push(...Array(r.padding[2]||0).fill(""));n.forEach((s,c)=>{if(!e[c])e.push([]);let f=e[c];for(let a=0;a<i;a++)if(f[a]===void 0)f.push("");f.push(s)})}),e}negatePadding(t){let e=t.width||0;if(t.padding)e-=(t.padding[3]||0)+(t.padding[1]||0);if(t.border)e-=4;return e}columnWidths(t){if(!this.wrap)return t.map((i)=>{return i.width||At.stringWidth(i.text)});let e=t.length,o=this.width,n=t.map((i)=>{if(i.width)return e--,o-=i.width,i.width;return}),r=e?Math.floor(o/e):0;return n.map((i,s)=>{if(i===void 0)return Math.max(r,Ba(t[s]));return i})}}function jr(t,e,o){if(t.border){if(/[.']-+[.']/.test(e))return"";if(e.trim().length!==0)return o;return" "}return""}function Ba(t){let e=t.padding||[],o=1+(e[3]||0)+(e[1]||0);if(t.border)return o+4;return o}function La(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Aa(t,e){t=t.trim();let o=At.stringWidth(t);if(o<e)return" ".repeat(e-o)+t;return t}function Ia(t,e){t=t.trim();let o=At.stringWidth(t);if(o>=e)return t;return" ".repeat(e-o>>1)+t}var At;function Tr(t,e){return At=e,new Gr({width:(t===null||t===void 0?void 0:t.width)||La(),wrap:t===null||t===void 0?void 0:t.wrap})}var _r=new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)","g");function Dn(t){return t.replace(_r,"")}function Nr(t,e){let[o,n]=t.match(_r)||["",""];t=Dn(t);let r="";for(let i=0;i<t.length;i++){if(i!==0&&i%e===0)r+=`
163
- `;r+=t.charAt(i)}if(o&&n)r=`${o}${r}${n}`;return r}function Fn(t){return Tr(t,{stringWidth:(e)=>{return[...e].length},stripAnsi:Dn,wrap:Nr})}import{dirname as Hr,resolve as Jr}from"path";import{readdirSync as ja,statSync as Ga}from"fs";function Bn(t,e){let o=Jr(".",t),n;if(!Ga(o).isDirectory())o=Hr(o);while(!0){if(n=e(o,ja(o)),n)return Jr(o,n);if(o=Hr(n=o),n===o)break}}import{inspect as tf}from"util";import{readFileSync as ef}from"fs";import{fileURLToPath as of}from"url";import{format as Na}from"util";import{normalize as Ha,resolve as Ja}from"path";function Be(t){if(!(t!==t.toLowerCase()&&t!==t.toUpperCase()))t=t.toLowerCase();if(t.indexOf("-")===-1&&t.indexOf("_")===-1)return t;else{let o="",n=!1,r=t.match(/^-+/);for(let i=r?r[0].length:0;i<t.length;i++){let s=t.charAt(i);if(n)n=!1,s=s.toUpperCase();if(i!==0&&(s==="-"||s==="_"))n=!0;else if(s!=="-"&&s!=="_")o+=s}return o}}function Ho(t,e){let o=t.toLowerCase();e=e||"-";let n="";for(let r=0;r<t.length;r++){let i=o.charAt(r),s=t.charAt(r);if(i!==s&&r>0)n+=`${e}${o.charAt(r)}`;else n+=s}return n}function Jo(t){if(t===null||t===void 0)return!1;if(typeof t==="number")return!0;if(/^0x[0-9a-f]+$/i.test(t))return!0;if(/^0[^.]/.test(t))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(t)}function zr(t){if(Array.isArray(t))return t.map((s)=>typeof s!=="string"?s+"":s);t=t.trim();let e=0,o=null,n=null,r=null,i=[];for(let s=0;s<t.length;s++){if(o=n,n=t.charAt(s),n===" "&&!r){if(o!==" ")e++;continue}if(n===r)r=null;else if((n==="'"||n==='"')&&!r)r=n;if(!i[e])i[e]="";i[e]+=n}return i}var Nt;(function(t){t.BOOLEAN="boolean",t.STRING="string",t.NUMBER="number",t.ARRAY="array"})(Nt||(Nt={}));var se;class An{constructor(t){se=t}parse(t,e){let o=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},e),n=zr(t),r=typeof t==="string",i=Ta(Object.assign(Object.create(null),o.alias)),s=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},o.configuration),c=Object.assign(Object.create(null),o.default),f=o.configObjects||[],a=o.envPrefix,u=s["populate--"],h=u?"--":"_",d=Object.create(null),w=Object.create(null),x=o.__||se.format,m={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},b=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,S=new RegExp("^--"+s["negation-prefix"]+"(.+)");if([].concat(o.array||[]).filter(Boolean).forEach(function(g){let $=typeof g==="object"?g.key:g,W=Object.keys(g).map(function(y){return{boolean:"bools",string:"strings",number:"numbers"}[y]}).filter(Boolean).pop();if(W)m[W][$]=!0;m.arrays[$]=!0,m.keys.push($)}),[].concat(o.boolean||[]).filter(Boolean).forEach(function(g){m.bools[g]=!0,m.keys.push(g)}),[].concat(o.string||[]).filter(Boolean).forEach(function(g){m.strings[g]=!0,m.keys.push(g)}),[].concat(o.number||[]).filter(Boolean).forEach(function(g){m.numbers[g]=!0,m.keys.push(g)}),[].concat(o.count||[]).filter(Boolean).forEach(function(g){m.counts[g]=!0,m.keys.push(g)}),[].concat(o.normalize||[]).filter(Boolean).forEach(function(g){m.normalize[g]=!0,m.keys.push(g)}),typeof o.narg==="object")Object.entries(o.narg).forEach(([g,$])=>{if(typeof $==="number")m.nargs[g]=$,m.keys.push(g)});if(typeof o.coerce==="object")Object.entries(o.coerce).forEach(([g,$])=>{if(typeof $==="function")m.coercions[g]=$,m.keys.push(g)});if(typeof o.config<"u"){if(Array.isArray(o.config)||typeof o.config==="string")[].concat(o.config).filter(Boolean).forEach(function(g){m.configs[g]=!0});else if(typeof o.config==="object")Object.entries(o.config).forEach(([g,$])=>{if(typeof $==="boolean"||typeof $==="function")m.configs[g]=$})}dt(o.key,i,o.default,m.arrays),Object.keys(c).forEach(function(g){(m.aliases[g]||[]).forEach(function($){c[$]=c[g]})});let R=null;to();let P=[],M=Object.assign(Object.create(null),{_:[]}),st={};for(let g=0;g<n.length;g++){let $=n[g],W=$.replace(/^-{3,}/,"---"),y,C,N,B,v,yt;if($!=="--"&&/^-/.test($)&&nt($))ct($);else if(W.match(/^---+(=|$)/)){ct($);continue}else if($.match(/^--.+=/)||!s["short-option-groups"]&&$.match(/^-.+=/)){if(B=$.match(/^--?([^=]+)=([\s\S]*)$/),B!==null&&Array.isArray(B)&&B.length>=3)if(A(B[1],m.arrays))g=ot(g,B[1],n,B[2]);else if(A(B[1],m.nargs)!==!1)g=_(g,B[1],n,B[2]);else et(B[1],B[2],!0)}else if($.match(S)&&s["boolean-negation"]){if(B=$.match(S),B!==null&&Array.isArray(B)&&B.length>=2)C=B[1],et(C,A(C,m.arrays)?[!1]:!1)}else if($.match(/^--.+/)||!s["short-option-groups"]&&$.match(/^-[^-]+/)){if(B=$.match(/^--?(.+)/),B!==null&&Array.isArray(B)&&B.length>=2)if(C=B[1],A(C,m.arrays))g=ot(g,C,n);else if(A(C,m.nargs)!==!1)g=_(g,C,n);else if(v=n[g+1],v!==void 0&&(!v.match(/^-/)||v.match(b))&&!A(C,m.bools)&&!A(C,m.counts))et(C,v),g++;else if(/^(true|false)$/.test(v))et(C,v),g++;else et(C,U(C))}else if($.match(/^-.\..+=/)){if(B=$.match(/^-([^=]+)=([\s\S]*)$/),B!==null&&Array.isArray(B)&&B.length>=3)et(B[1],B[2])}else if($.match(/^-.\..+/)&&!$.match(b)){if(v=n[g+1],B=$.match(/^-(.\..+)/),B!==null&&Array.isArray(B)&&B.length>=2)if(C=B[1],v!==void 0&&!v.match(/^-/)&&!A(C,m.bools)&&!A(C,m.counts))et(C,v),g++;else et(C,U(C))}else if($.match(/^-[^-]+/)&&!$.match(b)){N=$.slice(1,-1).split(""),y=!1;for(let Dt=0;Dt<N.length;Dt++){if(v=$.slice(Dt+2),N[Dt+1]&&N[Dt+1]==="="){if(yt=$.slice(Dt+3),C=N[Dt],A(C,m.arrays))g=ot(g,C,n,yt);else if(A(C,m.nargs)!==!1)g=_(g,C,n,yt);else et(C,yt);y=!0;break}if(v==="-"){et(N[Dt],v);continue}if(/[A-Za-z]/.test(N[Dt])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(v)&&A(v,m.bools)===!1){et(N[Dt],v),y=!0;break}if(N[Dt+1]&&N[Dt+1].match(/\W/)){et(N[Dt],v),y=!0;break}else et(N[Dt],U(N[Dt]))}if(C=$.slice(-1)[0],!y&&C!=="-")if(A(C,m.arrays))g=ot(g,C,n);else if(A(C,m.nargs)!==!1)g=_(g,C,n);else if(v=n[g+1],v!==void 0&&(!/^(-|--)[^-]/.test(v)||v.match(b))&&!A(C,m.bools)&&!A(C,m.counts))et(C,v),g++;else if(/^(true|false)$/.test(v))et(C,v),g++;else et(C,U(C))}else if($.match(/^-[0-9]$/)&&$.match(b)&&A($.slice(1),m.bools))C=$.slice(1),et(C,U(C));else if($==="--"){P=n.slice(g+1);break}else if(s["halt-at-non-option"]){P=n.slice(g);break}else ct($)}if(mt(M,!0),mt(M,!1),L(M),tt(),z(M,m.aliases,c,!0),V(M),s["set-placeholder-key"])ut(M);if(Object.keys(m.counts).forEach(function(g){if(!T(M,g.split(".")))et(g,0)}),u&&P.length)M[h]=[];if(P.forEach(function(g){M[h].push(g)}),s["camel-case-expansion"]&&s["strip-dashed"])Object.keys(M).filter((g)=>g!=="--"&&g.includes("-")).forEach((g)=>{delete M[g]});if(s["strip-aliased"])[].concat(...Object.keys(i).map((g)=>i[g])).forEach((g)=>{if(s["camel-case-expansion"]&&g.includes("-"))delete M[g.split(".").map(($)=>Be($)).join(".")];delete M[g]});function ct(g){let $=D("_",g);if(typeof $==="string"||typeof $==="number")M._.push($)}function _(g,$,W,y){let C,N=A($,m.nargs);if(N=typeof N!=="number"||isNaN(N)?1:N,N===0){if(!rt(y))R=Error(x("Argument unexpected for: %s",$));return et($,U($)),g}let B=rt(y)?0:1;if(s["nargs-eats-options"]){if(W.length-(g+1)+B<N)R=Error(x("Not enough arguments following: %s",$));B=N}else{for(C=g+1;C<W.length;C++)if(!W[C].match(/^-[^0-9]/)||W[C].match(b)||nt(W[C]))B++;else break;if(B<N)R=Error(x("Not enough arguments following: %s",$))}let v=Math.min(B,N);if(!rt(y)&&v>0)et($,y),v--;for(C=g+1;C<v+g+1;C++)et($,W[C]);return g+v}function ot(g,$,W,y){let C=[],N=y||W[g+1],B=A($,m.nargs);if(A($,m.bools)&&!/^(true|false)$/.test(N))C.push(!0);else if(rt(N)||rt(y)&&/^-/.test(N)&&!b.test(N)&&!nt(N)){if(c[$]!==void 0){let v=c[$];C=Array.isArray(v)?v:[v]}}else{if(!rt(y))C.push(G($,y,!0));for(let v=g+1;v<W.length;v++){if(!s["greedy-arrays"]&&C.length>0||B&&typeof B==="number"&&C.length>=B)break;if(N=W[v],/^-/.test(N)&&!b.test(N)&&!nt(N))break;g=v,C.push(G($,N,r))}}if(typeof B==="number"&&(B&&C.length<B||isNaN(B)&&C.length===0))R=Error(x("Not enough arguments following: %s",$));return et($,C),g}function et(g,$,W=r){if(/-/.test(g)&&s["camel-case-expansion"]){let N=g.split(".").map(function(B){return Be(B)}).join(".");re(g,N)}let y=G(g,$,W),C=g.split(".");if(Z(M,C,y),m.aliases[g])m.aliases[g].forEach(function(N){let B=N.split(".");Z(M,B,y)});if(C.length>1&&s["dot-notation"])(m.aliases[C[0]]||[]).forEach(function(N){let B=N.split("."),v=[].concat(C);if(v.shift(),B=B.concat(v),!(m.aliases[g]||[]).includes(B.join(".")))Z(M,B,y)});if(A(g,m.normalize)&&!A(g,m.arrays))[g].concat(m.aliases[g]||[]).forEach(function(B){Object.defineProperty(st,B,{enumerable:!0,get(){return $},set(v){$=typeof v==="string"?se.normalize(v):v}})})}function re(g,$){if(!(m.aliases[g]&&m.aliases[g].length))m.aliases[g]=[$],d[$]=!0;if(!(m.aliases[$]&&m.aliases[$].length))re($,g)}function G(g,$,W){if(W)$=_a($);if(A(g,m.bools)||A(g,m.counts)){if(typeof $==="string")$=$==="true"}let y=Array.isArray($)?$.map(function(C){return D(g,C)}):D(g,$);if(A(g,m.counts)&&(rt(y)||typeof y==="boolean"))y=Ln();if(A(g,m.normalize)&&A(g,m.arrays))if(Array.isArray($))y=$.map((C)=>{return se.normalize(C)});else y=se.normalize($);return y}function D(g,$){if(!s["parse-positional-numbers"]&&g==="_")return $;if(!A(g,m.strings)&&!A(g,m.bools)&&!Array.isArray($)){if(Jo($)&&s["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${$}`)))||!rt($)&&A(g,m.numbers))$=Number($)}return $}function L(g){let $=Object.create(null);z($,m.aliases,c),Object.keys(m.configs).forEach(function(W){let y=g[W]||$[W];if(y)try{let C=null,N=se.resolve(se.cwd(),y),B=m.configs[W];if(typeof B==="function"){try{C=B(N)}catch(v){C=v}if(C instanceof Error){R=C;return}}else C=se.require(N);K(C)}catch(C){if(C.name==="PermissionDenied")R=C;else if(g[W])R=Error(x("Invalid JSON config file: %s",y))}})}function K(g,$){Object.keys(g).forEach(function(W){let y=g[W],C=$?$+"."+W:W;if(typeof y==="object"&&y!==null&&!Array.isArray(y)&&s["dot-notation"])K(y,C);else if(!T(M,C.split("."))||A(C,m.arrays)&&s["combine-arrays"])et(C,y)})}function tt(){if(typeof f<"u")f.forEach(function(g){K(g)})}function mt(g,$){if(typeof a>"u")return;let W=typeof a==="string"?a:"",y=se.env();Object.keys(y).forEach(function(C){if(W===""||C.lastIndexOf(W,0)===0){let N=C.split("__").map(function(B,v){if(v===0)B=B.substring(W.length);return Be(B)});if(($&&m.configs[N.join(".")]||!$)&&!T(g,N))et(N.join("."),y[C])}})}function V(g){let $,W=new Set;Object.keys(g).forEach(function(y){if(!W.has(y)){if($=A(y,m.coercions),typeof $==="function")try{let C=D(y,$(g[y]));[].concat(m.aliases[y]||[],y).forEach((N)=>{W.add(N),g[N]=C})}catch(C){R=C}}})}function ut(g){return m.keys.forEach(($)=>{if(~$.indexOf("."))return;if(typeof g[$]>"u")g[$]=void 0}),g}function z(g,$,W,y=!1){Object.keys(W).forEach(function(C){if(!T(g,C.split("."))){if(Z(g,C.split("."),W[C]),y)w[C]=!0;($[C]||[]).forEach(function(N){if(T(g,N.split(".")))return;Z(g,N.split("."),W[C])})}})}function T(g,$){let W=g;if(!s["dot-notation"])$=[$.join(".")];$.slice(0,-1).forEach(function(C){W=W[C]||{}});let y=$[$.length-1];if(typeof W!=="object")return!1;else return y in W}function Z(g,$,W){let y=g;if(!s["dot-notation"])$=[$.join(".")];$.slice(0,-1).forEach(function(yt){if(yt=vr(yt),typeof y==="object"&&y[yt]===void 0)y[yt]={};if(typeof y[yt]!=="object"||Array.isArray(y[yt])){if(Array.isArray(y[yt]))y[yt].push({});else y[yt]=[y[yt],{}];y=y[yt][y[yt].length-1]}else y=y[yt]});let C=vr($[$.length-1]),N=A($.join("."),m.arrays),B=Array.isArray(W),v=s["duplicate-arguments-array"];if(!v&&A(C,m.nargs)){if(v=!0,!rt(y[C])&&m.nargs[C]===1||Array.isArray(y[C])&&y[C].length===m.nargs[C])y[C]=void 0}if(W===Ln())y[C]=Ln(y[C]);else if(Array.isArray(y[C]))if(v&&N&&B)y[C]=s["flatten-duplicate-arrays"]?y[C].concat(W):(Array.isArray(y[C][0])?y[C]:[y[C]]).concat([W]);else if(!v&&Boolean(N)===Boolean(B))y[C]=W;else y[C]=y[C].concat([W]);else if(y[C]===void 0&&N)y[C]=B?W:[W];else if(v&&!(y[C]===void 0||A(C,m.counts)||A(C,m.bools)))y[C]=[y[C],W];else y[C]=W}function dt(...g){g.forEach(function($){Object.keys($||{}).forEach(function(W){if(m.aliases[W])return;m.aliases[W]=[].concat(i[W]||[]),m.aliases[W].concat(W).forEach(function(y){if(/-/.test(y)&&s["camel-case-expansion"]){let C=Be(y);if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].concat(W).forEach(function(y){if(y.length>1&&/[A-Z]/.test(y)&&s["camel-case-expansion"]){let C=Ho(y,"-");if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].forEach(function(y){m.aliases[y]=[W].concat(m.aliases[W].filter(function(C){return y!==C}))})})})}function A(g,$){let W=[].concat(m.aliases[g]||[],g),y=Object.keys($),C=W.find((N)=>y.includes(N));return C?$[C]:!1}function Xt(g){let $=Object.keys(m);return[].concat($.map((y)=>m[y])).some(function(y){return Array.isArray(y)?y.includes(g):y[g]})}function xe(g,...$){return[].concat(...$).some(function(y){let C=g.match(y);return C&&Xt(C[1])})}function F(g){if(g.match(b)||!g.match(/^-[^-]+/))return!1;let $=!0,W,y=g.slice(1).split("");for(let C=0;C<y.length;C++){if(W=g.slice(C+2),!Xt(y[C])){$=!1;break}if(y[C+1]&&y[C+1]==="="||W==="-"||/[A-Za-z]/.test(y[C])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(W)||y[C+1]&&y[C+1].match(/\W/))break}return $}function nt(g){return s["unknown-options-as-args"]&&pt(g)}function pt(g){if(g=g.replace(/^-{3,}/,"--"),g.match(b))return!1;if(F(g))return!1;return!xe(g,/^-+([^=]+?)=[\s\S]*$/,S,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function U(g){if(!A(g,m.bools)&&!A(g,m.counts)&&`${g}`in c)return c[g];else return Q(ft(g))}function Q(g){return{[Nt.BOOLEAN]:!0,[Nt.STRING]:"",[Nt.NUMBER]:void 0,[Nt.ARRAY]:[]}[g]}function ft(g){let $=Nt.BOOLEAN;if(A(g,m.strings))$=Nt.STRING;else if(A(g,m.numbers))$=Nt.NUMBER;else if(A(g,m.bools))$=Nt.BOOLEAN;else if(A(g,m.arrays))$=Nt.ARRAY;return $}function rt(g){return g===void 0}function to(){Object.keys(m.counts).find((g)=>{if(A(g,m.arrays))return R=Error(x("Invalid configuration: %s, opts.count excludes opts.array.",g)),!0;else if(A(g,m.nargs))return R=Error(x("Invalid configuration: %s, opts.count excludes opts.narg.",g)),!0;return!1})}return{aliases:Object.assign({},m.aliases),argv:Object.assign(st,M),configuration:s,defaulted:Object.assign({},w),error:R,newAliases:Object.assign({},d)}}}function Ta(t){let e=[],o=Object.create(null),n=!0;Object.keys(t).forEach(function(r){e.push([].concat(t[r],r))});while(n){n=!1;for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length;i++)if(e[r].filter(function(c){return e[i].indexOf(c)!==-1}).length){e[r]=e[r].concat(e[i]),e.splice(i,1),n=!0;break}}return e.forEach(function(r){r=r.filter(function(s,c,f){return f.indexOf(s)===c});let i=r.pop();if(i!==void 0&&typeof i==="string")o[i]=r}),o}function Ln(t){return t!==void 0?t+1:1}function vr(t){if(t==="__proto__")return"___proto___";return t}function _a(t){return typeof t==="string"&&(t[0]==="'"||t[0]==='"')&&t[t.length-1]===t[0]?t.substring(1,t.length-1):t}var In,jn,Gn,kr=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Ur=(jn=(In=process===null||process===void 0?void 0:process.versions)===null||In===void 0?void 0:In.node)!==null&&jn!==void 0?jn:(Gn=process===null||process===void 0?void 0:process.version)===null||Gn===void 0?void 0:Gn.slice(1);if(Ur){if(Number(Ur.match(/^([^.]+)/)[1])<kr)throw Error(`yargs parser supports a minimum Node.js version of ${kr}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var za=process?process.env:{},Kr=new An({cwd:process.cwd,env:()=>{return za},format:Na,normalize:Ha,resolve:Ja,require:(t)=>{return ie(t)}}),Co=function(e,o){return Kr.parse(e.slice(),o).argv};Co.detailed=function(t,e){return Kr.parse(t.slice(),e)};Co.camelCase=Be;Co.decamelize=Ho;Co.looksLikeNumber=Jo;var Tn=Co;import{basename as nf,dirname as rf,extname as sf,relative as cf,resolve as ti}from"path";function qr(){if(va())return 0;return 1}function va(){return ka()&&!process.defaultApp}function ka(){return!!process.versions.electron}function _n(t){return t.slice(qr()+1)}function Vr(){return process.argv[qr()]}class lt extends Error{constructor(t){super(t||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,lt)}}import{readFileSync as Ua,statSync as Ka,writeFile as qa}from"fs";import{format as Va}from"util";import{resolve as Xa}from"path";var Xr={fs:{readFileSync:Ua,writeFile:qa},format:Va,resolve:Xa,exists:(t)=>{try{return Ka(t).isFile()}catch(e){return!1}}};var Kt;class Zr{constructor(t){t=t||{},this.directory=t.directory||"./locales",this.updateFiles=typeof t.updateFiles==="boolean"?t.updateFiles:!0,this.locale=t.locale||"en",this.fallbackToLanguage=typeof t.fallbackToLanguage==="boolean"?t.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...t){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let e=t.shift(),o=function(){};if(typeof t[t.length-1]==="function")o=t.pop();if(o=o||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]=e,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o});else o();return Kt.format.apply(Kt.format,[this.cache[this.locale][e]||e].concat(t))}__n(){let t=Array.prototype.slice.call(arguments),e=t.shift(),o=t.shift(),n=t.shift(),r=function(){};if(typeof t[t.length-1]==="function")r=t.pop();if(!this.cache[this.locale])this._readLocaleFile();let i=n===1?e:o;if(this.cache[this.locale][e])i=this.cache[this.locale][e][n===1?"one":"other"];if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]={one:e,other:o},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r});else r();let s=[i];if(~i.indexOf("%d"))s.push(n);return Kt.format.apply(Kt.format,s.concat(t))}setLocale(t){this.locale=t}getLocale(){return this.locale}updateLocale(t){if(!this.cache[this.locale])this._readLocaleFile();for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))this.cache[this.locale][e]=t[e]}_taggedLiteral(t,...e){let o="";return t.forEach(function(n,r){let i=e[r+1];if(o+=n,typeof i<"u")o+="%s"}),this.__.apply(this,[o].concat([].slice.call(e,1)))}_enqueueWrite(t){if(this.writeQueue.push(t),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let t=this,e=this.writeQueue[0],o=e.directory,n=e.locale,r=e.cb,i=this._resolveLocaleFile(o,n),s=JSON.stringify(this.cache[n],null,2);Kt.fs.writeFile(i,s,"utf-8",function(c){if(t.writeQueue.shift(),t.writeQueue.length>0)t._processWriteQueue();r(c)})}_readLocaleFile(){let t={},e=this._resolveLocaleFile(this.directory,this.locale);try{if(Kt.fs.readFileSync)t=JSON.parse(Kt.fs.readFileSync(e,"utf-8"))}catch(o){if(o instanceof SyntaxError)o.message="syntax error in "+e;if(o.code==="ENOENT")t={};else throw o}this.cache[this.locale]=t}_resolveLocaleFile(t,e){let o=Kt.resolve(t,"./",e+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(o)&&~e.lastIndexOf("_")){let n=Kt.resolve(t,"./",e.split("_")[0]+".json");if(this._fileExistsSync(n))o=n}return o}_fileExistsSync(t){return Kt.exists(t)}}function Qr(t,e){Kt=e;let o=new Zr(t);return{__:o.__.bind(o),__n:o.__n.bind(o),setLocale:o.setLocale.bind(o),getLocale:o.getLocale.bind(o),updateLocale:o.updateLocale.bind(o),locale:o.locale}}var Za=(t)=>{return Qr(t,Xr)},Yr=Za;var af="require is not supported by ESM",ei="loading a directory of commands is not supported yet for ESM",$o;try{$o=of(import.meta.url)}catch(t){$o=process.cwd()}var ff=$o.substring(0,$o.lastIndexOf("node_modules")),Nn={assert:{notStrictEqual:Qa,strictEqual:Ya},cliui:Fn,findUp:Bn,getEnv:(t)=>{return process.env[t]},inspect:tf,getCallerFile:()=>{throw new lt(ei)},getProcessArgvBin:Vr,mainFilename:ff||process.cwd(),Parser:Tn,path:{basename:nf,dirname:rf,extname:sf,relative:cf,resolve:ti},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(t,e)=>process.emitWarning(t,e),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:ef,require:()=>{throw new lt(af)},requireDirectory:()=>{throw new lt(ei)},stringWidth:(t)=>{return[...t].length},y18n:Yr({directory:ti($o,"../../../locales"),updateFiles:!1})};function Ft(t,e,o,n){o.assert.notStrictEqual(t,e,n)}function Hn(t,e){e.assert.strictEqual(typeof t,"string")}function eo(t){return Object.keys(t)}function ht(t){return!!t&&!!t.then&&typeof t.then==="function"}function we(t){let o=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),n=/\.*[\][<>]/g,r=o.shift();if(!r)throw Error(`No command found in: ${t}`);let i={cmd:r.replace(n,""),demanded:[],optional:[]};return o.forEach((s,c)=>{let f=!1;if(s=s.replace(/\s/g,""),/\.+[\]>]/.test(s)&&c===o.length-1)f=!0;if(/^\[/.test(s))i.optional.push({cmd:s.replace(n,"").split("|"),variadic:f});else i.demanded.push({cmd:s.replace(n,"").split("|"),variadic:f})}),i}var lf=["first","second","third","fourth","fifth","sixth"];function I(t,e,o){function n(){return typeof t==="object"?[{demanded:[],optional:[]},t,e]:[we(`cmd ${t}`),e,o]}try{let r=0,[i,s,c]=n(),f=[].slice.call(s);while(f.length&&f[f.length-1]===void 0)f.pop();let a=c||f.length;if(a<i.demanded.length)throw new lt(`Not enough arguments provided. Expected ${i.demanded.length} but received ${f.length}.`);let u=i.demanded.length+i.optional.length;if(a>u)throw new lt(`Too many arguments provided. Expected max ${u} but received ${a}.`);i.demanded.forEach((h)=>{let d=f.shift(),w=oi(d);if(h.cmd.filter((m)=>m===w||m==="*").length===0)ni(w,h.cmd,r);r+=1}),i.optional.forEach((h)=>{if(f.length===0)return;let d=f.shift(),w=oi(d);if(h.cmd.filter((m)=>m===w||m==="*").length===0)ni(w,h.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function oi(t){if(Array.isArray(t))return"array";else if(t===null)return"null";return typeof t}function ni(t,e,o){throw new lt(`Invalid ${lf[o]||"manyith"} argument. Expected ${e.join(" or ")} but received ${t}.`)}class Jn{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,o=!0,n=!1){if(I("<array|function> [boolean] [boolean] [boolean]",[t,e,o],arguments.length),Array.isArray(t)){for(let r=0;r<t.length;r++){if(typeof t[r]!=="function")throw Error("middleware must be a function");let i=t[r];i.applyBeforeValidation=e,i.global=o}Array.prototype.push.apply(this.globalMiddleware,t)}else if(typeof t==="function"){let r=t;r.applyBeforeValidation=e,r.global=o,r.mutates=n,this.globalMiddleware.push(t)}return this.yargs}addCoerceMiddleware(t,e){let o=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((n)=>{let r=[...o[e]||[],e];if(!n.option)return!0;else return!r.includes(n.option)}),t.option=e,this.addMiddleware(t,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let t=this.frozens.pop();if(t!==void 0)this.globalMiddleware=t}reset(){this.globalMiddleware=this.globalMiddleware.filter((t)=>t.global)}}function ri(t){if(!t)return[];return t.map((e)=>{return e.applyBeforeValidation=!1,e})}function Le(t,e,o,n){return o.reduce((r,i)=>{if(i.applyBeforeValidation!==n)return r;if(i.mutates){if(i.applied)return r;i.applied=!0}if(ht(r))return r.then((s)=>Promise.all([s,i(s,e)])).then(([s,c])=>Object.assign(s,c));else{let s=i(r,e);return ht(s)?s.then((c)=>Object.assign(r,c)):Object.assign(r,s)}},t)}function Ae(t,e,o=(n)=>{throw n}){try{let n=hf(t)?t():t;return ht(n)?n.then((r)=>e(r)):e(n)}catch(n){return o(n)}}function hf(t){return typeof t==="function"}function zn(t){for(let e=0,o=Object.keys(ie.cache),n;e<o.length;e++)if(n=ie.cache[o[e]],n.exports===t)return n;return null}var oo=/(^\*)|(^\$0)/;class si{constructor(t,e,o,n){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=n,this.usage=t,this.globalMiddleware=o,this.validation=e}addDirectory(t,e,o,n){if(n=n||{},typeof n.recurse!=="boolean")n.recurse=!1;if(!Array.isArray(n.extensions))n.extensions=["js"];let r=typeof n.visit==="function"?n.visit:(i)=>i;n.visit=(i,s,c)=>{let f=r(i,s,c);if(f){if(this.requireCache.has(s))return f;else this.requireCache.add(s);this.addHandler(f)}return f},this.shim.requireDirectory({require:e,filename:o},t,n)}addHandler(t,e,o,n,r,i){let s=[],c=ri(r);if(n=n||(()=>{}),Array.isArray(t))if(uf(t))[t,...s]=t;else for(let f of t)this.addHandler(f);else if(df(t)){let f=Array.isArray(t.command)||typeof t.command==="string"?t.command:this.moduleName(t);if(t.aliases)f=[].concat(f).concat(t.aliases);this.addHandler(f,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated);return}else if(ii(o)){this.addHandler([t].concat(s),e,o.builder,o.handler,o.middlewares,o.deprecated);return}if(typeof t==="string"){let f=we(t);s=s.map((h)=>we(h).cmd);let a=!1,u=[f.cmd].concat(s).filter((h)=>{if(oo.test(h))return a=!0,!1;return!0});if(u.length===0&&a)u.push("$0");if(a)f.cmd=u[0],s=u.slice(1),t=t.replace(oo,f.cmd);if(s.forEach((h)=>{this.aliasMap[h]=f.cmd}),e!==!1)this.usage.command(t,e,a,s,i);if(this.handlers[f.cmd]={original:t,description:e,handler:n,builder:o||{},middlewares:c,deprecated:i,demanded:f.demanded,optional:f.optional},a)this.defaultCommand=this.handlers[f.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,o,n,r,i){let s=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,c=e.getInternalMethods().getContext(),f=c.commands.slice(),a=!t;if(t)c.commands.push(t),c.fullCommands.push(s.original);let u=this.applyBuilderUpdateUsageAndParse(a,s,e,o.aliases,f,n,r,i);return ht(u)?u.then((h)=>this.applyMiddlewareAndGetResult(a,s,h.innerArgv,c,r,h.aliases,e)):this.applyMiddlewareAndGetResult(a,s,u.innerArgv,c,r,u.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,o,n,r,i,s,c){let f=e.builder,a=o;if(zo(f)){o.getInternalMethods().getUsageInstance().freeze();let u=f(o.getInternalMethods().reset(n),c);if(ht(u))return u.then((h)=>{return a=ai(h)?h:o,this.parseAndUpdateUsage(t,e,a,r,i,s)})}else if(pf(f))o.getInternalMethods().getUsageInstance().freeze(),a=o.getInternalMethods().reset(n),Object.keys(e.builder).forEach((u)=>{a.option(u,f[u])});return this.parseAndUpdateUsage(t,e,a,r,i,s)}parseAndUpdateUsage(t,e,o,n,r,i){if(t)o.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(o))o.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(n,e),e.description);let s=o.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,i);return ht(s)?s.then((c)=>({aliases:o.parsed.aliases,innerArgv:c})):{aliases:o.parsed.aliases,innerArgv:s}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&t.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(t,e){let o=oo.test(e.original)?e.original.replace(oo,"").trim():e.original,n=t.filter((r)=>{return!oo.test(r)});return n.push(o),`$0 ${n.join(" ")}`}handleValidationAndGetResult(t,e,o,n,r,i,s,c){if(!i.getInternalMethods().getHasOutput()){let f=i.getInternalMethods().runValidation(r,c,i.parsed.error,t);o=Ae(o,(a)=>{return f(a),a})}if(e.handler&&!i.getInternalMethods().getHasOutput()){i.getInternalMethods().setHasOutput();let f=!!i.getOptions().configuration["populate--"];if(i.getInternalMethods().postProcess(o,f,!1,!1),o=Le(o,i,s,!1),o=Ae(o,(a)=>{let u=e.handler(a);return ht(u)?u.then(()=>a):a}),!t)i.getInternalMethods().getUsageInstance().cacheHelpMessage();if(ht(o)&&!i.getInternalMethods().hasParseCallback())o.catch((a)=>{try{i.getInternalMethods().getUsageInstance().fail(null,a)}catch(u){}})}if(!t)n.commands.pop(),n.fullCommands.pop();return o}applyMiddlewareAndGetResult(t,e,o,n,r,i,s){let c={};if(r)return o;if(!s.getInternalMethods().getHasOutput())c=this.populatePositionals(e,o,n,s);let f=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares),a=Le(o,s,f,!0);return ht(a)?a.then((u)=>this.handleValidationAndGetResult(t,e,u,n,i,s,f,c)):this.handleValidationAndGetResult(t,e,a,n,i,s,f,c)}populatePositionals(t,e,o,n){e._=e._.slice(o.commands.length);let r=t.demanded.slice(0),i=t.optional.slice(0),s={};this.validation.positionalCount(r.length,e._.length);while(r.length){let c=r.shift();this.populatePositional(c,e,s)}while(i.length){let c=i.shift();this.populatePositional(c,e,s)}return e._=o.commands.concat(e._.map((c)=>""+c)),this.postProcessPositionals(e,s,this.cmdToParseOptions(t.original),n),s}populatePositional(t,e,o){let n=t.cmd[0];if(t.variadic)o[n]=e._.splice(0).map(String);else if(e._.length)o[n]=[String(e._.shift())]}cmdToParseOptions(t){let e={array:[],default:{},alias:{},demand:{}},o=we(t);return o.demanded.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i,e.demand[r]=!0}),o.optional.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i}),e}postProcessPositionals(t,e,o,n){let r=Object.assign({},n.getOptions());r.default=Object.assign(o.default,r.default);for(let f of Object.keys(o.alias))r.alias[f]=(r.alias[f]||[]).concat(o.alias[f]);r.array=r.array.concat(o.array),r.config={};let i=[];if(Object.keys(e).forEach((f)=>{e[f].map((a)=>{if(r.configuration["unknown-options-as-args"])r.key[f]=!0;i.push(`--${f}`),i.push(a)})}),!i.length)return;let s=Object.assign({},r.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(i,Object.assign({},r,{configuration:s}));if(c.error)n.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let f=Object.keys(e);Object.keys(e).forEach((a)=>{f.push(...c.aliases[a])}),Object.keys(c.argv).forEach((a)=>{if(f.includes(a)){if(!e[a])e[a]=c.argv[a];if(!this.isInConfigs(n,a)&&!this.isDefaulted(n,a)&&Object.prototype.hasOwnProperty.call(t,a)&&Object.prototype.hasOwnProperty.call(c.argv,a)&&(Array.isArray(t[a])||Array.isArray(c.argv[a])))t[a]=[].concat(t[a],c.argv[a]);else t[a]=c.argv[a]}})}}isDefaulted(t,e){let{default:o}=t.getOptions();return Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(e))}isInConfigs(t,e){let{configObjects:o}=t.getOptions();return o.some((n)=>Object.prototype.hasOwnProperty.call(n,e))||o.some((n)=>Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(e)))}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){let o=oo.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(o,this.defaultCommand.description)}let e=this.defaultCommand.builder;if(zo(e))return e(t,!0);else if(!ii(e))Object.keys(e).forEach((o)=>{t.option(o,e[o])});return}moduleName(t){let e=zn(t);if(!e)throw Error(`No command name given for module: ${this.shim.inspect(t)}`);return this.commandFromFilename(e.filename)}commandFromFilename(t){return this.shim.path.basename(t,this.shim.path.extname(t))}extractDesc({describe:t,description:e,desc:o}){for(let n of[t,e,o]){if(typeof n==="string"||n===!1)return n;Ft(n,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let t=this.frozens.pop();Ft(t,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=t}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function ci(t,e,o,n){return new si(t,e,o,n)}function ii(t){return typeof t==="object"&&!!t.builder&&typeof t.handler==="function"}function uf(t){return t.every((e)=>typeof e==="string")}function zo(t){return typeof t==="function"}function pf(t){return typeof t==="object"}function df(t){return typeof t==="object"&&!Array.isArray(t)}function ge(t={},e=()=>!0){let o={};return eo(t).forEach((n)=>{if(e(n,t[n]))o[n]=t[n]}),o}function be(t){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((e)=>{let o=e;if(o._handle&&o.isTTY&&typeof o._handle.setBlocking==="function")o._handle.setBlocking(t)})}function mf(t){return typeof t==="boolean"}function li(t,e){let o=e.y18n.__,n={},r=[];n.failFn=function(D){r.push(D)};let i=null,s=null,c=!0;n.showHelpOnFail=function(D=!0,L){let[K,tt]=typeof D==="string"?[!0,D]:[D,L];if(t.getInternalMethods().isGlobalContext())s=tt;return i=tt,c=K,n};let f=!1;n.fail=function(D,L){let K=t.getInternalMethods().getLoggerInstance();if(r.length)for(let tt=r.length-1;tt>=0;--tt){let mt=r[tt];if(mf(mt)){if(L)throw L;else if(D)throw Error(D)}else mt(D,L,n)}else{if(t.getExitProcess())be(!0);if(!f){if(f=!0,c)t.showHelp("error"),K.error();if(D||L)K.error(D||L);let tt=i||s;if(tt){if(D||L)K.error("");K.error(tt)}}if(L=L||new lt(D),t.getExitProcess())return t.exit(1);else if(t.getInternalMethods().hasParseCallback())return t.exit(1,L);else throw L}};let a=[],u=!1;n.usage=(G,D)=>{if(G===null)return u=!0,a=[],n;return u=!1,a.push([G,D||""]),n},n.getUsage=()=>{return a},n.getUsageDisabled=()=>{return u},n.getPositionalGroupName=()=>{return o("Positionals:")};let h=[];n.example=(G,D)=>{h.push([G,D||""])};let d=[];n.command=function(D,L,K,tt,mt=!1){if(K)d=d.map((V)=>{return V[2]=!1,V});d.push([D,L||"",K,tt,mt])},n.getCommands=()=>d;let w={};n.describe=function(D,L){if(Array.isArray(D))D.forEach((K)=>{n.describe(K,L)});else if(typeof D==="object")Object.keys(D).forEach((K)=>{n.describe(K,D[K])});else w[D]=L},n.getDescriptions=()=>w;let x=[];n.epilog=(G)=>{x.push(G)};let m=!1,b;n.wrap=(G)=>{m=!0,b=G},n.getWrap=()=>{if(e.getEnv("YARGS_DISABLE_WRAP"))return null;if(!m)b=ot(),m=!0;return b};let S="__yargsString__:";n.deferY18nLookup=(G)=>S+G,n.help=function(){if(M)return M;P();let D=t.customScriptName?t.$0:e.path.basename(t.$0),L=t.getDemandedOptions(),K=t.getDemandedCommands(),tt=t.getDeprecatedOptions(),mt=t.getGroups(),V=t.getOptions(),ut=[];ut=ut.concat(Object.keys(w)),ut=ut.concat(Object.keys(L)),ut=ut.concat(Object.keys(K)),ut=ut.concat(Object.keys(V.default)),ut=ut.filter(ct),ut=Object.keys(ut.reduce((F,nt)=>{if(nt!=="_")F[nt]=!0;return F},{}));let z=n.getWrap(),T=e.cliui({width:z,wrap:!!z});if(!u){if(a.length)a.forEach((F)=>{if(T.div({text:`${F[0].replace(/\$0/g,D)}`}),F[1])T.div({text:`${F[1]}`,padding:[1,0,0,0]})}),T.div();else if(d.length){let F=null;if(K._)F=`${D} <${o("command")}>
162
+ `);if(r.border)n.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),n.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)n.unshift(...Array(r.padding[0]||0).fill("")),n.push(...Array(r.padding[2]||0).fill(""));n.forEach((s,c)=>{if(!e[c])e.push([]);let u=e[c];for(let a=0;a<i;a++)if(u[a]===void 0)u.push("");u.push(s)})}),e}negatePadding(t){let e=t.width||0;if(t.padding)e-=(t.padding[3]||0)+(t.padding[1]||0);if(t.border)e-=4;return e}columnWidths(t){if(!this.wrap)return t.map((i)=>{return i.width||It.stringWidth(i.text)});let e=t.length,o=this.width,n=t.map((i)=>{if(i.width)return e--,o-=i.width,i.width;return}),r=e?Math.floor(o/e):0;return n.map((i,s)=>{if(i===void 0)return Math.max(r,Fa(t[s]));return i})}}function Ir(t,e,o){if(t.border){if(/[.']-+[.']/.test(e))return"";if(e.trim().length!==0)return o;return" "}return""}function Fa(t){let e=t.padding||[],o=1+(e[3]||0)+(e[1]||0);if(t.border)return o+4;return o}function Ba(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function La(t,e){t=t.trim();let o=It.stringWidth(t);if(o<e)return" ".repeat(e-o)+t;return t}function Aa(t,e){t=t.trim();let o=It.stringWidth(t);if(o>=e)return t;return" ".repeat(e-o>>1)+t}var It;function Tr(t,e){return It=e,new jr({width:(t===null||t===void 0?void 0:t.width)||Ba(),wrap:t===null||t===void 0?void 0:t.wrap})}var _r=new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)","g");function Ln(t){return t.replace(_r,"")}function Gr(t,e){let[o,n]=t.match(_r)||["",""];t=Ln(t);let r="";for(let i=0;i<t.length;i++){if(i!==0&&i%e===0)r+=`
163
+ `;r+=t.charAt(i)}if(o&&n)r=`${o}${r}${n}`;return r}function An(t){return Tr(t,{stringWidth:(e)=>{return[...e].length},stripAnsi:Ln,wrap:Gr})}import{dirname as Hr,resolve as Nr}from"path";import{readdirSync as Ia,statSync as ja}from"fs";function In(t,e){let o=Nr(".",t),n;if(!ja(o).isDirectory())o=Hr(o);while(!0){if(n=e(o,Ia(o)),n)return Nr(o,n);if(o=Hr(n=o),n===o)break}}import{inspect as Ya}from"util";import{readFileSync as tf}from"fs";import{fileURLToPath as ef}from"url";import{format as Ga}from"util";import{normalize as Ha,resolve as Na}from"path";function Ge(t){if(!(t!==t.toLowerCase()&&t!==t.toUpperCase()))t=t.toLowerCase();if(t.indexOf("-")===-1&&t.indexOf("_")===-1)return t;else{let o="",n=!1,r=t.match(/^-+/);for(let i=r?r[0].length:0;i<t.length;i++){let s=t.charAt(i);if(n)n=!1,s=s.toUpperCase();if(i!==0&&(s==="-"||s==="_"))n=!0;else if(s!=="-"&&s!=="_")o+=s}return o}}function Ko(t,e){let o=t.toLowerCase();e=e||"-";let n="";for(let r=0;r<t.length;r++){let i=o.charAt(r),s=t.charAt(r);if(i!==s&&r>0)n+=`${e}${o.charAt(r)}`;else n+=s}return n}function Vo(t){if(t===null||t===void 0)return!1;if(typeof t==="number")return!0;if(/^0x[0-9a-f]+$/i.test(t))return!0;if(/^0[^.]/.test(t))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(t)}function Jr(t){if(Array.isArray(t))return t.map((s)=>typeof s!=="string"?s+"":s);t=t.trim();let e=0,o=null,n=null,r=null,i=[];for(let s=0;s<t.length;s++){if(o=n,n=t.charAt(s),n===" "&&!r){if(o!==" ")e++;continue}if(n===r)r=null;else if((n==="'"||n==='"')&&!r)r=n;if(!i[e])i[e]="";i[e]+=n}return i}var Jt;(function(t){t.BOOLEAN="boolean",t.STRING="string",t.NUMBER="number",t.ARRAY="array"})(Jt||(Jt={}));var he;class Tn{constructor(t){he=t}parse(t,e){let o=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},e),n=Jr(t),r=typeof t==="string",i=Ta(Object.assign(Object.create(null),o.alias)),s=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},o.configuration),c=Object.assign(Object.create(null),o.default),u=o.configObjects||[],a=o.envPrefix,l=s["populate--"],h=l?"--":"_",d=Object.create(null),g=Object.create(null),x=o.__||he.format,m={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},b=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,S=new RegExp("^--"+s["negation-prefix"]+"(.+)");if([].concat(o.array||[]).filter(Boolean).forEach(function(w){let $=typeof w==="object"?w.key:w,W=Object.keys(w).map(function(P){return{boolean:"bools",string:"strings",number:"numbers"}[P]}).filter(Boolean).pop();if(W)m[W][$]=!0;m.arrays[$]=!0,m.keys.push($)}),[].concat(o.boolean||[]).filter(Boolean).forEach(function(w){m.bools[w]=!0,m.keys.push(w)}),[].concat(o.string||[]).filter(Boolean).forEach(function(w){m.strings[w]=!0,m.keys.push(w)}),[].concat(o.number||[]).filter(Boolean).forEach(function(w){m.numbers[w]=!0,m.keys.push(w)}),[].concat(o.count||[]).filter(Boolean).forEach(function(w){m.counts[w]=!0,m.keys.push(w)}),[].concat(o.normalize||[]).filter(Boolean).forEach(function(w){m.normalize[w]=!0,m.keys.push(w)}),typeof o.narg==="object")Object.entries(o.narg).forEach(([w,$])=>{if(typeof $==="number")m.nargs[w]=$,m.keys.push(w)});if(typeof o.coerce==="object")Object.entries(o.coerce).forEach(([w,$])=>{if(typeof $==="function")m.coercions[w]=$,m.keys.push(w)});if(typeof o.config<"u"){if(Array.isArray(o.config)||typeof o.config==="string")[].concat(o.config).filter(Boolean).forEach(function(w){m.configs[w]=!0});else if(typeof o.config==="object")Object.entries(o.config).forEach(([w,$])=>{if(typeof $==="boolean"||typeof $==="function")m.configs[w]=$})}dt(o.key,i,o.default,m.arrays),Object.keys(c).forEach(function(w){(m.aliases[w]||[]).forEach(function($){c[$]=c[w]})});let R=null;so();let y=[],M=Object.assign(Object.create(null),{_:[]}),it={};for(let w=0;w<n.length;w++){let $=n[w],W=$.replace(/^-{3,}/,"---"),P,C,H,B,v,Pt;if($!=="--"&&/^-/.test($)&&nt($))st($);else if(W.match(/^---+(=|$)/)){st($);continue}else if($.match(/^--.+=/)||!s["short-option-groups"]&&$.match(/^-.+=/)){if(B=$.match(/^--?([^=]+)=([\s\S]*)$/),B!==null&&Array.isArray(B)&&B.length>=3)if(A(B[1],m.arrays))w=ot(w,B[1],n,B[2]);else if(A(B[1],m.nargs)!==!1)w=G(w,B[1],n,B[2]);else et(B[1],B[2],!0)}else if($.match(S)&&s["boolean-negation"]){if(B=$.match(S),B!==null&&Array.isArray(B)&&B.length>=2)C=B[1],et(C,A(C,m.arrays)?[!1]:!1)}else if($.match(/^--.+/)||!s["short-option-groups"]&&$.match(/^-[^-]+/)){if(B=$.match(/^--?(.+)/),B!==null&&Array.isArray(B)&&B.length>=2)if(C=B[1],A(C,m.arrays))w=ot(w,C,n);else if(A(C,m.nargs)!==!1)w=G(w,C,n);else if(v=n[w+1],v!==void 0&&(!v.match(/^-/)||v.match(b))&&!A(C,m.bools)&&!A(C,m.counts))et(C,v),w++;else if(/^(true|false)$/.test(v))et(C,v),w++;else et(C,U(C))}else if($.match(/^-.\..+=/)){if(B=$.match(/^-([^=]+)=([\s\S]*)$/),B!==null&&Array.isArray(B)&&B.length>=3)et(B[1],B[2])}else if($.match(/^-.\..+/)&&!$.match(b)){if(v=n[w+1],B=$.match(/^-(.\..+)/),B!==null&&Array.isArray(B)&&B.length>=2)if(C=B[1],v!==void 0&&!v.match(/^-/)&&!A(C,m.bools)&&!A(C,m.counts))et(C,v),w++;else et(C,U(C))}else if($.match(/^-[^-]+/)&&!$.match(b)){H=$.slice(1,-1).split(""),P=!1;for(let Ft=0;Ft<H.length;Ft++){if(v=$.slice(Ft+2),H[Ft+1]&&H[Ft+1]==="="){if(Pt=$.slice(Ft+3),C=H[Ft],A(C,m.arrays))w=ot(w,C,n,Pt);else if(A(C,m.nargs)!==!1)w=G(w,C,n,Pt);else et(C,Pt);P=!0;break}if(v==="-"){et(H[Ft],v);continue}if(/[A-Za-z]/.test(H[Ft])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(v)&&A(v,m.bools)===!1){et(H[Ft],v),P=!0;break}if(H[Ft+1]&&H[Ft+1].match(/\W/)){et(H[Ft],v),P=!0;break}else et(H[Ft],U(H[Ft]))}if(C=$.slice(-1)[0],!P&&C!=="-")if(A(C,m.arrays))w=ot(w,C,n);else if(A(C,m.nargs)!==!1)w=G(w,C,n);else if(v=n[w+1],v!==void 0&&(!/^(-|--)[^-]/.test(v)||v.match(b))&&!A(C,m.bools)&&!A(C,m.counts))et(C,v),w++;else if(/^(true|false)$/.test(v))et(C,v),w++;else et(C,U(C))}else if($.match(/^-[0-9]$/)&&$.match(b)&&A($.slice(1),m.bools))C=$.slice(1),et(C,U(C));else if($==="--"){y=n.slice(w+1);break}else if(s["halt-at-non-option"]){y=n.slice(w);break}else st($)}if(mt(M,!0),mt(M,!1),L(M),tt(),z(M,m.aliases,c,!0),q(M),s["set-placeholder-key"])ut(M);if(Object.keys(m.counts).forEach(function(w){if(!_(M,w.split(".")))et(w,0)}),l&&y.length)M[h]=[];if(y.forEach(function(w){M[h].push(w)}),s["camel-case-expansion"]&&s["strip-dashed"])Object.keys(M).filter((w)=>w!=="--"&&w.includes("-")).forEach((w)=>{delete M[w]});if(s["strip-aliased"])[].concat(...Object.keys(i).map((w)=>i[w])).forEach((w)=>{if(s["camel-case-expansion"]&&w.includes("-"))delete M[w.split(".").map(($)=>Ge($)).join(".")];delete M[w]});function st(w){let $=D("_",w);if(typeof $==="string"||typeof $==="number")M._.push($)}function G(w,$,W,P){let C,H=A($,m.nargs);if(H=typeof H!=="number"||isNaN(H)?1:H,H===0){if(!rt(P))R=Error(x("Argument unexpected for: %s",$));return et($,U($)),w}let B=rt(P)?0:1;if(s["nargs-eats-options"]){if(W.length-(w+1)+B<H)R=Error(x("Not enough arguments following: %s",$));B=H}else{for(C=w+1;C<W.length;C++)if(!W[C].match(/^-[^0-9]/)||W[C].match(b)||nt(W[C]))B++;else break;if(B<H)R=Error(x("Not enough arguments following: %s",$))}let v=Math.min(B,H);if(!rt(P)&&v>0)et($,P),v--;for(C=w+1;C<v+w+1;C++)et($,W[C]);return w+v}function ot(w,$,W,P){let C=[],H=P||W[w+1],B=A($,m.nargs);if(A($,m.bools)&&!/^(true|false)$/.test(H))C.push(!0);else if(rt(H)||rt(P)&&/^-/.test(H)&&!b.test(H)&&!nt(H)){if(c[$]!==void 0){let v=c[$];C=Array.isArray(v)?v:[v]}}else{if(!rt(P))C.push(T($,P,!0));for(let v=w+1;v<W.length;v++){if(!s["greedy-arrays"]&&C.length>0||B&&typeof B==="number"&&C.length>=B)break;if(H=W[v],/^-/.test(H)&&!b.test(H)&&!nt(H))break;w=v,C.push(T($,H,r))}}if(typeof B==="number"&&(B&&C.length<B||isNaN(B)&&C.length===0))R=Error(x("Not enough arguments following: %s",$));return et($,C),w}function et(w,$,W=r){if(/-/.test(w)&&s["camel-case-expansion"]){let H=w.split(".").map(function(B){return Ge(B)}).join(".");fe(w,H)}let P=T(w,$,W),C=w.split(".");if(Z(M,C,P),m.aliases[w])m.aliases[w].forEach(function(H){let B=H.split(".");Z(M,B,P)});if(C.length>1&&s["dot-notation"])(m.aliases[C[0]]||[]).forEach(function(H){let B=H.split("."),v=[].concat(C);if(v.shift(),B=B.concat(v),!(m.aliases[w]||[]).includes(B.join(".")))Z(M,B,P)});if(A(w,m.normalize)&&!A(w,m.arrays))[w].concat(m.aliases[w]||[]).forEach(function(B){Object.defineProperty(it,B,{enumerable:!0,get(){return $},set(v){$=typeof v==="string"?he.normalize(v):v}})})}function fe(w,$){if(!(m.aliases[w]&&m.aliases[w].length))m.aliases[w]=[$],d[$]=!0;if(!(m.aliases[$]&&m.aliases[$].length))fe($,w)}function T(w,$,W){if(W)$=_a($);if(A(w,m.bools)||A(w,m.counts)){if(typeof $==="string")$=$==="true"}let P=Array.isArray($)?$.map(function(C){return D(w,C)}):D(w,$);if(A(w,m.counts)&&(rt(P)||typeof P==="boolean"))P=jn();if(A(w,m.normalize)&&A(w,m.arrays))if(Array.isArray($))P=$.map((C)=>{return he.normalize(C)});else P=he.normalize($);return P}function D(w,$){if(!s["parse-positional-numbers"]&&w==="_")return $;if(!A(w,m.strings)&&!A(w,m.bools)&&!Array.isArray($)){if(Vo($)&&s["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${$}`)))||!rt($)&&A(w,m.numbers))$=Number($)}return $}function L(w){let $=Object.create(null);z($,m.aliases,c),Object.keys(m.configs).forEach(function(W){let P=w[W]||$[W];if(P)try{let C=null,H=he.resolve(he.cwd(),P),B=m.configs[W];if(typeof B==="function"){try{C=B(H)}catch(v){C=v}if(C instanceof Error){R=C;return}}else C=he.require(H);K(C)}catch(C){if(C.name==="PermissionDenied")R=C;else if(w[W])R=Error(x("Invalid JSON config file: %s",P))}})}function K(w,$){Object.keys(w).forEach(function(W){let P=w[W],C=$?$+"."+W:W;if(typeof P==="object"&&P!==null&&!Array.isArray(P)&&s["dot-notation"])K(P,C);else if(!_(M,C.split("."))||A(C,m.arrays)&&s["combine-arrays"])et(C,P)})}function tt(){if(typeof u<"u")u.forEach(function(w){K(w)})}function mt(w,$){if(typeof a>"u")return;let W=typeof a==="string"?a:"",P=he.env();Object.keys(P).forEach(function(C){if(W===""||C.lastIndexOf(W,0)===0){let H=C.split("__").map(function(B,v){if(v===0)B=B.substring(W.length);return Ge(B)});if(($&&m.configs[H.join(".")]||!$)&&!_(w,H))et(H.join("."),P[C])}})}function q(w){let $,W=new Set;Object.keys(w).forEach(function(P){if(!W.has(P)){if($=A(P,m.coercions),typeof $==="function")try{let C=D(P,$(w[P]));[].concat(m.aliases[P]||[],P).forEach((H)=>{W.add(H),w[H]=C})}catch(C){R=C}}})}function ut(w){return m.keys.forEach(($)=>{if(~$.indexOf("."))return;if(typeof w[$]>"u")w[$]=void 0}),w}function z(w,$,W,P=!1){Object.keys(W).forEach(function(C){if(!_(w,C.split("."))){if(Z(w,C.split("."),W[C]),P)g[C]=!0;($[C]||[]).forEach(function(H){if(_(w,H.split(".")))return;Z(w,H.split("."),W[C])})}})}function _(w,$){let W=w;if(!s["dot-notation"])$=[$.join(".")];$.slice(0,-1).forEach(function(C){W=W[C]||{}});let P=$[$.length-1];if(typeof W!=="object")return!1;else return P in W}function Z(w,$,W){let P=w;if(!s["dot-notation"])$=[$.join(".")];$.slice(0,-1).forEach(function(Pt){if(Pt=zr(Pt),typeof P==="object"&&P[Pt]===void 0)P[Pt]={};if(typeof P[Pt]!=="object"||Array.isArray(P[Pt])){if(Array.isArray(P[Pt]))P[Pt].push({});else P[Pt]=[P[Pt],{}];P=P[Pt][P[Pt].length-1]}else P=P[Pt]});let C=zr($[$.length-1]),H=A($.join("."),m.arrays),B=Array.isArray(W),v=s["duplicate-arguments-array"];if(!v&&A(C,m.nargs)){if(v=!0,!rt(P[C])&&m.nargs[C]===1||Array.isArray(P[C])&&P[C].length===m.nargs[C])P[C]=void 0}if(W===jn())P[C]=jn(P[C]);else if(Array.isArray(P[C]))if(v&&H&&B)P[C]=s["flatten-duplicate-arrays"]?P[C].concat(W):(Array.isArray(P[C][0])?P[C]:[P[C]]).concat([W]);else if(!v&&Boolean(H)===Boolean(B))P[C]=W;else P[C]=P[C].concat([W]);else if(P[C]===void 0&&H)P[C]=B?W:[W];else if(v&&!(P[C]===void 0||A(C,m.counts)||A(C,m.bools)))P[C]=[P[C],W];else P[C]=W}function dt(...w){w.forEach(function($){Object.keys($||{}).forEach(function(W){if(m.aliases[W])return;m.aliases[W]=[].concat(i[W]||[]),m.aliases[W].concat(W).forEach(function(P){if(/-/.test(P)&&s["camel-case-expansion"]){let C=Ge(P);if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].concat(W).forEach(function(P){if(P.length>1&&/[A-Z]/.test(P)&&s["camel-case-expansion"]){let C=Ko(P,"-");if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].forEach(function(P){m.aliases[P]=[W].concat(m.aliases[W].filter(function(C){return P!==C}))})})})}function A(w,$){let W=[].concat(m.aliases[w]||[],w),P=Object.keys($),C=W.find((H)=>P.includes(H));return C?$[C]:!1}function te(w){let $=Object.keys(m);return[].concat($.map((P)=>m[P])).some(function(P){return Array.isArray(P)?P.includes(w):P[w]})}function $e(w,...$){return[].concat(...$).some(function(P){let C=w.match(P);return C&&te(C[1])})}function F(w){if(w.match(b)||!w.match(/^-[^-]+/))return!1;let $=!0,W,P=w.slice(1).split("");for(let C=0;C<P.length;C++){if(W=w.slice(C+2),!te(P[C])){$=!1;break}if(P[C+1]&&P[C+1]==="="||W==="-"||/[A-Za-z]/.test(P[C])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(W)||P[C+1]&&P[C+1].match(/\W/))break}return $}function nt(w){return s["unknown-options-as-args"]&&pt(w)}function pt(w){if(w=w.replace(/^-{3,}/,"--"),w.match(b))return!1;if(F(w))return!1;return!$e(w,/^-+([^=]+?)=[\s\S]*$/,S,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function U(w){if(!A(w,m.bools)&&!A(w,m.counts)&&`${w}`in c)return c[w];else return Q(ft(w))}function Q(w){return{[Jt.BOOLEAN]:!0,[Jt.STRING]:"",[Jt.NUMBER]:void 0,[Jt.ARRAY]:[]}[w]}function ft(w){let $=Jt.BOOLEAN;if(A(w,m.strings))$=Jt.STRING;else if(A(w,m.numbers))$=Jt.NUMBER;else if(A(w,m.bools))$=Jt.BOOLEAN;else if(A(w,m.arrays))$=Jt.ARRAY;return $}function rt(w){return w===void 0}function so(){Object.keys(m.counts).find((w)=>{if(A(w,m.arrays))return R=Error(x("Invalid configuration: %s, opts.count excludes opts.array.",w)),!0;else if(A(w,m.nargs))return R=Error(x("Invalid configuration: %s, opts.count excludes opts.narg.",w)),!0;return!1})}return{aliases:Object.assign({},m.aliases),argv:Object.assign(it,M),configuration:s,defaulted:Object.assign({},g),error:R,newAliases:Object.assign({},d)}}}function Ta(t){let e=[],o=Object.create(null),n=!0;Object.keys(t).forEach(function(r){e.push([].concat(t[r],r))});while(n){n=!1;for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length;i++)if(e[r].filter(function(c){return e[i].indexOf(c)!==-1}).length){e[r]=e[r].concat(e[i]),e.splice(i,1),n=!0;break}}return e.forEach(function(r){r=r.filter(function(s,c,u){return u.indexOf(s)===c});let i=r.pop();if(i!==void 0&&typeof i==="string")o[i]=r}),o}function jn(t){return t!==void 0?t+1:1}function zr(t){if(t==="__proto__")return"___proto___";return t}function _a(t){return typeof t==="string"&&(t[0]==="'"||t[0]==='"')&&t[t.length-1]===t[0]?t.substring(1,t.length-1):t}var _n,Gn,Hn,vr=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,kr=(Gn=(_n=process===null||process===void 0?void 0:process.versions)===null||_n===void 0?void 0:_n.node)!==null&&Gn!==void 0?Gn:(Hn=process===null||process===void 0?void 0:process.version)===null||Hn===void 0?void 0:Hn.slice(1);if(kr){if(Number(kr.match(/^([^.]+)/)[1])<vr)throw Error(`yargs parser supports a minimum Node.js version of ${vr}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Ja=process?process.env:{},Ur=new Tn({cwd:process.cwd,env:()=>{return Ja},format:Ga,normalize:Ha,resolve:Na,require:(t)=>{return le(t)}}),Mo=function(e,o){return Ur.parse(e.slice(),o).argv};Mo.detailed=function(t,e){return Ur.parse(t.slice(),e)};Mo.camelCase=Ge;Mo.decamelize=Ko;Mo.looksLikeNumber=Vo;var Nn=Mo;import{basename as of,dirname as nf,extname as rf,relative as sf,resolve as Yr}from"path";function Kr(){if(za())return 0;return 1}function za(){return va()&&!process.defaultApp}function va(){return!!process.versions.electron}function Jn(t){return t.slice(Kr()+1)}function Vr(){return process.argv[Kr()]}class lt extends Error{constructor(t){super(t||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,lt)}}import{readFileSync as ka,statSync as Ua,writeFile as Ka}from"fs";import{format as Va}from"util";import{resolve as qa}from"path";var qr={fs:{readFileSync:ka,writeFile:Ka},format:Va,resolve:qa,exists:(t)=>{try{return Ua(t).isFile()}catch(e){return!1}}};var Xt;class Xr{constructor(t){t=t||{},this.directory=t.directory||"./locales",this.updateFiles=typeof t.updateFiles==="boolean"?t.updateFiles:!0,this.locale=t.locale||"en",this.fallbackToLanguage=typeof t.fallbackToLanguage==="boolean"?t.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...t){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let e=t.shift(),o=function(){};if(typeof t[t.length-1]==="function")o=t.pop();if(o=o||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]=e,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o});else o();return Xt.format.apply(Xt.format,[this.cache[this.locale][e]||e].concat(t))}__n(){let t=Array.prototype.slice.call(arguments),e=t.shift(),o=t.shift(),n=t.shift(),r=function(){};if(typeof t[t.length-1]==="function")r=t.pop();if(!this.cache[this.locale])this._readLocaleFile();let i=n===1?e:o;if(this.cache[this.locale][e])i=this.cache[this.locale][e][n===1?"one":"other"];if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]={one:e,other:o},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r});else r();let s=[i];if(~i.indexOf("%d"))s.push(n);return Xt.format.apply(Xt.format,s.concat(t))}setLocale(t){this.locale=t}getLocale(){return this.locale}updateLocale(t){if(!this.cache[this.locale])this._readLocaleFile();for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))this.cache[this.locale][e]=t[e]}_taggedLiteral(t,...e){let o="";return t.forEach(function(n,r){let i=e[r+1];if(o+=n,typeof i<"u")o+="%s"}),this.__.apply(this,[o].concat([].slice.call(e,1)))}_enqueueWrite(t){if(this.writeQueue.push(t),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let t=this,e=this.writeQueue[0],o=e.directory,n=e.locale,r=e.cb,i=this._resolveLocaleFile(o,n),s=JSON.stringify(this.cache[n],null,2);Xt.fs.writeFile(i,s,"utf-8",function(c){if(t.writeQueue.shift(),t.writeQueue.length>0)t._processWriteQueue();r(c)})}_readLocaleFile(){let t={},e=this._resolveLocaleFile(this.directory,this.locale);try{if(Xt.fs.readFileSync)t=JSON.parse(Xt.fs.readFileSync(e,"utf-8"))}catch(o){if(o instanceof SyntaxError)o.message="syntax error in "+e;if(o.code==="ENOENT")t={};else throw o}this.cache[this.locale]=t}_resolveLocaleFile(t,e){let o=Xt.resolve(t,"./",e+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(o)&&~e.lastIndexOf("_")){let n=Xt.resolve(t,"./",e.split("_")[0]+".json");if(this._fileExistsSync(n))o=n}return o}_fileExistsSync(t){return Xt.exists(t)}}function Zr(t,e){Xt=e;let o=new Xr(t);return{__:o.__.bind(o),__n:o.__n.bind(o),setLocale:o.setLocale.bind(o),getLocale:o.getLocale.bind(o),updateLocale:o.updateLocale.bind(o),locale:o.locale}}var Xa=(t)=>{return Zr(t,qr)},Qr=Xa;var cf="require is not supported by ESM",ti="loading a directory of commands is not supported yet for ESM",Oo;try{Oo=ef(import.meta.url)}catch(t){Oo=process.cwd()}var af=Oo.substring(0,Oo.lastIndexOf("node_modules")),zn={assert:{notStrictEqual:Za,strictEqual:Qa},cliui:An,findUp:In,getEnv:(t)=>{return process.env[t]},inspect:Ya,getCallerFile:()=>{throw new lt(ti)},getProcessArgvBin:Vr,mainFilename:af||process.cwd(),Parser:Nn,path:{basename:of,dirname:nf,extname:rf,relative:sf,resolve:Yr},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(t,e)=>process.emitWarning(t,e),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:tf,require:()=>{throw new lt(cf)},requireDirectory:()=>{throw new lt(ti)},stringWidth:(t)=>{return[...t].length},y18n:Qr({directory:Yr(Oo,"../../../locales"),updateFiles:!1})};function Bt(t,e,o,n){o.assert.notStrictEqual(t,e,n)}function vn(t,e){e.assert.strictEqual(typeof t,"string")}function co(t){return Object.keys(t)}function ht(t){return!!t&&!!t.then&&typeof t.then==="function"}function Se(t){let o=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),n=/\.*[\][<>]/g,r=o.shift();if(!r)throw Error(`No command found in: ${t}`);let i={cmd:r.replace(n,""),demanded:[],optional:[]};return o.forEach((s,c)=>{let u=!1;if(s=s.replace(/\s/g,""),/\.+[\]>]/.test(s)&&c===o.length-1)u=!0;if(/^\[/.test(s))i.optional.push({cmd:s.replace(n,"").split("|"),variadic:u});else i.demanded.push({cmd:s.replace(n,"").split("|"),variadic:u})}),i}var ff=["first","second","third","fourth","fifth","sixth"];function I(t,e,o){function n(){return typeof t==="object"?[{demanded:[],optional:[]},t,e]:[Se(`cmd ${t}`),e,o]}try{let r=0,[i,s,c]=n(),u=[].slice.call(s);while(u.length&&u[u.length-1]===void 0)u.pop();let a=c||u.length;if(a<i.demanded.length)throw new lt(`Not enough arguments provided. Expected ${i.demanded.length} but received ${u.length}.`);let l=i.demanded.length+i.optional.length;if(a>l)throw new lt(`Too many arguments provided. Expected max ${l} but received ${a}.`);i.demanded.forEach((h)=>{let d=u.shift(),g=ei(d);if(h.cmd.filter((m)=>m===g||m==="*").length===0)oi(g,h.cmd,r);r+=1}),i.optional.forEach((h)=>{if(u.length===0)return;let d=u.shift(),g=ei(d);if(h.cmd.filter((m)=>m===g||m==="*").length===0)oi(g,h.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function ei(t){if(Array.isArray(t))return"array";else if(t===null)return"null";return typeof t}function oi(t,e,o){throw new lt(`Invalid ${ff[o]||"manyith"} argument. Expected ${e.join(" or ")} but received ${t}.`)}class kn{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,o=!0,n=!1){if(I("<array|function> [boolean] [boolean] [boolean]",[t,e,o],arguments.length),Array.isArray(t)){for(let r=0;r<t.length;r++){if(typeof t[r]!=="function")throw Error("middleware must be a function");let i=t[r];i.applyBeforeValidation=e,i.global=o}Array.prototype.push.apply(this.globalMiddleware,t)}else if(typeof t==="function"){let r=t;r.applyBeforeValidation=e,r.global=o,r.mutates=n,this.globalMiddleware.push(t)}return this.yargs}addCoerceMiddleware(t,e){let o=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((n)=>{let r=[...o[e]||[],e];if(!n.option)return!0;else return!r.includes(n.option)}),t.option=e,this.addMiddleware(t,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let t=this.frozens.pop();if(t!==void 0)this.globalMiddleware=t}reset(){this.globalMiddleware=this.globalMiddleware.filter((t)=>t.global)}}function ni(t){if(!t)return[];return t.map((e)=>{return e.applyBeforeValidation=!1,e})}function He(t,e,o,n){return o.reduce((r,i)=>{if(i.applyBeforeValidation!==n)return r;if(i.mutates){if(i.applied)return r;i.applied=!0}if(ht(r))return r.then((s)=>Promise.all([s,i(s,e)])).then(([s,c])=>Object.assign(s,c));else{let s=i(r,e);return ht(s)?s.then((c)=>Object.assign(r,c)):Object.assign(r,s)}},t)}function Ne(t,e,o=(n)=>{throw n}){try{let n=lf(t)?t():t;return ht(n)?n.then((r)=>e(r)):e(n)}catch(n){return o(n)}}function lf(t){return typeof t==="function"}function Un(t){for(let e=0,o=Object.keys(le.cache),n;e<o.length;e++)if(n=le.cache[o[e]],n.exports===t)return n;return null}var ao=/(^\*)|(^\$0)/;class ii{constructor(t,e,o,n){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=n,this.usage=t,this.globalMiddleware=o,this.validation=e}addDirectory(t,e,o,n){if(n=n||{},typeof n.recurse!=="boolean")n.recurse=!1;if(!Array.isArray(n.extensions))n.extensions=["js"];let r=typeof n.visit==="function"?n.visit:(i)=>i;n.visit=(i,s,c)=>{let u=r(i,s,c);if(u){if(this.requireCache.has(s))return u;else this.requireCache.add(s);this.addHandler(u)}return u},this.shim.requireDirectory({require:e,filename:o},t,n)}addHandler(t,e,o,n,r,i){let s=[],c=ni(r);if(n=n||(()=>{}),Array.isArray(t))if(hf(t))[t,...s]=t;else for(let u of t)this.addHandler(u);else if(pf(t)){let u=Array.isArray(t.command)||typeof t.command==="string"?t.command:this.moduleName(t);if(t.aliases)u=[].concat(u).concat(t.aliases);this.addHandler(u,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated);return}else if(ri(o)){this.addHandler([t].concat(s),e,o.builder,o.handler,o.middlewares,o.deprecated);return}if(typeof t==="string"){let u=Se(t);s=s.map((h)=>Se(h).cmd);let a=!1,l=[u.cmd].concat(s).filter((h)=>{if(ao.test(h))return a=!0,!1;return!0});if(l.length===0&&a)l.push("$0");if(a)u.cmd=l[0],s=l.slice(1),t=t.replace(ao,u.cmd);if(s.forEach((h)=>{this.aliasMap[h]=u.cmd}),e!==!1)this.usage.command(t,e,a,s,i);if(this.handlers[u.cmd]={original:t,description:e,handler:n,builder:o||{},middlewares:c,deprecated:i,demanded:u.demanded,optional:u.optional},a)this.defaultCommand=this.handlers[u.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,o,n,r,i){let s=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,c=e.getInternalMethods().getContext(),u=c.commands.slice(),a=!t;if(t)c.commands.push(t),c.fullCommands.push(s.original);let l=this.applyBuilderUpdateUsageAndParse(a,s,e,o.aliases,u,n,r,i);return ht(l)?l.then((h)=>this.applyMiddlewareAndGetResult(a,s,h.innerArgv,c,r,h.aliases,e)):this.applyMiddlewareAndGetResult(a,s,l.innerArgv,c,r,l.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,o,n,r,i,s,c){let u=e.builder,a=o;if(qo(u)){o.getInternalMethods().getUsageInstance().freeze();let l=u(o.getInternalMethods().reset(n),c);if(ht(l))return l.then((h)=>{return a=ci(h)?h:o,this.parseAndUpdateUsage(t,e,a,r,i,s)})}else if(uf(u))o.getInternalMethods().getUsageInstance().freeze(),a=o.getInternalMethods().reset(n),Object.keys(e.builder).forEach((l)=>{a.option(l,u[l])});return this.parseAndUpdateUsage(t,e,a,r,i,s)}parseAndUpdateUsage(t,e,o,n,r,i){if(t)o.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(o))o.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(n,e),e.description);let s=o.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,i);return ht(s)?s.then((c)=>({aliases:o.parsed.aliases,innerArgv:c})):{aliases:o.parsed.aliases,innerArgv:s}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&t.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(t,e){let o=ao.test(e.original)?e.original.replace(ao,"").trim():e.original,n=t.filter((r)=>{return!ao.test(r)});return n.push(o),`$0 ${n.join(" ")}`}handleValidationAndGetResult(t,e,o,n,r,i,s,c){if(!i.getInternalMethods().getHasOutput()){let u=i.getInternalMethods().runValidation(r,c,i.parsed.error,t);o=Ne(o,(a)=>{return u(a),a})}if(e.handler&&!i.getInternalMethods().getHasOutput()){i.getInternalMethods().setHasOutput();let u=!!i.getOptions().configuration["populate--"];if(i.getInternalMethods().postProcess(o,u,!1,!1),o=He(o,i,s,!1),o=Ne(o,(a)=>{let l=e.handler(a);return ht(l)?l.then(()=>a):a}),!t)i.getInternalMethods().getUsageInstance().cacheHelpMessage();if(ht(o)&&!i.getInternalMethods().hasParseCallback())o.catch((a)=>{try{i.getInternalMethods().getUsageInstance().fail(null,a)}catch(l){}})}if(!t)n.commands.pop(),n.fullCommands.pop();return o}applyMiddlewareAndGetResult(t,e,o,n,r,i,s){let c={};if(r)return o;if(!s.getInternalMethods().getHasOutput())c=this.populatePositionals(e,o,n,s);let u=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares),a=He(o,s,u,!0);return ht(a)?a.then((l)=>this.handleValidationAndGetResult(t,e,l,n,i,s,u,c)):this.handleValidationAndGetResult(t,e,a,n,i,s,u,c)}populatePositionals(t,e,o,n){e._=e._.slice(o.commands.length);let r=t.demanded.slice(0),i=t.optional.slice(0),s={};this.validation.positionalCount(r.length,e._.length);while(r.length){let c=r.shift();this.populatePositional(c,e,s)}while(i.length){let c=i.shift();this.populatePositional(c,e,s)}return e._=o.commands.concat(e._.map((c)=>""+c)),this.postProcessPositionals(e,s,this.cmdToParseOptions(t.original),n),s}populatePositional(t,e,o){let n=t.cmd[0];if(t.variadic)o[n]=e._.splice(0).map(String);else if(e._.length)o[n]=[String(e._.shift())]}cmdToParseOptions(t){let e={array:[],default:{},alias:{},demand:{}},o=Se(t);return o.demanded.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i,e.demand[r]=!0}),o.optional.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i}),e}postProcessPositionals(t,e,o,n){let r=Object.assign({},n.getOptions());r.default=Object.assign(o.default,r.default);for(let u of Object.keys(o.alias))r.alias[u]=(r.alias[u]||[]).concat(o.alias[u]);r.array=r.array.concat(o.array),r.config={};let i=[];if(Object.keys(e).forEach((u)=>{e[u].map((a)=>{if(r.configuration["unknown-options-as-args"])r.key[u]=!0;i.push(`--${u}`),i.push(a)})}),!i.length)return;let s=Object.assign({},r.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(i,Object.assign({},r,{configuration:s}));if(c.error)n.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let u=Object.keys(e);Object.keys(e).forEach((a)=>{u.push(...c.aliases[a])}),Object.keys(c.argv).forEach((a)=>{if(u.includes(a)){if(!e[a])e[a]=c.argv[a];if(!this.isInConfigs(n,a)&&!this.isDefaulted(n,a)&&Object.prototype.hasOwnProperty.call(t,a)&&Object.prototype.hasOwnProperty.call(c.argv,a)&&(Array.isArray(t[a])||Array.isArray(c.argv[a])))t[a]=[].concat(t[a],c.argv[a]);else t[a]=c.argv[a]}})}}isDefaulted(t,e){let{default:o}=t.getOptions();return Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(e))}isInConfigs(t,e){let{configObjects:o}=t.getOptions();return o.some((n)=>Object.prototype.hasOwnProperty.call(n,e))||o.some((n)=>Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(e)))}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){let o=ao.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(o,this.defaultCommand.description)}let e=this.defaultCommand.builder;if(qo(e))return e(t,!0);else if(!ri(e))Object.keys(e).forEach((o)=>{t.option(o,e[o])});return}moduleName(t){let e=Un(t);if(!e)throw Error(`No command name given for module: ${this.shim.inspect(t)}`);return this.commandFromFilename(e.filename)}commandFromFilename(t){return this.shim.path.basename(t,this.shim.path.extname(t))}extractDesc({describe:t,description:e,desc:o}){for(let n of[t,e,o]){if(typeof n==="string"||n===!1)return n;Bt(n,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let t=this.frozens.pop();Bt(t,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=t}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function si(t,e,o,n){return new ii(t,e,o,n)}function ri(t){return typeof t==="object"&&!!t.builder&&typeof t.handler==="function"}function hf(t){return t.every((e)=>typeof e==="string")}function qo(t){return typeof t==="function"}function uf(t){return typeof t==="object"}function pf(t){return typeof t==="object"&&!Array.isArray(t)}function Pe(t={},e=()=>!0){let o={};return co(t).forEach((n)=>{if(e(n,t[n]))o[n]=t[n]}),o}function ye(t){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((e)=>{let o=e;if(o._handle&&o.isTTY&&typeof o._handle.setBlocking==="function")o._handle.setBlocking(t)})}function df(t){return typeof t==="boolean"}function fi(t,e){let o=e.y18n.__,n={},r=[];n.failFn=function(D){r.push(D)};let i=null,s=null,c=!0;n.showHelpOnFail=function(D=!0,L){let[K,tt]=typeof D==="string"?[!0,D]:[D,L];if(t.getInternalMethods().isGlobalContext())s=tt;return i=tt,c=K,n};let u=!1;n.fail=function(D,L){let K=t.getInternalMethods().getLoggerInstance();if(r.length)for(let tt=r.length-1;tt>=0;--tt){let mt=r[tt];if(df(mt)){if(L)throw L;else if(D)throw Error(D)}else mt(D,L,n)}else{if(t.getExitProcess())ye(!0);if(!u){if(u=!0,c)t.showHelp("error"),K.error();if(D||L)K.error(D||L);let tt=i||s;if(tt){if(D||L)K.error("");K.error(tt)}}if(L=L||new lt(D),t.getExitProcess())return t.exit(1);else if(t.getInternalMethods().hasParseCallback())return t.exit(1,L);else throw L}};let a=[],l=!1;n.usage=(T,D)=>{if(T===null)return l=!0,a=[],n;return l=!1,a.push([T,D||""]),n},n.getUsage=()=>{return a},n.getUsageDisabled=()=>{return l},n.getPositionalGroupName=()=>{return o("Positionals:")};let h=[];n.example=(T,D)=>{h.push([T,D||""])};let d=[];n.command=function(D,L,K,tt,mt=!1){if(K)d=d.map((q)=>{return q[2]=!1,q});d.push([D,L||"",K,tt,mt])},n.getCommands=()=>d;let g={};n.describe=function(D,L){if(Array.isArray(D))D.forEach((K)=>{n.describe(K,L)});else if(typeof D==="object")Object.keys(D).forEach((K)=>{n.describe(K,D[K])});else g[D]=L},n.getDescriptions=()=>g;let x=[];n.epilog=(T)=>{x.push(T)};let m=!1,b;n.wrap=(T)=>{m=!0,b=T},n.getWrap=()=>{if(e.getEnv("YARGS_DISABLE_WRAP"))return null;if(!m)b=ot(),m=!0;return b};let S="__yargsString__:";n.deferY18nLookup=(T)=>S+T,n.help=function(){if(M)return M;y();let D=t.customScriptName?t.$0:e.path.basename(t.$0),L=t.getDemandedOptions(),K=t.getDemandedCommands(),tt=t.getDeprecatedOptions(),mt=t.getGroups(),q=t.getOptions(),ut=[];ut=ut.concat(Object.keys(g)),ut=ut.concat(Object.keys(L)),ut=ut.concat(Object.keys(K)),ut=ut.concat(Object.keys(q.default)),ut=ut.filter(st),ut=Object.keys(ut.reduce((F,nt)=>{if(nt!=="_")F[nt]=!0;return F},{}));let z=n.getWrap(),_=e.cliui({width:z,wrap:!!z});if(!l){if(a.length)a.forEach((F)=>{if(_.div({text:`${F[0].replace(/\$0/g,D)}`}),F[1])_.div({text:`${F[1]}`,padding:[1,0,0,0]})}),_.div();else if(d.length){let F=null;if(K._)F=`${D} <${o("command")}>
164
164
  `;else F=`${D} [${o("command")}]
165
- `;T.div(`${F}`)}}if(d.length>1||d.length===1&&!d[0][2]){T.div(o("Commands:"));let F=t.getInternalMethods().getContext(),nt=F.commands.length?`${F.commands.join(" ")} `:"";if(t.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)d=d.sort((U,Q)=>U[0].localeCompare(Q[0]));let pt=D?`${D} `:"";d.forEach((U)=>{let Q=`${pt}${nt}${U[0].replace(/^\$0 ?/,"")}`;T.span({text:Q,padding:[0,2,0,2],width:R(d,z,`${D}${nt}`)+4},{text:U[1]});let ft=[];if(U[2])ft.push(`[${o("default")}]`);if(U[3]&&U[3].length)ft.push(`[${o("aliases:")} ${U[3].join(", ")}]`);if(U[4])if(typeof U[4]==="string")ft.push(`[${o("deprecated: %s",U[4])}]`);else ft.push(`[${o("deprecated")}]`);if(ft.length)T.div({text:ft.join(" "),padding:[0,0,0,2],align:"right"});else T.div()}),T.div()}let Z=(Object.keys(V.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);ut=ut.filter((F)=>!t.parsed.newAliases[F]&&Z.every((nt)=>(V.alias[nt]||[]).indexOf(F)===-1));let dt=o("Options:");if(!mt[dt])mt[dt]=[];st(ut,V.alias,mt,dt);let A=(F)=>/^--/.test(vo(F)),Xt=Object.keys(mt).filter((F)=>mt[F].length>0).map((F)=>{let nt=mt[F].filter(ct).map((pt)=>{if(Z.includes(pt))return pt;for(let U=0,Q;(Q=Z[U])!==void 0;U++)if((V.alias[Q]||[]).includes(pt))return Q;return pt});return{groupName:F,normalizedKeys:nt}}).filter(({normalizedKeys:F})=>F.length>0).map(({groupName:F,normalizedKeys:nt})=>{let pt=nt.reduce((U,Q)=>{return U[Q]=[Q].concat(V.alias[Q]||[]).map((ft)=>{if(F===n.getPositionalGroupName())return ft;else return(/^[0-9]$/.test(ft)?V.boolean.includes(Q)?"-":"--":ft.length>1?"--":"-")+ft}).sort((ft,rt)=>A(ft)===A(rt)?0:A(ft)?1:-1).join(", "),U},{});return{groupName:F,normalizedKeys:nt,switches:pt}});if(Xt.filter(({groupName:F})=>F!==n.getPositionalGroupName()).some(({normalizedKeys:F,switches:nt})=>!F.every((pt)=>A(nt[pt]))))Xt.filter(({groupName:F})=>F!==n.getPositionalGroupName()).forEach(({normalizedKeys:F,switches:nt})=>{F.forEach((pt)=>{if(A(nt[pt]))nt[pt]=xf(nt[pt],4)})});if(Xt.forEach(({groupName:F,normalizedKeys:nt,switches:pt})=>{T.div(F),nt.forEach((U)=>{let Q=pt[U],ft=w[U]||"",rt=null;if(ft.includes(S))ft=o(ft.substring(S.length));if(V.boolean.includes(U))rt=`[${o("boolean")}]`;if(V.count.includes(U))rt=`[${o("count")}]`;if(V.string.includes(U))rt=`[${o("string")}]`;if(V.normalize.includes(U))rt=`[${o("string")}]`;if(V.array.includes(U))rt=`[${o("array")}]`;if(V.number.includes(U))rt=`[${o("number")}]`;let to=(W)=>typeof W==="string"?`[${o("deprecated: %s",W)}]`:`[${o("deprecated")}]`,g=[U in tt?to(tt[U]):null,rt,U in L?`[${o("required")}]`:null,V.choices&&V.choices[U]?`[${o("choices:")} ${n.stringifiedValues(V.choices[U])}]`:null,_(V.default[U],V.defaultDescription[U])].filter(Boolean).join(" ");T.span({text:vo(Q),padding:[0,2,0,2+fi(Q)],width:R(pt,z)+4},ft);let $=t.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(g&&!$)T.div({text:g,padding:[0,0,0,2],align:"right"});else T.div()}),T.div()}),h.length)T.div(o("Examples:")),h.forEach((F)=>{F[0]=F[0].replace(/\$0/g,D)}),h.forEach((F)=>{if(F[1]==="")T.div({text:F[0],padding:[0,2,0,2]});else T.div({text:F[0],padding:[0,2,0,2],width:R(h,z)+4},{text:F[1]})}),T.div();if(x.length>0){let F=x.map((nt)=>nt.replace(/\$0/g,D)).join(`
166
- `);T.div(`${F}
167
- `)}return T.toString().replace(/\s*$/,"")};function R(G,D,L){let K=0;if(!Array.isArray(G))G=Object.values(G).map((tt)=>[tt]);if(G.forEach((tt)=>{K=Math.max(e.stringWidth(L?`${L} ${vo(tt[0])}`:vo(tt[0]))+fi(tt[0]),K)}),D)K=Math.min(K,parseInt((D*0.5).toString(),10));return K}function P(){let G=t.getDemandedOptions(),D=t.getOptions();(Object.keys(D.alias)||[]).forEach((L)=>{D.alias[L].forEach((K)=>{if(w[K])n.describe(L,w[K]);if(K in G)t.demandOption(L,G[K]);if(D.boolean.includes(K))t.boolean(L);if(D.count.includes(K))t.count(L);if(D.string.includes(K))t.string(L);if(D.normalize.includes(K))t.normalize(L);if(D.array.includes(K))t.array(L);if(D.number.includes(K))t.number(L)})})}let M;n.cacheHelpMessage=function(){M=this.help()},n.clearCachedHelpMessage=function(){M=void 0},n.hasCachedHelpMessage=function(){return!!M};function st(G,D,L,K){let tt=[],mt=null;return Object.keys(L).forEach((V)=>{tt=tt.concat(L[V])}),G.forEach((V)=>{if(mt=[V].concat(D[V]),!mt.some((ut)=>tt.indexOf(ut)!==-1))L[K].push(V)}),tt}function ct(G){return t.getOptions().hiddenOptions.indexOf(G)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}n.showHelp=(G)=>{let D=t.getInternalMethods().getLoggerInstance();if(!G)G="error";(typeof G==="function"?G:D[G])(n.help())},n.functionDescription=(G)=>{return["(",G.name?e.Parser.decamelize(G.name,"-"):o("generated-value"),")"].join("")},n.stringifiedValues=function(D,L){let K="",tt=L||", ",mt=[].concat(D);if(!D||!mt.length)return K;return mt.forEach((V)=>{if(K.length)K+=tt;K+=JSON.stringify(V)}),K};function _(G,D){let L=`[${o("default:")} `;if(G===void 0&&!D)return null;if(D)L+=D;else switch(typeof G){case"string":L+=`"${G}"`;break;case"object":L+=JSON.stringify(G);break;default:L+=G}return`${L}]`}function ot(){if(e.process.stdColumns)return Math.min(80,e.process.stdColumns);else return 80}let et=null;n.version=(G)=>{et=G},n.showVersion=(G)=>{let D=t.getInternalMethods().getLoggerInstance();if(!G)G="error";(typeof G==="function"?G:D[G])(et)},n.reset=function(D){return i=null,f=!1,a=[],u=!1,x=[],h=[],d=[],w=ge(w,(L)=>!D[L]),n};let re=[];return n.freeze=function(){re.push({failMessage:i,failureOutput:f,usages:a,usageDisabled:u,epilogs:x,examples:h,commands:d,descriptions:w})},n.unfreeze=function(D=!1){let L=re.pop();if(!L)return;if(D)w={...L.descriptions,...w},d=[...L.commands,...d],a=[...L.usages,...a],h=[...L.examples,...h],x=[...L.epilogs,...x];else({failMessage:i,failureOutput:f,usages:a,usageDisabled:u,epilogs:x,examples:h,commands:d,descriptions:w}=L)},n}function vn(t){return typeof t==="object"}function xf(t,e){return vn(t)?{text:t.text,indentation:t.indentation+e}:{text:t,indentation:e}}function fi(t){return vn(t)?t.indentation:0}function vo(t){return vn(t)?t.text:t}var hi=`###-begin-{{app_name}}-completions-###
165
+ `;_.div(`${F}`)}}if(d.length>1||d.length===1&&!d[0][2]){_.div(o("Commands:"));let F=t.getInternalMethods().getContext(),nt=F.commands.length?`${F.commands.join(" ")} `:"";if(t.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)d=d.sort((U,Q)=>U[0].localeCompare(Q[0]));let pt=D?`${D} `:"";d.forEach((U)=>{let Q=`${pt}${nt}${U[0].replace(/^\$0 ?/,"")}`;_.span({text:Q,padding:[0,2,0,2],width:R(d,z,`${D}${nt}`)+4},{text:U[1]});let ft=[];if(U[2])ft.push(`[${o("default")}]`);if(U[3]&&U[3].length)ft.push(`[${o("aliases:")} ${U[3].join(", ")}]`);if(U[4])if(typeof U[4]==="string")ft.push(`[${o("deprecated: %s",U[4])}]`);else ft.push(`[${o("deprecated")}]`);if(ft.length)_.div({text:ft.join(" "),padding:[0,0,0,2],align:"right"});else _.div()}),_.div()}let Z=(Object.keys(q.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);ut=ut.filter((F)=>!t.parsed.newAliases[F]&&Z.every((nt)=>(q.alias[nt]||[]).indexOf(F)===-1));let dt=o("Options:");if(!mt[dt])mt[dt]=[];it(ut,q.alias,mt,dt);let A=(F)=>/^--/.test(Xo(F)),te=Object.keys(mt).filter((F)=>mt[F].length>0).map((F)=>{let nt=mt[F].filter(st).map((pt)=>{if(Z.includes(pt))return pt;for(let U=0,Q;(Q=Z[U])!==void 0;U++)if((q.alias[Q]||[]).includes(pt))return Q;return pt});return{groupName:F,normalizedKeys:nt}}).filter(({normalizedKeys:F})=>F.length>0).map(({groupName:F,normalizedKeys:nt})=>{let pt=nt.reduce((U,Q)=>{return U[Q]=[Q].concat(q.alias[Q]||[]).map((ft)=>{if(F===n.getPositionalGroupName())return ft;else return(/^[0-9]$/.test(ft)?q.boolean.includes(Q)?"-":"--":ft.length>1?"--":"-")+ft}).sort((ft,rt)=>A(ft)===A(rt)?0:A(ft)?1:-1).join(", "),U},{});return{groupName:F,normalizedKeys:nt,switches:pt}});if(te.filter(({groupName:F})=>F!==n.getPositionalGroupName()).some(({normalizedKeys:F,switches:nt})=>!F.every((pt)=>A(nt[pt]))))te.filter(({groupName:F})=>F!==n.getPositionalGroupName()).forEach(({normalizedKeys:F,switches:nt})=>{F.forEach((pt)=>{if(A(nt[pt]))nt[pt]=mf(nt[pt],4)})});if(te.forEach(({groupName:F,normalizedKeys:nt,switches:pt})=>{_.div(F),nt.forEach((U)=>{let Q=pt[U],ft=g[U]||"",rt=null;if(ft.includes(S))ft=o(ft.substring(S.length));if(q.boolean.includes(U))rt=`[${o("boolean")}]`;if(q.count.includes(U))rt=`[${o("count")}]`;if(q.string.includes(U))rt=`[${o("string")}]`;if(q.normalize.includes(U))rt=`[${o("string")}]`;if(q.array.includes(U))rt=`[${o("array")}]`;if(q.number.includes(U))rt=`[${o("number")}]`;let so=(W)=>typeof W==="string"?`[${o("deprecated: %s",W)}]`:`[${o("deprecated")}]`,w=[U in tt?so(tt[U]):null,rt,U in L?`[${o("required")}]`:null,q.choices&&q.choices[U]?`[${o("choices:")} ${n.stringifiedValues(q.choices[U])}]`:null,G(q.default[U],q.defaultDescription[U])].filter(Boolean).join(" ");_.span({text:Xo(Q),padding:[0,2,0,2+ai(Q)],width:R(pt,z)+4},ft);let $=t.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(w&&!$)_.div({text:w,padding:[0,0,0,2],align:"right"});else _.div()}),_.div()}),h.length)_.div(o("Examples:")),h.forEach((F)=>{F[0]=F[0].replace(/\$0/g,D)}),h.forEach((F)=>{if(F[1]==="")_.div({text:F[0],padding:[0,2,0,2]});else _.div({text:F[0],padding:[0,2,0,2],width:R(h,z)+4},{text:F[1]})}),_.div();if(x.length>0){let F=x.map((nt)=>nt.replace(/\$0/g,D)).join(`
166
+ `);_.div(`${F}
167
+ `)}return _.toString().replace(/\s*$/,"")};function R(T,D,L){let K=0;if(!Array.isArray(T))T=Object.values(T).map((tt)=>[tt]);if(T.forEach((tt)=>{K=Math.max(e.stringWidth(L?`${L} ${Xo(tt[0])}`:Xo(tt[0]))+ai(tt[0]),K)}),D)K=Math.min(K,parseInt((D*0.5).toString(),10));return K}function y(){let T=t.getDemandedOptions(),D=t.getOptions();(Object.keys(D.alias)||[]).forEach((L)=>{D.alias[L].forEach((K)=>{if(g[K])n.describe(L,g[K]);if(K in T)t.demandOption(L,T[K]);if(D.boolean.includes(K))t.boolean(L);if(D.count.includes(K))t.count(L);if(D.string.includes(K))t.string(L);if(D.normalize.includes(K))t.normalize(L);if(D.array.includes(K))t.array(L);if(D.number.includes(K))t.number(L)})})}let M;n.cacheHelpMessage=function(){M=this.help()},n.clearCachedHelpMessage=function(){M=void 0},n.hasCachedHelpMessage=function(){return!!M};function it(T,D,L,K){let tt=[],mt=null;return Object.keys(L).forEach((q)=>{tt=tt.concat(L[q])}),T.forEach((q)=>{if(mt=[q].concat(D[q]),!mt.some((ut)=>tt.indexOf(ut)!==-1))L[K].push(q)}),tt}function st(T){return t.getOptions().hiddenOptions.indexOf(T)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}n.showHelp=(T)=>{let D=t.getInternalMethods().getLoggerInstance();if(!T)T="error";(typeof T==="function"?T:D[T])(n.help())},n.functionDescription=(T)=>{return["(",T.name?e.Parser.decamelize(T.name,"-"):o("generated-value"),")"].join("")},n.stringifiedValues=function(D,L){let K="",tt=L||", ",mt=[].concat(D);if(!D||!mt.length)return K;return mt.forEach((q)=>{if(K.length)K+=tt;K+=JSON.stringify(q)}),K};function G(T,D){let L=`[${o("default:")} `;if(T===void 0&&!D)return null;if(D)L+=D;else switch(typeof T){case"string":L+=`"${T}"`;break;case"object":L+=JSON.stringify(T);break;default:L+=T}return`${L}]`}function ot(){if(e.process.stdColumns)return Math.min(80,e.process.stdColumns);else return 80}let et=null;n.version=(T)=>{et=T},n.showVersion=(T)=>{let D=t.getInternalMethods().getLoggerInstance();if(!T)T="error";(typeof T==="function"?T:D[T])(et)},n.reset=function(D){return i=null,u=!1,a=[],l=!1,x=[],h=[],d=[],g=Pe(g,(L)=>!D[L]),n};let fe=[];return n.freeze=function(){fe.push({failMessage:i,failureOutput:u,usages:a,usageDisabled:l,epilogs:x,examples:h,commands:d,descriptions:g})},n.unfreeze=function(D=!1){let L=fe.pop();if(!L)return;if(D)g={...L.descriptions,...g},d=[...L.commands,...d],a=[...L.usages,...a],h=[...L.examples,...h],x=[...L.epilogs,...x];else({failMessage:i,failureOutput:u,usages:a,usageDisabled:l,epilogs:x,examples:h,commands:d,descriptions:g}=L)},n}function Kn(t){return typeof t==="object"}function mf(t,e){return Kn(t)?{text:t.text,indentation:t.indentation+e}:{text:t,indentation:e}}function ai(t){return Kn(t)?t.indentation:0}function Xo(t){return Kn(t)?t.text:t}var li=`###-begin-{{app_name}}-completions-###
168
168
  #
169
169
  # yargs command completion script
170
170
  #
@@ -192,7 +192,7 @@ _{{app_name}}_yargs_completions()
192
192
  }
193
193
  complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
194
194
  ###-end-{{app_name}}-completions-###
195
- `,ui=`#compdef {{app_name}}
195
+ `,hi=`#compdef {{app_name}}
196
196
  ###-begin-{{app_name}}-completions-###
197
197
  #
198
198
  # yargs command completion script
@@ -211,11 +211,11 @@ _{{app_name}}_yargs_completions()
211
211
  }
212
212
  compdef _{{app_name}}_yargs_completions {{app_name}}
213
213
  ###-end-{{app_name}}-completions-###
214
- `;class pi{constructor(t,e,o,n){var r,i,s;this.yargs=t,this.usage=e,this.command=o,this.shim=n,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(s=((r=this.shim.getEnv("SHELL"))===null||r===void 0?void 0:r.includes("zsh"))||((i=this.shim.getEnv("ZSH_NAME"))===null||i===void 0?void 0:i.includes("zsh")))!==null&&s!==void 0?s:!1}defaultCompletion(t,e,o,n){let r=this.command.getCommandHandlers();for(let s=0,c=t.length;s<c;++s)if(r[t[s]]&&r[t[s]].builder){let f=r[t[s]].builder;if(zo(f)){this.indexAfterLastReset=s+1;let a=this.yargs.getInternalMethods().reset();return f(a,!0),a.argv}}let i=[];this.commandCompletions(i,t,o),this.optionCompletions(i,t,e,o),this.choicesFromOptionsCompletions(i,t,e,o),this.choicesFromPositionalsCompletions(i,t,e,o),n(null,i)}commandCompletions(t,e,o){let n=this.yargs.getInternalMethods().getContext().commands;if(!o.match(/^-/)&&n[n.length-1]!==o&&!this.previousArgHasChoices(e))this.usage.getCommands().forEach((r)=>{let i=we(r[0]).cmd;if(e.indexOf(i)===-1)if(!this.zshShell)t.push(i);else{let s=r[1]||"";t.push(i.replace(/:/g,"\\:")+":"+s)}})}optionCompletions(t,e,o,n){if((n.match(/^-/)||n===""&&t.length===0)&&!this.previousArgHasChoices(e)){let r=this.yargs.getOptions(),i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((s)=>{let c=!!r.configuration["boolean-negation"]&&r.boolean.includes(s);if(!i.includes(s)&&!r.hiddenOptions.includes(s)&&!this.argsContainKey(e,s,c))this.completeOptionKey(s,t,n,c&&!!r.default[s])})}}choicesFromOptionsCompletions(t,e,o,n){if(this.previousArgHasChoices(e)){let r=this.getPreviousArgChoices(e);if(r&&r.length>0)t.push(...r.map((i)=>i.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(t,e,o,n){if(n===""&&t.length>0&&this.previousArgHasChoices(e))return;let r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],i=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),s=r[o._.length-i-1];if(!s)return;let c=this.yargs.getOptions().choices[s]||[];for(let f of c)if(f.startsWith(n))t.push(f.replace(/:/g,"\\:"))}getPreviousArgChoices(t){if(t.length<1)return;let e=t[t.length-1],o="";if(!e.startsWith("-")&&t.length>1)o=e,e=t[t.length-2];if(!e.startsWith("-"))return;let n=e.replace(/^-+/,""),r=this.yargs.getOptions(),i=[n,...this.yargs.getAliases()[n]||[]],s;for(let c of i)if(Object.prototype.hasOwnProperty.call(r.key,c)&&Array.isArray(r.choices[c])){s=r.choices[c];break}if(s)return s.filter((c)=>!o||c.startsWith(o))}previousArgHasChoices(t){let e=this.getPreviousArgChoices(t);return e!==void 0&&e.length>0}argsContainKey(t,e,o){let n=(r)=>t.indexOf((/^[^0-9]$/.test(r)?"-":"--")+r)!==-1;if(n(e))return!0;if(o&&n(`no-${e}`))return!0;if(this.aliases){for(let r of this.aliases[e])if(n(r))return!0}return!1}completeOptionKey(t,e,o,n){var r,i,s,c;let f=t;if(this.zshShell){let d=this.usage.getDescriptions(),w=(i=(r=this===null||this===void 0?void 0:this.aliases)===null||r===void 0?void 0:r[t])===null||i===void 0?void 0:i.find((b)=>{let S=d[b];return typeof S==="string"&&S.length>0}),x=w?d[w]:void 0,m=(c=(s=d[t])!==null&&s!==void 0?s:x)!==null&&c!==void 0?c:"";f=`${t.replace(/:/g,"\\:")}:${m.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let a=(d)=>/^--/.test(d),u=(d)=>/^[^0-9]$/.test(d),h=!a(o)&&u(t)?"-":"--";if(e.push(h+f),n)e.push(h+"no-"+f)}customCompletion(t,e,o,n){if(Ft(this.customCompletionFunction,null,this.shim),gf(this.customCompletionFunction)){let r=this.customCompletionFunction(o,e);if(ht(r))return r.then((i)=>{this.shim.process.nextTick(()=>{n(null,i)})}).catch((i)=>{this.shim.process.nextTick(()=>{n(i,void 0)})});return n(null,r)}else if(bf(this.customCompletionFunction))return this.customCompletionFunction(o,e,(r=n)=>this.defaultCompletion(t,e,o,r),(r)=>{n(null,r)});else return this.customCompletionFunction(o,e,(r)=>{n(null,r)})}getCompletion(t,e){let o=t.length?t[t.length-1]:"",n=this.yargs.parse(t,!0),r=this.customCompletionFunction?(i)=>this.customCompletion(t,i,o,e):(i)=>this.defaultCompletion(t,i,o,e);return ht(n)?n.then(r):r(n)}generateCompletionScript(t,e){let o=this.zshShell?ui:hi,n=this.shim.path.basename(t);if(t.match(/\.js$/))t=`./${t}`;return o=o.replace(/{{app_name}}/g,n),o=o.replace(/{{completion_command}}/g,e),o.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function di(t,e,o,n){return new pi(t,e,o,n)}function gf(t){return t.length<3}function bf(t){return t.length>3}function mi(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let o=[],n;for(n=0;n<=e.length;n++)o[n]=[n];let r;for(r=0;r<=t.length;r++)o[0][r]=r;for(n=1;n<=e.length;n++)for(r=1;r<=t.length;r++)if(e.charAt(n-1)===t.charAt(r-1))o[n][r]=o[n-1][r-1];else if(n>1&&r>1&&e.charAt(n-2)===t.charAt(r-1)&&e.charAt(n-1)===t.charAt(r-2))o[n][r]=o[n-2][r-2]+1;else o[n][r]=Math.min(o[n-1][r-1]+1,Math.min(o[n][r-1]+1,o[n-1][r]+1));return o[e.length][t.length]}var xi=["$0","--","_"];function wi(t,e,o){let n=o.y18n.__,r=o.y18n.__n,i={};i.nonOptionCount=function(h){let d=t.getDemandedCommands(),x=h._.length+(h["--"]?h["--"].length:0)-t.getInternalMethods().getContext().commands.length;if(d._&&(x<d._.min||x>d._.max)){if(x<d._.min)if(d._.minMsg!==void 0)e.fail(d._.minMsg?d._.minMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.min.toString()):null);else e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",x,x.toString(),d._.min.toString()));else if(x>d._.max)if(d._.maxMsg!==void 0)e.fail(d._.maxMsg?d._.maxMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.max.toString()):null);else e.fail(r("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",x,x.toString(),d._.max.toString()))}},i.positionalCount=function(h,d){if(d<h)e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",d,d+"",h+""))},i.requiredArguments=function(h,d){let w=null;for(let x of Object.keys(d))if(!Object.prototype.hasOwnProperty.call(h,x)||typeof h[x]>"u")w=w||{},w[x]=d[x];if(w){let x=[];for(let b of Object.keys(w)){let S=w[b];if(S&&x.indexOf(S)<0)x.push(S)}let m=x.length?`
214
+ `;class ui{constructor(t,e,o,n){var r,i,s;this.yargs=t,this.usage=e,this.command=o,this.shim=n,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(s=((r=this.shim.getEnv("SHELL"))===null||r===void 0?void 0:r.includes("zsh"))||((i=this.shim.getEnv("ZSH_NAME"))===null||i===void 0?void 0:i.includes("zsh")))!==null&&s!==void 0?s:!1}defaultCompletion(t,e,o,n){let r=this.command.getCommandHandlers();for(let s=0,c=t.length;s<c;++s)if(r[t[s]]&&r[t[s]].builder){let u=r[t[s]].builder;if(qo(u)){this.indexAfterLastReset=s+1;let a=this.yargs.getInternalMethods().reset();return u(a,!0),a.argv}}let i=[];this.commandCompletions(i,t,o),this.optionCompletions(i,t,e,o),this.choicesFromOptionsCompletions(i,t,e,o),this.choicesFromPositionalsCompletions(i,t,e,o),n(null,i)}commandCompletions(t,e,o){let n=this.yargs.getInternalMethods().getContext().commands;if(!o.match(/^-/)&&n[n.length-1]!==o&&!this.previousArgHasChoices(e))this.usage.getCommands().forEach((r)=>{let i=Se(r[0]).cmd;if(e.indexOf(i)===-1)if(!this.zshShell)t.push(i);else{let s=r[1]||"";t.push(i.replace(/:/g,"\\:")+":"+s)}})}optionCompletions(t,e,o,n){if((n.match(/^-/)||n===""&&t.length===0)&&!this.previousArgHasChoices(e)){let r=this.yargs.getOptions(),i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((s)=>{let c=!!r.configuration["boolean-negation"]&&r.boolean.includes(s);if(!i.includes(s)&&!r.hiddenOptions.includes(s)&&!this.argsContainKey(e,s,c))this.completeOptionKey(s,t,n,c&&!!r.default[s])})}}choicesFromOptionsCompletions(t,e,o,n){if(this.previousArgHasChoices(e)){let r=this.getPreviousArgChoices(e);if(r&&r.length>0)t.push(...r.map((i)=>i.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(t,e,o,n){if(n===""&&t.length>0&&this.previousArgHasChoices(e))return;let r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],i=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),s=r[o._.length-i-1];if(!s)return;let c=this.yargs.getOptions().choices[s]||[];for(let u of c)if(u.startsWith(n))t.push(u.replace(/:/g,"\\:"))}getPreviousArgChoices(t){if(t.length<1)return;let e=t[t.length-1],o="";if(!e.startsWith("-")&&t.length>1)o=e,e=t[t.length-2];if(!e.startsWith("-"))return;let n=e.replace(/^-+/,""),r=this.yargs.getOptions(),i=[n,...this.yargs.getAliases()[n]||[]],s;for(let c of i)if(Object.prototype.hasOwnProperty.call(r.key,c)&&Array.isArray(r.choices[c])){s=r.choices[c];break}if(s)return s.filter((c)=>!o||c.startsWith(o))}previousArgHasChoices(t){let e=this.getPreviousArgChoices(t);return e!==void 0&&e.length>0}argsContainKey(t,e,o){let n=(r)=>t.indexOf((/^[^0-9]$/.test(r)?"-":"--")+r)!==-1;if(n(e))return!0;if(o&&n(`no-${e}`))return!0;if(this.aliases){for(let r of this.aliases[e])if(n(r))return!0}return!1}completeOptionKey(t,e,o,n){var r,i,s,c;let u=t;if(this.zshShell){let d=this.usage.getDescriptions(),g=(i=(r=this===null||this===void 0?void 0:this.aliases)===null||r===void 0?void 0:r[t])===null||i===void 0?void 0:i.find((b)=>{let S=d[b];return typeof S==="string"&&S.length>0}),x=g?d[g]:void 0,m=(c=(s=d[t])!==null&&s!==void 0?s:x)!==null&&c!==void 0?c:"";u=`${t.replace(/:/g,"\\:")}:${m.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let a=(d)=>/^--/.test(d),l=(d)=>/^[^0-9]$/.test(d),h=!a(o)&&l(t)?"-":"--";if(e.push(h+u),n)e.push(h+"no-"+u)}customCompletion(t,e,o,n){if(Bt(this.customCompletionFunction,null,this.shim),gf(this.customCompletionFunction)){let r=this.customCompletionFunction(o,e);if(ht(r))return r.then((i)=>{this.shim.process.nextTick(()=>{n(null,i)})}).catch((i)=>{this.shim.process.nextTick(()=>{n(i,void 0)})});return n(null,r)}else if(wf(this.customCompletionFunction))return this.customCompletionFunction(o,e,(r=n)=>this.defaultCompletion(t,e,o,r),(r)=>{n(null,r)});else return this.customCompletionFunction(o,e,(r)=>{n(null,r)})}getCompletion(t,e){let o=t.length?t[t.length-1]:"",n=this.yargs.parse(t,!0),r=this.customCompletionFunction?(i)=>this.customCompletion(t,i,o,e):(i)=>this.defaultCompletion(t,i,o,e);return ht(n)?n.then(r):r(n)}generateCompletionScript(t,e){let o=this.zshShell?hi:li,n=this.shim.path.basename(t);if(t.match(/\.js$/))t=`./${t}`;return o=o.replace(/{{app_name}}/g,n),o=o.replace(/{{completion_command}}/g,e),o.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function pi(t,e,o,n){return new ui(t,e,o,n)}function gf(t){return t.length<3}function wf(t){return t.length>3}function di(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let o=[],n;for(n=0;n<=e.length;n++)o[n]=[n];let r;for(r=0;r<=t.length;r++)o[0][r]=r;for(n=1;n<=e.length;n++)for(r=1;r<=t.length;r++)if(e.charAt(n-1)===t.charAt(r-1))o[n][r]=o[n-1][r-1];else if(n>1&&r>1&&e.charAt(n-2)===t.charAt(r-1)&&e.charAt(n-1)===t.charAt(r-2))o[n][r]=o[n-2][r-2]+1;else o[n][r]=Math.min(o[n-1][r-1]+1,Math.min(o[n][r-1]+1,o[n-1][r]+1));return o[e.length][t.length]}var mi=["$0","--","_"];function xi(t,e,o){let n=o.y18n.__,r=o.y18n.__n,i={};i.nonOptionCount=function(h){let d=t.getDemandedCommands(),x=h._.length+(h["--"]?h["--"].length:0)-t.getInternalMethods().getContext().commands.length;if(d._&&(x<d._.min||x>d._.max)){if(x<d._.min)if(d._.minMsg!==void 0)e.fail(d._.minMsg?d._.minMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.min.toString()):null);else e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",x,x.toString(),d._.min.toString()));else if(x>d._.max)if(d._.maxMsg!==void 0)e.fail(d._.maxMsg?d._.maxMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.max.toString()):null);else e.fail(r("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",x,x.toString(),d._.max.toString()))}},i.positionalCount=function(h,d){if(d<h)e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",d,d+"",h+""))},i.requiredArguments=function(h,d){let g=null;for(let x of Object.keys(d))if(!Object.prototype.hasOwnProperty.call(h,x)||typeof h[x]>"u")g=g||{},g[x]=d[x];if(g){let x=[];for(let b of Object.keys(g)){let S=g[b];if(S&&x.indexOf(S)<0)x.push(S)}let m=x.length?`
215
215
  ${x.join(`
216
- `)}`:"";e.fail(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(w).length,Object.keys(w).join(", ")+m))}},i.unknownArguments=function(h,d,w,x,m=!0){var b;let S=t.getInternalMethods().getCommandInstance().getCommands(),R=[],P=t.getInternalMethods().getContext();if(Object.keys(h).forEach((M)=>{if(!xi.includes(M)&&!Object.prototype.hasOwnProperty.call(w,M)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),M)&&!i.isValidAndSomeAliasIsNotNew(M,d))R.push(M)}),m&&(P.commands.length>0||S.length>0||x))h._.slice(P.commands.length).forEach((M)=>{if(!S.includes(""+M))R.push(""+M)});if(m){let st=((b=t.getDemandedCommands()._)===null||b===void 0?void 0:b.max)||0,ct=P.commands.length+st;if(ct<h._.length)h._.slice(ct).forEach((_)=>{if(_=String(_),!P.commands.includes(_)&&!R.includes(_))R.push(_)})}if(R.length)e.fail(r("Unknown argument: %s","Unknown arguments: %s",R.length,R.map((M)=>M.trim()?M:`"${M}"`).join(", ")))},i.unknownCommands=function(h){let d=t.getInternalMethods().getCommandInstance().getCommands(),w=[],x=t.getInternalMethods().getContext();if(x.commands.length>0||d.length>0)h._.slice(x.commands.length).forEach((m)=>{if(!d.includes(""+m))w.push(""+m)});if(w.length>0)return e.fail(r("Unknown command: %s","Unknown commands: %s",w.length,w.join(", "))),!0;else return!1},i.isValidAndSomeAliasIsNotNew=function(h,d){if(!Object.prototype.hasOwnProperty.call(d,h))return!1;let w=t.parsed.newAliases;return[h,...d[h]].some((x)=>!Object.prototype.hasOwnProperty.call(w,x)||!w[h])},i.limitedChoices=function(h){let d=t.getOptions(),w={};if(!Object.keys(d.choices).length)return;Object.keys(h).forEach((b)=>{if(xi.indexOf(b)===-1&&Object.prototype.hasOwnProperty.call(d.choices,b))[].concat(h[b]).forEach((S)=>{if(d.choices[b].indexOf(S)===-1&&S!==void 0)w[b]=(w[b]||[]).concat(S)})});let x=Object.keys(w);if(!x.length)return;let m=n("Invalid values:");x.forEach((b)=>{m+=`
217
- ${n("Argument: %s, Given: %s, Choices: %s",b,e.stringifiedValues(w[b]),e.stringifiedValues(d.choices[b]))}`}),e.fail(m)};let s={};i.implies=function(h,d){if(I("<string|object> [array|number|string]",[h,d],arguments.length),typeof h==="object")Object.keys(h).forEach((w)=>{i.implies(w,h[w])});else{if(t.global(h),!s[h])s[h]=[];if(Array.isArray(d))d.forEach((w)=>i.implies(h,w));else Ft(d,void 0,o),s[h].push(d)}},i.getImplied=function(){return s};function c(u,h){let d=Number(h);if(h=isNaN(d)?h:d,typeof h==="number")h=u._.length>=h;else if(h.match(/^--no-.+/))h=h.match(/^--no-(.+)/)[1],h=!Object.prototype.hasOwnProperty.call(u,h);else h=Object.prototype.hasOwnProperty.call(u,h);return h}i.implications=function(h){let d=[];if(Object.keys(s).forEach((w)=>{let x=w;(s[w]||[]).forEach((m)=>{let b=x,S=m;if(b=c(h,b),m=c(h,m),b&&!m)d.push(` ${x} -> ${S}`)})}),d.length){let w=`${n("Implications failed:")}
218
- `;d.forEach((x)=>{w+=x}),e.fail(w)}};let f={};i.conflicts=function(h,d){if(I("<string|object> [array|string]",[h,d],arguments.length),typeof h==="object")Object.keys(h).forEach((w)=>{i.conflicts(w,h[w])});else{if(t.global(h),!f[h])f[h]=[];if(Array.isArray(d))d.forEach((w)=>i.conflicts(h,w));else f[h].push(d)}},i.getConflicting=()=>f,i.conflicting=function(h){if(Object.keys(h).forEach((d)=>{if(f[d])f[d].forEach((w)=>{if(w&&h[d]!==void 0&&h[w]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,w))})}),t.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(f).forEach((d)=>{f[d].forEach((w)=>{if(w&&h[o.Parser.camelCase(d)]!==void 0&&h[o.Parser.camelCase(w)]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,w))})})},i.recommendCommands=function(h,d){d=d.sort((b,S)=>S.length-b.length);let x=null,m=1/0;for(let b=0,S;(S=d[b])!==void 0;b++){let R=mi(h,S);if(R<=3&&R<m)m=R,x=S}if(x)e.fail(n("Did you mean %s?",x))},i.reset=function(h){return s=ge(s,(d)=>!h[d]),f=ge(f,(d)=>!h[d]),i};let a=[];return i.freeze=function(){a.push({implied:s,conflicting:f})},i.unfreeze=function(){let h=a.pop();Ft(h,void 0,o),{implied:s,conflicting:f}=h},i}var kn=[],So;function yo(t,e,o,n){So=n;let r={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if(typeof t.extends!=="string")return r;let i=/\.json|\..*rc$/.test(t.extends),s=null;if(!i)try{s=ie.resolve(t.extends)}catch(c){return t}else s=$f(e,t.extends);Cf(s),kn.push(s),r=i?JSON.parse(So.readFileSync(s,"utf8")):ie(t.extends),delete t.extends,r=yo(r,So.path.dirname(s),o,So)}return kn=[],o?gi(r,t):Object.assign({},r,t)}function Cf(t){if(kn.indexOf(t)>-1)throw new lt(`Circular extended configurations: '${t}'.`)}function $f(t,e){return So.path.resolve(t,e)}function gi(t,e){let o={};function n(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(o,t);for(let r of Object.keys(e))if(n(e[r])&&n(o[r]))o[r]=gi(t[r],e[r]);else o[r]=e[r];return o}var j=function(t,e,o,n,r){if(n==="m")throw TypeError("Private method is not writable");if(n==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof e==="function"?t!==e||!r:!e.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(t,o):r?r.value=o:e.set(t,o),o},p=function(t,e,o,n){if(o==="a"&&!n)throw TypeError("Private accessor was defined without a getter");if(typeof e==="function"?t!==e||!n:!e.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?n:o==="a"?n.call(t):n?n.value:e.get(t)},gt,Ie,Po,Ht,It,ko,Ce,je,Uo,Jt,Ko,zt,Zt,jt,vt,qo,no,Pt,J,Vo,Xo,Gt,Ge,ro,Te,$e,Zo,q,_e,Ne,He,X,Qo,Qt,wt;function Ti(t){return(e=[],o=t.process.cwd(),n)=>{let r=new _i(e,o,n,t);return Object.defineProperty(r,"argv",{get:()=>{return r.parse()},enumerable:!0}),r.help(),r.version(),r}}var bi=Symbol("copyDoubleDash"),Ci=Symbol("copyDoubleDash"),Un=Symbol("deleteFromParserHintObject"),$i=Symbol("emitWarning"),Si=Symbol("freeze"),yi=Symbol("getDollarZero"),Je=Symbol("getParserConfiguration"),Pi=Symbol("getUsageConfiguration"),Kn=Symbol("guessLocale"),Ei=Symbol("guessVersion"),Ri=Symbol("parsePositionalNumbers"),qn=Symbol("pkgUp"),Se=Symbol("populateParserHintArray"),io=Symbol("populateParserHintSingleValueDictionary"),Vn=Symbol("populateParserHintArrayDictionary"),Xn=Symbol("populateParserHintDictionary"),Zn=Symbol("sanitizeKey"),Qn=Symbol("setKey"),Yn=Symbol("unfreeze"),Mi=Symbol("validateAsync"),Oi=Symbol("getCommandInstance"),Wi=Symbol("getContext"),Di=Symbol("getHasOutput"),Fi=Symbol("getLoggerInstance"),Bi=Symbol("getParseContext"),Li=Symbol("getUsageInstance"),Ai=Symbol("getValidationInstance"),Yo=Symbol("hasParseCallback"),Ii=Symbol("isGlobalContext"),ze=Symbol("postProcess"),ji=Symbol("rebase"),tr=Symbol("reset"),Eo=Symbol("runYargsParserAndExecuteCommands"),er=Symbol("runValidation"),Gi=Symbol("setHasOutput"),ve=Symbol("kTrackManuallySetKeys");class _i{constructor(t=[],e,o,n){this.customScriptName=!1,this.parsed=!1,gt.set(this,void 0),Ie.set(this,void 0),Po.set(this,{commands:[],fullCommands:[]}),Ht.set(this,null),It.set(this,null),ko.set(this,"show-hidden"),Ce.set(this,null),je.set(this,!0),Uo.set(this,{}),Jt.set(this,!0),Ko.set(this,[]),zt.set(this,void 0),Zt.set(this,{}),jt.set(this,!1),vt.set(this,null),qo.set(this,!0),no.set(this,void 0),Pt.set(this,""),J.set(this,void 0),Vo.set(this,void 0),Xo.set(this,{}),Gt.set(this,null),Ge.set(this,null),ro.set(this,{}),Te.set(this,{}),$e.set(this,void 0),Zo.set(this,!1),q.set(this,void 0),_e.set(this,!1),Ne.set(this,!1),He.set(this,!1),X.set(this,void 0),Qo.set(this,{}),Qt.set(this,null),wt.set(this,void 0),j(this,q,n,"f"),j(this,$e,t,"f"),j(this,Ie,e,"f"),j(this,Vo,o,"f"),j(this,zt,new Jn(this),"f"),this.$0=this[yi](),this[tr](),j(this,gt,p(this,gt,"f"),"f"),j(this,X,p(this,X,"f"),"f"),j(this,wt,p(this,wt,"f"),"f"),j(this,J,p(this,J,"f"),"f"),p(this,J,"f").showHiddenOpt=p(this,ko,"f"),j(this,no,this[Ci](),"f")}addHelpOpt(t,e){if(I("[string|boolean] [string]",[t,e],arguments.length),p(this,vt,"f"))this[Un](p(this,vt,"f")),j(this,vt,null,"f");if(t===!1&&e===void 0)return this;return j(this,vt,typeof t==="string"?t:"help","f"),this.boolean(p(this,vt,"f")),this.describe(p(this,vt,"f"),e||p(this,X,"f").deferY18nLookup("Show help")),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(I("[string|boolean] [string]",[t,e],arguments.length),t===!1&&e===void 0)return this;let o=typeof t==="string"?t:p(this,ko,"f");return this.boolean(o),this.describe(o,e||p(this,X,"f").deferY18nLookup("Show hidden options")),p(this,J,"f").showHiddenOpt=o,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return I("<object|string|array> [string|array]",[t,e],arguments.length),this[Vn](this.alias.bind(this),"alias",t,e),this}array(t){return I("<array|string>",[t],arguments.length),this[Se]("array",t),this[ve](t),this}boolean(t){return I("<array|string>",[t],arguments.length),this[Se]("boolean",t),this[ve](t),this}check(t,e){return I("<function> [boolean]",[t,e],arguments.length),this.middleware((o,n)=>{return Ae(()=>{return t(o,n.getOptions())},(r)=>{if(!r)p(this,X,"f").fail(p(this,q,"f").y18n.__("Argument check failed: %s",t.toString()));else if(typeof r==="string"||r instanceof Error)p(this,X,"f").fail(r.toString(),r);return o},(r)=>{return p(this,X,"f").fail(r.message?r.message:r.toString(),r),o})},!1,e),this}choices(t,e){return I("<object|string|array> [string|array]",[t,e],arguments.length),this[Vn](this.choices.bind(this),"choices",t,e),this}coerce(t,e){if(I("<object|string|array> [function]",[t,e],arguments.length),Array.isArray(t)){if(!e)throw new lt("coerce callback must be provided");for(let o of t)this.coerce(o,e);return this}else if(typeof t==="object"){for(let o of Object.keys(t))this.coerce(o,t[o]);return this}if(!e)throw new lt("coerce callback must be provided");return p(this,J,"f").key[t]=!0,p(this,zt,"f").addCoerceMiddleware((o,n)=>{let r;if(!Object.prototype.hasOwnProperty.call(o,t))return o;return Ae(()=>{return r=n.getAliases(),e(o[t])},(s)=>{o[t]=s;let c=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(r[t]&&c!==!0)for(let f of r[t])o[f]=s;return o},(s)=>{throw new lt(s.message)})},t),this}conflicts(t,e){return I("<string|object> [string|array]",[t,e],arguments.length),p(this,wt,"f").conflicts(t,e),this}config(t="config",e,o){if(I("[object|string] [string|function] [function]",[t,e,o],arguments.length),typeof t==="object"&&!Array.isArray(t))return t=yo(t,p(this,Ie,"f"),this[Je]()["deep-merge-config"]||!1,p(this,q,"f")),p(this,J,"f").configObjects=(p(this,J,"f").configObjects||[]).concat(t),this;if(typeof e==="function")o=e,e=void 0;return this.describe(t,e||p(this,X,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((n)=>{p(this,J,"f").config[n]=o||!0}),this}completion(t,e,o){if(I("[string] [string|boolean|function] [function]",[t,e,o],arguments.length),typeof e==="function")o=e,e=void 0;if(j(this,It,t||p(this,It,"f")||"completion","f"),!e&&e!==!1)e="generate completion script";if(this.command(p(this,It,"f"),e),o)p(this,Ht,"f").registerFunction(o);return this}command(t,e,o,n,r,i){return I("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,o,n,r,i],arguments.length),p(this,gt,"f").addHandler(t,e,o,n,r,i),this}commands(t,e,o,n,r,i){return this.command(t,e,o,n,r,i)}commandDir(t,e){I("<string> [object]",[t,e],arguments.length);let o=p(this,Vo,"f")||p(this,q,"f").require;return p(this,gt,"f").addDirectory(t,o,p(this,q,"f").getCallerFile(),e),this}count(t){return I("<array|string>",[t],arguments.length),this[Se]("count",t),this[ve](t),this}default(t,e,o){if(I("<object|string|array> [*] [string]",[t,e,o],arguments.length),o)Hn(t,p(this,q,"f")),p(this,J,"f").defaultDescription[t]=o;if(typeof e==="function"){if(Hn(t,p(this,q,"f")),!p(this,J,"f").defaultDescription[t])p(this,J,"f").defaultDescription[t]=p(this,X,"f").functionDescription(e);e=e.call()}return this[io](this.default.bind(this),"default",t,e),this}defaults(t,e,o){return this.default(t,e,o)}demandCommand(t=1,e,o,n){if(I("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,o,n],arguments.length),typeof e!=="number")o=e,e=1/0;return this.global("_",!1),p(this,J,"f").demandedCommands._={min:t,max:e,minMsg:o,maxMsg:n},this}demand(t,e,o){if(Array.isArray(e))e.forEach((n)=>{Ft(o,!0,p(this,q,"f")),this.demandOption(n,o)}),e=1/0;else if(typeof e!=="number")o=e,e=1/0;if(typeof t==="number")Ft(o,!0,p(this,q,"f")),this.demandCommand(t,e,o,o);else if(Array.isArray(t))t.forEach((n)=>{Ft(o,!0,p(this,q,"f")),this.demandOption(n,o)});else if(typeof o==="string")this.demandOption(t,o);else if(o===!0||typeof o>"u")this.demandOption(t);return this}demandOption(t,e){return I("<object|string|array> [string]",[t,e],arguments.length),this[io](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return I("<string> [string|boolean]",[t,e],arguments.length),p(this,J,"f").deprecatedOptions[t]=e,this}describe(t,e){return I("<object|string|array> [string]",[t,e],arguments.length),this[Qn](t,!0),p(this,X,"f").describe(t,e),this}detectLocale(t){return I("<boolean>",[t],arguments.length),j(this,je,t,"f"),this}env(t){if(I("[string|boolean]",[t],arguments.length),t===!1)delete p(this,J,"f").envPrefix;else p(this,J,"f").envPrefix=t||"";return this}epilogue(t){return I("<string>",[t],arguments.length),p(this,X,"f").epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){if(I("<string|array> [string]",[t,e],arguments.length),Array.isArray(t))t.forEach((o)=>this.example(...o));else p(this,X,"f").example(t,e);return this}exit(t,e){if(j(this,jt,!0,"f"),j(this,Ce,e,"f"),p(this,Jt,"f"))p(this,q,"f").process.exit(t)}exitProcess(t=!0){return I("[boolean]",[t],arguments.length),j(this,Jt,t,"f"),this}fail(t){if(I("<function|boolean>",[t],arguments.length),typeof t==="boolean"&&t!==!1)throw new lt("Invalid first argument. Expected function or boolean 'false'");return p(this,X,"f").failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){if(I("<array> [function]",[t,e],arguments.length),!e)return new Promise((o,n)=>{p(this,Ht,"f").getCompletion(t,(r,i)=>{if(r)n(r);else o(i)})});else return p(this,Ht,"f").getCompletion(t,e)}getDemandedOptions(){return I([],0),p(this,J,"f").demandedOptions}getDemandedCommands(){return I([],0),p(this,J,"f").demandedCommands}getDeprecatedOptions(){return I([],0),p(this,J,"f").deprecatedOptions}getDetectLocale(){return p(this,je,"f")}getExitProcess(){return p(this,Jt,"f")}getGroups(){return Object.assign({},p(this,Zt,"f"),p(this,Te,"f"))}getHelp(){if(j(this,jt,!0,"f"),!p(this,X,"f").hasCachedHelpMessage()){if(!this.parsed){let e=this[Eo](p(this,$e,"f"),void 0,void 0,0,!0);if(ht(e))return e.then(()=>{return p(this,X,"f").help()})}let t=p(this,gt,"f").runDefaultBuilderOn(this);if(ht(t))return t.then(()=>{return p(this,X,"f").help()})}return Promise.resolve(p(this,X,"f").help())}getOptions(){return p(this,J,"f")}getStrict(){return p(this,_e,"f")}getStrictCommands(){return p(this,Ne,"f")}getStrictOptions(){return p(this,He,"f")}global(t,e){if(I("<string|array> [boolean]",[t,e],arguments.length),t=[].concat(t),e!==!1)p(this,J,"f").local=p(this,J,"f").local.filter((o)=>t.indexOf(o)===-1);else t.forEach((o)=>{if(!p(this,J,"f").local.includes(o))p(this,J,"f").local.push(o)});return this}group(t,e){I("<string|array> <string>",[t,e],arguments.length);let o=p(this,Te,"f")[e]||p(this,Zt,"f")[e];if(p(this,Te,"f")[e])delete p(this,Te,"f")[e];let n={};return p(this,Zt,"f")[e]=(o||[]).concat(t).filter((r)=>{if(n[r])return!1;return n[r]=!0}),this}hide(t){return I("<string>",[t],arguments.length),p(this,J,"f").hiddenOptions.push(t),this}implies(t,e){return I("<string|object> [number|string|array]",[t,e],arguments.length),p(this,wt,"f").implies(t,e),this}locale(t){if(I("[string]",[t],arguments.length),t===void 0)return this[Kn](),p(this,q,"f").y18n.getLocale();return j(this,je,!1,"f"),p(this,q,"f").y18n.setLocale(t),this}middleware(t,e,o){return p(this,zt,"f").addMiddleware(t,!!e,o)}nargs(t,e){return I("<string|object|array> [number]",[t,e],arguments.length),this[io](this.nargs.bind(this),"narg",t,e),this}normalize(t){return I("<array|string>",[t],arguments.length),this[Se]("normalize",t),this}number(t){return I("<array|string>",[t],arguments.length),this[Se]("number",t),this[ve](t),this}option(t,e){if(I("<string|object> [object]",[t,e],arguments.length),typeof t==="object")Object.keys(t).forEach((o)=>{this.options(o,t[o])});else{if(typeof e!=="object")e={};if(this[ve](t),p(this,Qt,"f")&&(t==="version"||(e===null||e===void 0?void 0:e.alias)==="version"))this[$i](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
219
- `),void 0,"versionWarning");if(p(this,J,"f").key[t]=!0,e.alias)this.alias(t,e.alias);let o=e.deprecate||e.deprecated;if(o)this.deprecateOption(t,o);let n=e.demand||e.required||e.require;if(n)this.demand(t,n);if(e.demandOption)this.demandOption(t,typeof e.demandOption==="string"?e.demandOption:void 0);if(e.conflicts)this.conflicts(t,e.conflicts);if("default"in e)this.default(t,e.default);if(e.implies!==void 0)this.implies(t,e.implies);if(e.nargs!==void 0)this.nargs(t,e.nargs);if(e.config)this.config(t,e.configParser);if(e.normalize)this.normalize(t);if(e.choices)this.choices(t,e.choices);if(e.coerce)this.coerce(t,e.coerce);if(e.group)this.group(t,e.group);if(e.boolean||e.type==="boolean"){if(this.boolean(t),e.alias)this.boolean(e.alias)}if(e.array||e.type==="array"){if(this.array(t),e.alias)this.array(e.alias)}if(e.number||e.type==="number"){if(this.number(t),e.alias)this.number(e.alias)}if(e.string||e.type==="string"){if(this.string(t),e.alias)this.string(e.alias)}if(e.count||e.type==="count")this.count(t);if(typeof e.global==="boolean")this.global(t,e.global);if(e.defaultDescription)p(this,J,"f").defaultDescription[t]=e.defaultDescription;if(e.skipValidation)this.skipValidation(t);let r=e.describe||e.description||e.desc,i=p(this,X,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(i,t)||typeof r==="string")this.describe(t,r);if(e.hidden)this.hide(t);if(e.requiresArg)this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,o){if(I("[string|array] [function|boolean|object] [function]",[t,e,o],arguments.length),this[Si](),typeof t>"u")t=p(this,$e,"f");if(typeof e==="object")j(this,Ge,e,"f"),e=o;if(typeof e==="function")j(this,Gt,e,"f"),e=!1;if(!e)j(this,$e,t,"f");if(p(this,Gt,"f"))j(this,Jt,!1,"f");let n=this[Eo](t,!!e),r=this.parsed;if(p(this,Ht,"f").setParsed(this.parsed),ht(n))return n.then((i)=>{if(p(this,Gt,"f"))p(this,Gt,"f").call(this,p(this,Ce,"f"),i,p(this,Pt,"f"));return i}).catch((i)=>{if(p(this,Gt,"f"))p(this,Gt,"f")(i,this.parsed.argv,p(this,Pt,"f"));throw i}).finally(()=>{this[Yn](),this.parsed=r});else{if(p(this,Gt,"f"))p(this,Gt,"f").call(this,p(this,Ce,"f"),n,p(this,Pt,"f"));this[Yn](),this.parsed=r}return n}parseAsync(t,e,o){let n=this.parse(t,e,o);return!ht(n)?Promise.resolve(n):n}parseSync(t,e,o){let n=this.parse(t,e,o);if(ht(n))throw new lt(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(t){return I("<object>",[t],arguments.length),j(this,Xo,t,"f"),this}pkgConf(t,e){I("<string> [string]",[t,e],arguments.length);let o=null,n=this[qn](e||p(this,Ie,"f"));if(n[t]&&typeof n[t]==="object")o=yo(n[t],e||p(this,Ie,"f"),this[Je]()["deep-merge-config"]||!1,p(this,q,"f")),p(this,J,"f").configObjects=(p(this,J,"f").configObjects||[]).concat(o);return this}positional(t,e){I("<string> <object>",[t,e],arguments.length);let o=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=ge(e,(i,s)=>{if(i==="type"&&!["string","number","boolean"].includes(s))return!1;return o.includes(i)});let n=p(this,Po,"f").fullCommands[p(this,Po,"f").fullCommands.length-1],r=n?p(this,gt,"f").cmdToParseOptions(n):{array:[],alias:{},default:{},demand:{}};return eo(r).forEach((i)=>{let s=r[i];if(Array.isArray(s)){if(s.indexOf(t)!==-1)e[i]=!0}else if(s[t]&&!(i in e))e[i]=s[t]}),this.group(t,p(this,X,"f").getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return I("[boolean]",[t],arguments.length),j(this,Zo,t,"f"),this}required(t,e,o){return this.demand(t,e,o)}require(t,e,o){return this.demand(t,e,o)}requiresArg(t){if(I("<array|string|object> [number]",[t],arguments.length),typeof t==="string"&&p(this,J,"f").narg[t])return this;else this[io](this.requiresArg.bind(this),"narg",t,NaN);return this}showCompletionScript(t,e){return I("[string] [string]",[t,e],arguments.length),t=t||this.$0,p(this,no,"f").log(p(this,Ht,"f").generateCompletionScript(t,e||p(this,It,"f")||"completion")),this}showHelp(t){if(I("[string|function]",[t],arguments.length),j(this,jt,!0,"f"),!p(this,X,"f").hasCachedHelpMessage()){if(!this.parsed){let o=this[Eo](p(this,$e,"f"),void 0,void 0,0,!0);if(ht(o))return o.then(()=>{p(this,X,"f").showHelp(t)}),this}let e=p(this,gt,"f").runDefaultBuilderOn(this);if(ht(e))return e.then(()=>{p(this,X,"f").showHelp(t)}),this}return p(this,X,"f").showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return I("[boolean|string] [string]",[t,e],arguments.length),p(this,X,"f").showHelpOnFail(t,e),this}showVersion(t){return I("[string|function]",[t],arguments.length),p(this,X,"f").showVersion(t),this}skipValidation(t){return I("<array|string>",[t],arguments.length),this[Se]("skipValidation",t),this}strict(t){return I("[boolean]",[t],arguments.length),j(this,_e,t!==!1,"f"),this}strictCommands(t){return I("[boolean]",[t],arguments.length),j(this,Ne,t!==!1,"f"),this}strictOptions(t){return I("[boolean]",[t],arguments.length),j(this,He,t!==!1,"f"),this}string(t){return I("<array|string>",[t],arguments.length),this[Se]("string",t),this[ve](t),this}terminalWidth(){return I([],0),p(this,q,"f").process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return I("<object>",[t],arguments.length),j(this,je,!1,"f"),p(this,q,"f").y18n.updateLocale(t),this}usage(t,e,o,n){if(I("<string|null|undefined> [string|boolean] [function|object] [function]",[t,e,o,n],arguments.length),e!==void 0)if(Ft(t,null,p(this,q,"f")),(t||"").match(/^\$0( |$)/))return this.command(t,e,o,n);else throw new lt(".usage() description must start with $0 if being used as alias for .command()");else return p(this,X,"f").usage(t),this}usageConfiguration(t){return I("<object>",[t],arguments.length),j(this,Qo,t,"f"),this}version(t,e,o){if(I("[boolean|string] [string] [string]",[t,e,o],arguments.length),p(this,Qt,"f"))this[Un](p(this,Qt,"f")),p(this,X,"f").version(void 0),j(this,Qt,null,"f");if(arguments.length===0)o=this[Ei](),t="version";else if(arguments.length===1){if(t===!1)return this;o=t,t="version"}else if(arguments.length===2)o=e,e=void 0;return j(this,Qt,typeof t==="string"?t:"version","f"),e=e||p(this,X,"f").deferY18nLookup("Show version number"),p(this,X,"f").version(o||void 0),this.boolean(p(this,Qt,"f")),this.describe(p(this,Qt,"f"),e),this}wrap(t){return I("<number|null|undefined>",[t],arguments.length),p(this,X,"f").wrap(t),this}[(gt=new WeakMap,Ie=new WeakMap,Po=new WeakMap,Ht=new WeakMap,It=new WeakMap,ko=new WeakMap,Ce=new WeakMap,je=new WeakMap,Uo=new WeakMap,Jt=new WeakMap,Ko=new WeakMap,zt=new WeakMap,Zt=new WeakMap,jt=new WeakMap,vt=new WeakMap,qo=new WeakMap,no=new WeakMap,Pt=new WeakMap,J=new WeakMap,Vo=new WeakMap,Xo=new WeakMap,Gt=new WeakMap,Ge=new WeakMap,ro=new WeakMap,Te=new WeakMap,$e=new WeakMap,Zo=new WeakMap,q=new WeakMap,_e=new WeakMap,Ne=new WeakMap,He=new WeakMap,X=new WeakMap,Qo=new WeakMap,Qt=new WeakMap,wt=new WeakMap,bi)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(e){}return t}[Ci](){return{log:(...t)=>{if(!this[Yo]())console.log(...t);if(j(this,jt,!0,"f"),p(this,Pt,"f").length)j(this,Pt,p(this,Pt,"f")+`
220
- `,"f");j(this,Pt,p(this,Pt,"f")+t.join(" "),"f")},error:(...t)=>{if(!this[Yo]())console.error(...t);if(j(this,jt,!0,"f"),p(this,Pt,"f").length)j(this,Pt,p(this,Pt,"f")+`
221
- `,"f");j(this,Pt,p(this,Pt,"f")+t.join(" "),"f")}}}[Un](t){eo(p(this,J,"f")).forEach((e)=>{if(((n)=>n==="configObjects")(e))return;let o=p(this,J,"f")[e];if(Array.isArray(o)){if(o.includes(t))o.splice(o.indexOf(t),1)}else if(typeof o==="object")delete o[t]}),delete p(this,X,"f").getDescriptions()[t]}[$i](t,e,o){if(!p(this,Uo,"f")[o])p(this,q,"f").process.emitWarning(t,e),p(this,Uo,"f")[o]=!0}[Si](){p(this,Ko,"f").push({options:p(this,J,"f"),configObjects:p(this,J,"f").configObjects.slice(0),exitProcess:p(this,Jt,"f"),groups:p(this,Zt,"f"),strict:p(this,_e,"f"),strictCommands:p(this,Ne,"f"),strictOptions:p(this,He,"f"),completionCommand:p(this,It,"f"),output:p(this,Pt,"f"),exitError:p(this,Ce,"f"),hasOutput:p(this,jt,"f"),parsed:this.parsed,parseFn:p(this,Gt,"f"),parseContext:p(this,Ge,"f")}),p(this,X,"f").freeze(),p(this,wt,"f").freeze(),p(this,gt,"f").freeze(),p(this,zt,"f").freeze()}[yi](){let t="",e;if(/\b(node|iojs|electron)(\.exe)?$/.test(p(this,q,"f").process.argv()[0]))e=p(this,q,"f").process.argv().slice(1,2);else e=p(this,q,"f").process.argv().slice(0,1);if(t=e.map((o)=>{let n=this[ji](p(this,Ie,"f"),o);return o.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<o.length?n:o}).join(" ").trim(),p(this,q,"f").getEnv("_")&&p(this,q,"f").getProcessArgvBin()===p(this,q,"f").getEnv("_"))t=p(this,q,"f").getEnv("_").replace(`${p(this,q,"f").path.dirname(p(this,q,"f").process.execPath())}/`,"");return t}[Je](){return p(this,Xo,"f")}[Pi](){return p(this,Qo,"f")}[Kn](){if(!p(this,je,"f"))return;let t=p(this,q,"f").getEnv("LC_ALL")||p(this,q,"f").getEnv("LC_MESSAGES")||p(this,q,"f").getEnv("LANG")||p(this,q,"f").getEnv("LANGUAGE")||"en_US";this.locale(t.replace(/[.:].*/,""))}[Ei](){return this[qn]().version||"unknown"}[Ri](t){let e=t["--"]?t["--"]:t._;for(let o=0,n;(n=e[o])!==void 0;o++)if(p(this,q,"f").Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`))))e[o]=Number(n);return t}[qn](t){let e=t||"*";if(p(this,ro,"f")[e])return p(this,ro,"f")[e];let o={};try{let n=t||p(this,q,"f").mainFilename;if(!t&&p(this,q,"f").path.extname(n))n=p(this,q,"f").path.dirname(n);let r=p(this,q,"f").findUp(n,(i,s)=>{if(s.includes("package.json"))return"package.json";else return});Ft(r,void 0,p(this,q,"f")),o=JSON.parse(p(this,q,"f").readFileSync(r,"utf8"))}catch(n){}return p(this,ro,"f")[e]=o||{},p(this,ro,"f")[e]}[Se](t,e){e=[].concat(e),e.forEach((o)=>{o=this[Zn](o),p(this,J,"f")[t].push(o)})}[io](t,e,o,n){this[Xn](t,e,o,n,(r,i,s)=>{p(this,J,"f")[r][i]=s})}[Vn](t,e,o,n){this[Xn](t,e,o,n,(r,i,s)=>{p(this,J,"f")[r][i]=(p(this,J,"f")[r][i]||[]).concat(s)})}[Xn](t,e,o,n,r){if(Array.isArray(o))o.forEach((i)=>{t(i,n)});else if(((i)=>typeof i==="object")(o))for(let i of eo(o))t(i,o[i]);else r(e,this[Zn](o),n)}[Zn](t){if(t==="__proto__")return"___proto___";return t}[Qn](t,e){return this[io](this[Qn].bind(this),"key",t,e),this}[Yn](){var t,e,o,n,r,i,s,c,f,a,u,h;let d=p(this,Ko,"f").pop();Ft(d,void 0,p(this,q,"f"));let w;t=this,e=this,o=this,n=this,r=this,i=this,s=this,c=this,f=this,a=this,u=this,h=this,{options:{set value(x){j(t,J,x,"f")}}.value,configObjects:w,exitProcess:{set value(x){j(e,Jt,x,"f")}}.value,groups:{set value(x){j(o,Zt,x,"f")}}.value,output:{set value(x){j(n,Pt,x,"f")}}.value,exitError:{set value(x){j(r,Ce,x,"f")}}.value,hasOutput:{set value(x){j(i,jt,x,"f")}}.value,parsed:this.parsed,strict:{set value(x){j(s,_e,x,"f")}}.value,strictCommands:{set value(x){j(c,Ne,x,"f")}}.value,strictOptions:{set value(x){j(f,He,x,"f")}}.value,completionCommand:{set value(x){j(a,It,x,"f")}}.value,parseFn:{set value(x){j(u,Gt,x,"f")}}.value,parseContext:{set value(x){j(h,Ge,x,"f")}}.value}=d,p(this,J,"f").configObjects=w,p(this,X,"f").unfreeze(),p(this,wt,"f").unfreeze(),p(this,gt,"f").unfreeze(),p(this,zt,"f").unfreeze()}[Mi](t,e){return Ae(e,(o)=>{return t(o),o})}getInternalMethods(){return{getCommandInstance:this[Oi].bind(this),getContext:this[Wi].bind(this),getHasOutput:this[Di].bind(this),getLoggerInstance:this[Fi].bind(this),getParseContext:this[Bi].bind(this),getParserConfiguration:this[Je].bind(this),getUsageConfiguration:this[Pi].bind(this),getUsageInstance:this[Li].bind(this),getValidationInstance:this[Ai].bind(this),hasParseCallback:this[Yo].bind(this),isGlobalContext:this[Ii].bind(this),postProcess:this[ze].bind(this),reset:this[tr].bind(this),runValidation:this[er].bind(this),runYargsParserAndExecuteCommands:this[Eo].bind(this),setHasOutput:this[Gi].bind(this)}}[Oi](){return p(this,gt,"f")}[Wi](){return p(this,Po,"f")}[Di](){return p(this,jt,"f")}[Fi](){return p(this,no,"f")}[Bi](){return p(this,Ge,"f")||{}}[Li](){return p(this,X,"f")}[Ai](){return p(this,wt,"f")}[Yo](){return!!p(this,Gt,"f")}[Ii](){return p(this,qo,"f")}[ze](t,e,o,n){if(o)return t;if(ht(t))return t;if(!e)t=this[bi](t);if(this[Je]()["parse-positional-numbers"]||this[Je]()["parse-positional-numbers"]===void 0)t=this[Ri](t);if(n)t=Le(t,this,p(this,zt,"f").getMiddleware(),!1);return t}[tr](t={}){j(this,J,p(this,J,"f")||{},"f");let e={};e.local=p(this,J,"f").local||[],e.configObjects=p(this,J,"f").configObjects||[];let o={};e.local.forEach((i)=>{o[i]=!0,(t[i]||[]).forEach((s)=>{o[s]=!0})}),Object.assign(p(this,Te,"f"),Object.keys(p(this,Zt,"f")).reduce((i,s)=>{let c=p(this,Zt,"f")[s].filter((f)=>!(f in o));if(c.length>0)i[s]=c;return i},{})),j(this,Zt,{},"f");let n=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(n.forEach((i)=>{e[i]=(p(this,J,"f")[i]||[]).filter((s)=>!o[s])}),r.forEach((i)=>{e[i]=ge(p(this,J,"f")[i],(s)=>!o[s])}),e.envPrefix=p(this,J,"f").envPrefix,j(this,J,e,"f"),j(this,X,p(this,X,"f")?p(this,X,"f").reset(o):li(this,p(this,q,"f")),"f"),j(this,wt,p(this,wt,"f")?p(this,wt,"f").reset(o):wi(this,p(this,X,"f"),p(this,q,"f")),"f"),j(this,gt,p(this,gt,"f")?p(this,gt,"f").reset():ci(p(this,X,"f"),p(this,wt,"f"),p(this,zt,"f"),p(this,q,"f")),"f"),!p(this,Ht,"f"))j(this,Ht,di(this,p(this,X,"f"),p(this,gt,"f"),p(this,q,"f")),"f");return p(this,zt,"f").reset(),j(this,It,null,"f"),j(this,Pt,"","f"),j(this,Ce,null,"f"),j(this,jt,!1,"f"),this.parsed=!1,this}[ji](t,e){return p(this,q,"f").path.relative(t,e)}[Eo](t,e,o,n=0,r=!1){let i=!!o||r;t=t||p(this,$e,"f"),p(this,J,"f").__=p(this,q,"f").y18n.__,p(this,J,"f").configuration=this[Je]();let s=!!p(this,J,"f").configuration["populate--"],c=Object.assign({},p(this,J,"f").configuration,{"populate--":!0}),f=p(this,q,"f").Parser.detailed(t,Object.assign({},p(this,J,"f"),{configuration:{"parse-positional-numbers":!1,...c}})),a=Object.assign(f.argv,p(this,Ge,"f")),u=void 0,h=f.aliases,d=!1,w=!1;if(Object.keys(a).forEach((x)=>{if(x===p(this,vt,"f")&&a[x])d=!0;else if(x===p(this,Qt,"f")&&a[x])w=!0}),a.$0=this.$0,this.parsed=f,n===0)p(this,X,"f").clearCachedHelpMessage();try{if(this[Kn](),e)return this[ze](a,s,!!o,!1);if(p(this,vt,"f")){if([p(this,vt,"f")].concat(h[p(this,vt,"f")]||[]).filter((R)=>R.length>1).includes(""+a._[a._.length-1]))a._.pop(),d=!0}j(this,qo,!1,"f");let x=p(this,gt,"f").getCommands(),m=p(this,Ht,"f").completionKey in a,b=d||m||r;if(a._.length){if(x.length){let S;for(let R=n||0,P;a._[R]!==void 0;R++)if(P=String(a._[R]),x.includes(P)&&P!==p(this,It,"f")){let M=p(this,gt,"f").runCommand(P,this,f,R+1,r,d||w||r);return this[ze](M,s,!!o,!1)}else if(!S&&P!==p(this,It,"f")){S=P;break}if(!p(this,gt,"f").hasDefaultCommand()&&p(this,Zo,"f")&&S&&!b)p(this,wt,"f").recommendCommands(S,x)}if(p(this,It,"f")&&a._.includes(p(this,It,"f"))&&!m){if(p(this,Jt,"f"))be(!0);this.showCompletionScript(),this.exit(0)}}if(p(this,gt,"f").hasDefaultCommand()&&!b){let S=p(this,gt,"f").runCommand(null,this,f,0,r,d||w||r);return this[ze](S,s,!!o,!1)}if(m){if(p(this,Jt,"f"))be(!0);t=[].concat(t);let S=t.slice(t.indexOf(`--${p(this,Ht,"f").completionKey}`)+1);return p(this,Ht,"f").getCompletion(S,(R,P)=>{if(R)throw new lt(R.message);(P||[]).forEach((M)=>{p(this,no,"f").log(M)}),this.exit(0)}),this[ze](a,!s,!!o,!1)}if(!p(this,jt,"f")){if(d){if(p(this,Jt,"f"))be(!0);i=!0,this.showHelp("log"),this.exit(0)}else if(w){if(p(this,Jt,"f"))be(!0);i=!0,p(this,X,"f").showVersion("log"),this.exit(0)}}if(!i&&p(this,J,"f").skipValidation.length>0)i=Object.keys(a).some((S)=>p(this,J,"f").skipValidation.indexOf(S)>=0&&a[S]===!0);if(!i){if(f.error)throw new lt(f.error.message);if(!m){let S=this[er](h,{},f.error);if(!o)u=Le(a,this,p(this,zt,"f").getMiddleware(),!0);if(u=this[Mi](S,u!==null&&u!==void 0?u:a),ht(u)&&!o)u=u.then(()=>{return Le(a,this,p(this,zt,"f").getMiddleware(),!1)})}}}catch(x){if(x instanceof lt)p(this,X,"f").fail(x.message,x);else throw x}return this[ze](u!==null&&u!==void 0?u:a,s,!!o,!0)}[er](t,e,o,n){let r={...this.getDemandedOptions()};return(i)=>{if(o)throw new lt(o.message);p(this,wt,"f").nonOptionCount(i),p(this,wt,"f").requiredArguments(i,r);let s=!1;if(p(this,Ne,"f"))s=p(this,wt,"f").unknownCommands(i);if(p(this,_e,"f")&&!s)p(this,wt,"f").unknownArguments(i,t,e,!!n);else if(p(this,He,"f"))p(this,wt,"f").unknownArguments(i,t,{},!1,!1);p(this,wt,"f").limitedChoices(i),p(this,wt,"f").implications(i),p(this,wt,"f").conflicting(i)}}[Gi](){j(this,jt,!0,"f")}[ve](t){if(typeof t==="string")p(this,J,"f").key[t]=!0;else for(let e of t)p(this,J,"f").key[e]=!0}}function ai(t){return!!t&&typeof t.getInternalMethods==="function"}var Sf=Ti(Nn),Ni=Sf;import{readFileSync as Sp}from"fs";import{join as yp}from"path";var Pp=JSON.parse(Sp(yp(import.meta.dir,"../../package.json"),"utf-8"));if(process.argv.length===2){let{launchTUI:t}=await Promise.resolve().then(() => (ec(),tc));await t()}else{let[t,e,o,n,r,i,s,c,f,a,u,h,d,w,x,m,b,S,R,P]=await Promise.all([Promise.resolve().then(() => (cc(),sc)),Promise.resolve().then(() => (fc(),ac)),Promise.resolve().then(() => (pc(),uc)),Promise.resolve().then(() => (mc(),dc)),Promise.resolve().then(() => ($c(),Cc)),Promise.resolve().then(() => (Wc(),Oc)),Promise.resolve().then(() => (Fc(),Dc)),Promise.resolve().then(() => (Ic(),Ac)),Promise.resolve().then(() => (Tc(),Gc)),Promise.resolve().then(() => (Hc(),Nc)),Promise.resolve().then(() => (vc(),zc)),Promise.resolve().then(() => (Uc(),kc)),Promise.resolve().then(() => (qc(),Kc)),Promise.resolve().then(() => (Zc(),Xc)),Promise.resolve().then(() => (ca(),sa)),Promise.resolve().then(() => (fa(),aa)),Promise.resolve().then(() => (ha(),la)),Promise.resolve().then(() => (wa(),xa)),Promise.resolve().then(() => (ba(),ga)),Promise.resolve().then(() => (Ma(),Ra))]);Ni(_n(process.argv)).locale("en").scriptName("omw").version(`oh-my-worktree v${Pp.version}`).alias("version","v").help("help").alias("help","h").option("no-color",{type:"boolean",description:"Disable color output"}).command(t.default).command(e.default).command(o.default).command(n.default).command(r.default).command(i.default).command(s.default).command(c.default).command(f.default).command(a.default).command(u.default).command(h.default).command(d.default).command(w.default).command(x.default).command(m.default).command(b.default).command(S.default).command(R.default).command(P.default).completion("completion","Generate shell completion script").demandCommand(1,"Please specify a command. Run --help to see available commands.").strict().parse()}
216
+ `)}`:"";e.fail(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(g).length,Object.keys(g).join(", ")+m))}},i.unknownArguments=function(h,d,g,x,m=!0){var b;let S=t.getInternalMethods().getCommandInstance().getCommands(),R=[],y=t.getInternalMethods().getContext();if(Object.keys(h).forEach((M)=>{if(!mi.includes(M)&&!Object.prototype.hasOwnProperty.call(g,M)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),M)&&!i.isValidAndSomeAliasIsNotNew(M,d))R.push(M)}),m&&(y.commands.length>0||S.length>0||x))h._.slice(y.commands.length).forEach((M)=>{if(!S.includes(""+M))R.push(""+M)});if(m){let it=((b=t.getDemandedCommands()._)===null||b===void 0?void 0:b.max)||0,st=y.commands.length+it;if(st<h._.length)h._.slice(st).forEach((G)=>{if(G=String(G),!y.commands.includes(G)&&!R.includes(G))R.push(G)})}if(R.length)e.fail(r("Unknown argument: %s","Unknown arguments: %s",R.length,R.map((M)=>M.trim()?M:`"${M}"`).join(", ")))},i.unknownCommands=function(h){let d=t.getInternalMethods().getCommandInstance().getCommands(),g=[],x=t.getInternalMethods().getContext();if(x.commands.length>0||d.length>0)h._.slice(x.commands.length).forEach((m)=>{if(!d.includes(""+m))g.push(""+m)});if(g.length>0)return e.fail(r("Unknown command: %s","Unknown commands: %s",g.length,g.join(", "))),!0;else return!1},i.isValidAndSomeAliasIsNotNew=function(h,d){if(!Object.prototype.hasOwnProperty.call(d,h))return!1;let g=t.parsed.newAliases;return[h,...d[h]].some((x)=>!Object.prototype.hasOwnProperty.call(g,x)||!g[h])},i.limitedChoices=function(h){let d=t.getOptions(),g={};if(!Object.keys(d.choices).length)return;Object.keys(h).forEach((b)=>{if(mi.indexOf(b)===-1&&Object.prototype.hasOwnProperty.call(d.choices,b))[].concat(h[b]).forEach((S)=>{if(d.choices[b].indexOf(S)===-1&&S!==void 0)g[b]=(g[b]||[]).concat(S)})});let x=Object.keys(g);if(!x.length)return;let m=n("Invalid values:");x.forEach((b)=>{m+=`
217
+ ${n("Argument: %s, Given: %s, Choices: %s",b,e.stringifiedValues(g[b]),e.stringifiedValues(d.choices[b]))}`}),e.fail(m)};let s={};i.implies=function(h,d){if(I("<string|object> [array|number|string]",[h,d],arguments.length),typeof h==="object")Object.keys(h).forEach((g)=>{i.implies(g,h[g])});else{if(t.global(h),!s[h])s[h]=[];if(Array.isArray(d))d.forEach((g)=>i.implies(h,g));else Bt(d,void 0,o),s[h].push(d)}},i.getImplied=function(){return s};function c(l,h){let d=Number(h);if(h=isNaN(d)?h:d,typeof h==="number")h=l._.length>=h;else if(h.match(/^--no-.+/))h=h.match(/^--no-(.+)/)[1],h=!Object.prototype.hasOwnProperty.call(l,h);else h=Object.prototype.hasOwnProperty.call(l,h);return h}i.implications=function(h){let d=[];if(Object.keys(s).forEach((g)=>{let x=g;(s[g]||[]).forEach((m)=>{let b=x,S=m;if(b=c(h,b),m=c(h,m),b&&!m)d.push(` ${x} -> ${S}`)})}),d.length){let g=`${n("Implications failed:")}
218
+ `;d.forEach((x)=>{g+=x}),e.fail(g)}};let u={};i.conflicts=function(h,d){if(I("<string|object> [array|string]",[h,d],arguments.length),typeof h==="object")Object.keys(h).forEach((g)=>{i.conflicts(g,h[g])});else{if(t.global(h),!u[h])u[h]=[];if(Array.isArray(d))d.forEach((g)=>i.conflicts(h,g));else u[h].push(d)}},i.getConflicting=()=>u,i.conflicting=function(h){if(Object.keys(h).forEach((d)=>{if(u[d])u[d].forEach((g)=>{if(g&&h[d]!==void 0&&h[g]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,g))})}),t.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(u).forEach((d)=>{u[d].forEach((g)=>{if(g&&h[o.Parser.camelCase(d)]!==void 0&&h[o.Parser.camelCase(g)]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,g))})})},i.recommendCommands=function(h,d){d=d.sort((b,S)=>S.length-b.length);let x=null,m=1/0;for(let b=0,S;(S=d[b])!==void 0;b++){let R=di(h,S);if(R<=3&&R<m)m=R,x=S}if(x)e.fail(n("Did you mean %s?",x))},i.reset=function(h){return s=Pe(s,(d)=>!h[d]),u=Pe(u,(d)=>!h[d]),i};let a=[];return i.freeze=function(){a.push({implied:s,conflicting:u})},i.unfreeze=function(){let h=a.pop();Bt(h,void 0,o),{implied:s,conflicting:u}=h},i}var Vn=[],Wo;function Do(t,e,o,n){Wo=n;let r={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if(typeof t.extends!=="string")return r;let i=/\.json|\..*rc$/.test(t.extends),s=null;if(!i)try{s=le.resolve(t.extends)}catch(c){return t}else s=Cf(e,t.extends);bf(s),Vn.push(s),r=i?JSON.parse(Wo.readFileSync(s,"utf8")):le(t.extends),delete t.extends,r=Do(r,Wo.path.dirname(s),o,Wo)}return Vn=[],o?gi(r,t):Object.assign({},r,t)}function bf(t){if(Vn.indexOf(t)>-1)throw new lt(`Circular extended configurations: '${t}'.`)}function Cf(t,e){return Wo.path.resolve(t,e)}function gi(t,e){let o={};function n(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(o,t);for(let r of Object.keys(e))if(n(e[r])&&n(o[r]))o[r]=gi(t[r],e[r]);else o[r]=e[r];return o}var j=function(t,e,o,n,r){if(n==="m")throw TypeError("Private method is not writable");if(n==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof e==="function"?t!==e||!r:!e.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(t,o):r?r.value=o:e.set(t,o),o},p=function(t,e,o,n){if(o==="a"&&!n)throw TypeError("Private accessor was defined without a getter");if(typeof e==="function"?t!==e||!n:!e.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?n:o==="a"?n.call(t):n?n.value:e.get(t)},bt,Je,Fo,zt,jt,Zo,Re,ze,Qo,vt,Yo,kt,ee,Tt,Ut,tn,fo,yt,J,en,on,_t,ve,lo,ke,Ee,nn,V,Ue,Ke,Ve,X,rn,oe,gt;function Ti(t){return(e=[],o=t.process.cwd(),n)=>{let r=new _i(e,o,n,t);return Object.defineProperty(r,"argv",{get:()=>{return r.parse()},enumerable:!0}),r.help(),r.version(),r}}var wi=Symbol("copyDoubleDash"),bi=Symbol("copyDoubleDash"),qn=Symbol("deleteFromParserHintObject"),Ci=Symbol("emitWarning"),$i=Symbol("freeze"),Si=Symbol("getDollarZero"),qe=Symbol("getParserConfiguration"),Pi=Symbol("getUsageConfiguration"),Xn=Symbol("guessLocale"),yi=Symbol("guessVersion"),Ri=Symbol("parsePositionalNumbers"),Zn=Symbol("pkgUp"),Me=Symbol("populateParserHintArray"),ho=Symbol("populateParserHintSingleValueDictionary"),Qn=Symbol("populateParserHintArrayDictionary"),Yn=Symbol("populateParserHintDictionary"),tr=Symbol("sanitizeKey"),er=Symbol("setKey"),or=Symbol("unfreeze"),Ei=Symbol("validateAsync"),Mi=Symbol("getCommandInstance"),Oi=Symbol("getContext"),Wi=Symbol("getHasOutput"),Di=Symbol("getLoggerInstance"),Fi=Symbol("getParseContext"),Bi=Symbol("getUsageInstance"),Li=Symbol("getValidationInstance"),sn=Symbol("hasParseCallback"),Ai=Symbol("isGlobalContext"),Xe=Symbol("postProcess"),Ii=Symbol("rebase"),nr=Symbol("reset"),Bo=Symbol("runYargsParserAndExecuteCommands"),rr=Symbol("runValidation"),ji=Symbol("setHasOutput"),Ze=Symbol("kTrackManuallySetKeys");class _i{constructor(t=[],e,o,n){this.customScriptName=!1,this.parsed=!1,bt.set(this,void 0),Je.set(this,void 0),Fo.set(this,{commands:[],fullCommands:[]}),zt.set(this,null),jt.set(this,null),Zo.set(this,"show-hidden"),Re.set(this,null),ze.set(this,!0),Qo.set(this,{}),vt.set(this,!0),Yo.set(this,[]),kt.set(this,void 0),ee.set(this,{}),Tt.set(this,!1),Ut.set(this,null),tn.set(this,!0),fo.set(this,void 0),yt.set(this,""),J.set(this,void 0),en.set(this,void 0),on.set(this,{}),_t.set(this,null),ve.set(this,null),lo.set(this,{}),ke.set(this,{}),Ee.set(this,void 0),nn.set(this,!1),V.set(this,void 0),Ue.set(this,!1),Ke.set(this,!1),Ve.set(this,!1),X.set(this,void 0),rn.set(this,{}),oe.set(this,null),gt.set(this,void 0),j(this,V,n,"f"),j(this,Ee,t,"f"),j(this,Je,e,"f"),j(this,en,o,"f"),j(this,kt,new kn(this),"f"),this.$0=this[Si](),this[nr](),j(this,bt,p(this,bt,"f"),"f"),j(this,X,p(this,X,"f"),"f"),j(this,gt,p(this,gt,"f"),"f"),j(this,J,p(this,J,"f"),"f"),p(this,J,"f").showHiddenOpt=p(this,Zo,"f"),j(this,fo,this[bi](),"f")}addHelpOpt(t,e){if(I("[string|boolean] [string]",[t,e],arguments.length),p(this,Ut,"f"))this[qn](p(this,Ut,"f")),j(this,Ut,null,"f");if(t===!1&&e===void 0)return this;return j(this,Ut,typeof t==="string"?t:"help","f"),this.boolean(p(this,Ut,"f")),this.describe(p(this,Ut,"f"),e||p(this,X,"f").deferY18nLookup("Show help")),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(I("[string|boolean] [string]",[t,e],arguments.length),t===!1&&e===void 0)return this;let o=typeof t==="string"?t:p(this,Zo,"f");return this.boolean(o),this.describe(o,e||p(this,X,"f").deferY18nLookup("Show hidden options")),p(this,J,"f").showHiddenOpt=o,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return I("<object|string|array> [string|array]",[t,e],arguments.length),this[Qn](this.alias.bind(this),"alias",t,e),this}array(t){return I("<array|string>",[t],arguments.length),this[Me]("array",t),this[Ze](t),this}boolean(t){return I("<array|string>",[t],arguments.length),this[Me]("boolean",t),this[Ze](t),this}check(t,e){return I("<function> [boolean]",[t,e],arguments.length),this.middleware((o,n)=>{return Ne(()=>{return t(o,n.getOptions())},(r)=>{if(!r)p(this,X,"f").fail(p(this,V,"f").y18n.__("Argument check failed: %s",t.toString()));else if(typeof r==="string"||r instanceof Error)p(this,X,"f").fail(r.toString(),r);return o},(r)=>{return p(this,X,"f").fail(r.message?r.message:r.toString(),r),o})},!1,e),this}choices(t,e){return I("<object|string|array> [string|array]",[t,e],arguments.length),this[Qn](this.choices.bind(this),"choices",t,e),this}coerce(t,e){if(I("<object|string|array> [function]",[t,e],arguments.length),Array.isArray(t)){if(!e)throw new lt("coerce callback must be provided");for(let o of t)this.coerce(o,e);return this}else if(typeof t==="object"){for(let o of Object.keys(t))this.coerce(o,t[o]);return this}if(!e)throw new lt("coerce callback must be provided");return p(this,J,"f").key[t]=!0,p(this,kt,"f").addCoerceMiddleware((o,n)=>{let r;if(!Object.prototype.hasOwnProperty.call(o,t))return o;return Ne(()=>{return r=n.getAliases(),e(o[t])},(s)=>{o[t]=s;let c=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(r[t]&&c!==!0)for(let u of r[t])o[u]=s;return o},(s)=>{throw new lt(s.message)})},t),this}conflicts(t,e){return I("<string|object> [string|array]",[t,e],arguments.length),p(this,gt,"f").conflicts(t,e),this}config(t="config",e,o){if(I("[object|string] [string|function] [function]",[t,e,o],arguments.length),typeof t==="object"&&!Array.isArray(t))return t=Do(t,p(this,Je,"f"),this[qe]()["deep-merge-config"]||!1,p(this,V,"f")),p(this,J,"f").configObjects=(p(this,J,"f").configObjects||[]).concat(t),this;if(typeof e==="function")o=e,e=void 0;return this.describe(t,e||p(this,X,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((n)=>{p(this,J,"f").config[n]=o||!0}),this}completion(t,e,o){if(I("[string] [string|boolean|function] [function]",[t,e,o],arguments.length),typeof e==="function")o=e,e=void 0;if(j(this,jt,t||p(this,jt,"f")||"completion","f"),!e&&e!==!1)e="generate completion script";if(this.command(p(this,jt,"f"),e),o)p(this,zt,"f").registerFunction(o);return this}command(t,e,o,n,r,i){return I("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,o,n,r,i],arguments.length),p(this,bt,"f").addHandler(t,e,o,n,r,i),this}commands(t,e,o,n,r,i){return this.command(t,e,o,n,r,i)}commandDir(t,e){I("<string> [object]",[t,e],arguments.length);let o=p(this,en,"f")||p(this,V,"f").require;return p(this,bt,"f").addDirectory(t,o,p(this,V,"f").getCallerFile(),e),this}count(t){return I("<array|string>",[t],arguments.length),this[Me]("count",t),this[Ze](t),this}default(t,e,o){if(I("<object|string|array> [*] [string]",[t,e,o],arguments.length),o)vn(t,p(this,V,"f")),p(this,J,"f").defaultDescription[t]=o;if(typeof e==="function"){if(vn(t,p(this,V,"f")),!p(this,J,"f").defaultDescription[t])p(this,J,"f").defaultDescription[t]=p(this,X,"f").functionDescription(e);e=e.call()}return this[ho](this.default.bind(this),"default",t,e),this}defaults(t,e,o){return this.default(t,e,o)}demandCommand(t=1,e,o,n){if(I("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,o,n],arguments.length),typeof e!=="number")o=e,e=1/0;return this.global("_",!1),p(this,J,"f").demandedCommands._={min:t,max:e,minMsg:o,maxMsg:n},this}demand(t,e,o){if(Array.isArray(e))e.forEach((n)=>{Bt(o,!0,p(this,V,"f")),this.demandOption(n,o)}),e=1/0;else if(typeof e!=="number")o=e,e=1/0;if(typeof t==="number")Bt(o,!0,p(this,V,"f")),this.demandCommand(t,e,o,o);else if(Array.isArray(t))t.forEach((n)=>{Bt(o,!0,p(this,V,"f")),this.demandOption(n,o)});else if(typeof o==="string")this.demandOption(t,o);else if(o===!0||typeof o>"u")this.demandOption(t);return this}demandOption(t,e){return I("<object|string|array> [string]",[t,e],arguments.length),this[ho](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return I("<string> [string|boolean]",[t,e],arguments.length),p(this,J,"f").deprecatedOptions[t]=e,this}describe(t,e){return I("<object|string|array> [string]",[t,e],arguments.length),this[er](t,!0),p(this,X,"f").describe(t,e),this}detectLocale(t){return I("<boolean>",[t],arguments.length),j(this,ze,t,"f"),this}env(t){if(I("[string|boolean]",[t],arguments.length),t===!1)delete p(this,J,"f").envPrefix;else p(this,J,"f").envPrefix=t||"";return this}epilogue(t){return I("<string>",[t],arguments.length),p(this,X,"f").epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){if(I("<string|array> [string]",[t,e],arguments.length),Array.isArray(t))t.forEach((o)=>this.example(...o));else p(this,X,"f").example(t,e);return this}exit(t,e){if(j(this,Tt,!0,"f"),j(this,Re,e,"f"),p(this,vt,"f"))p(this,V,"f").process.exit(t)}exitProcess(t=!0){return I("[boolean]",[t],arguments.length),j(this,vt,t,"f"),this}fail(t){if(I("<function|boolean>",[t],arguments.length),typeof t==="boolean"&&t!==!1)throw new lt("Invalid first argument. Expected function or boolean 'false'");return p(this,X,"f").failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){if(I("<array> [function]",[t,e],arguments.length),!e)return new Promise((o,n)=>{p(this,zt,"f").getCompletion(t,(r,i)=>{if(r)n(r);else o(i)})});else return p(this,zt,"f").getCompletion(t,e)}getDemandedOptions(){return I([],0),p(this,J,"f").demandedOptions}getDemandedCommands(){return I([],0),p(this,J,"f").demandedCommands}getDeprecatedOptions(){return I([],0),p(this,J,"f").deprecatedOptions}getDetectLocale(){return p(this,ze,"f")}getExitProcess(){return p(this,vt,"f")}getGroups(){return Object.assign({},p(this,ee,"f"),p(this,ke,"f"))}getHelp(){if(j(this,Tt,!0,"f"),!p(this,X,"f").hasCachedHelpMessage()){if(!this.parsed){let e=this[Bo](p(this,Ee,"f"),void 0,void 0,0,!0);if(ht(e))return e.then(()=>{return p(this,X,"f").help()})}let t=p(this,bt,"f").runDefaultBuilderOn(this);if(ht(t))return t.then(()=>{return p(this,X,"f").help()})}return Promise.resolve(p(this,X,"f").help())}getOptions(){return p(this,J,"f")}getStrict(){return p(this,Ue,"f")}getStrictCommands(){return p(this,Ke,"f")}getStrictOptions(){return p(this,Ve,"f")}global(t,e){if(I("<string|array> [boolean]",[t,e],arguments.length),t=[].concat(t),e!==!1)p(this,J,"f").local=p(this,J,"f").local.filter((o)=>t.indexOf(o)===-1);else t.forEach((o)=>{if(!p(this,J,"f").local.includes(o))p(this,J,"f").local.push(o)});return this}group(t,e){I("<string|array> <string>",[t,e],arguments.length);let o=p(this,ke,"f")[e]||p(this,ee,"f")[e];if(p(this,ke,"f")[e])delete p(this,ke,"f")[e];let n={};return p(this,ee,"f")[e]=(o||[]).concat(t).filter((r)=>{if(n[r])return!1;return n[r]=!0}),this}hide(t){return I("<string>",[t],arguments.length),p(this,J,"f").hiddenOptions.push(t),this}implies(t,e){return I("<string|object> [number|string|array]",[t,e],arguments.length),p(this,gt,"f").implies(t,e),this}locale(t){if(I("[string]",[t],arguments.length),t===void 0)return this[Xn](),p(this,V,"f").y18n.getLocale();return j(this,ze,!1,"f"),p(this,V,"f").y18n.setLocale(t),this}middleware(t,e,o){return p(this,kt,"f").addMiddleware(t,!!e,o)}nargs(t,e){return I("<string|object|array> [number]",[t,e],arguments.length),this[ho](this.nargs.bind(this),"narg",t,e),this}normalize(t){return I("<array|string>",[t],arguments.length),this[Me]("normalize",t),this}number(t){return I("<array|string>",[t],arguments.length),this[Me]("number",t),this[Ze](t),this}option(t,e){if(I("<string|object> [object]",[t,e],arguments.length),typeof t==="object")Object.keys(t).forEach((o)=>{this.options(o,t[o])});else{if(typeof e!=="object")e={};if(this[Ze](t),p(this,oe,"f")&&(t==="version"||(e===null||e===void 0?void 0:e.alias)==="version"))this[Ci](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
219
+ `),void 0,"versionWarning");if(p(this,J,"f").key[t]=!0,e.alias)this.alias(t,e.alias);let o=e.deprecate||e.deprecated;if(o)this.deprecateOption(t,o);let n=e.demand||e.required||e.require;if(n)this.demand(t,n);if(e.demandOption)this.demandOption(t,typeof e.demandOption==="string"?e.demandOption:void 0);if(e.conflicts)this.conflicts(t,e.conflicts);if("default"in e)this.default(t,e.default);if(e.implies!==void 0)this.implies(t,e.implies);if(e.nargs!==void 0)this.nargs(t,e.nargs);if(e.config)this.config(t,e.configParser);if(e.normalize)this.normalize(t);if(e.choices)this.choices(t,e.choices);if(e.coerce)this.coerce(t,e.coerce);if(e.group)this.group(t,e.group);if(e.boolean||e.type==="boolean"){if(this.boolean(t),e.alias)this.boolean(e.alias)}if(e.array||e.type==="array"){if(this.array(t),e.alias)this.array(e.alias)}if(e.number||e.type==="number"){if(this.number(t),e.alias)this.number(e.alias)}if(e.string||e.type==="string"){if(this.string(t),e.alias)this.string(e.alias)}if(e.count||e.type==="count")this.count(t);if(typeof e.global==="boolean")this.global(t,e.global);if(e.defaultDescription)p(this,J,"f").defaultDescription[t]=e.defaultDescription;if(e.skipValidation)this.skipValidation(t);let r=e.describe||e.description||e.desc,i=p(this,X,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(i,t)||typeof r==="string")this.describe(t,r);if(e.hidden)this.hide(t);if(e.requiresArg)this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,o){if(I("[string|array] [function|boolean|object] [function]",[t,e,o],arguments.length),this[$i](),typeof t>"u")t=p(this,Ee,"f");if(typeof e==="object")j(this,ve,e,"f"),e=o;if(typeof e==="function")j(this,_t,e,"f"),e=!1;if(!e)j(this,Ee,t,"f");if(p(this,_t,"f"))j(this,vt,!1,"f");let n=this[Bo](t,!!e),r=this.parsed;if(p(this,zt,"f").setParsed(this.parsed),ht(n))return n.then((i)=>{if(p(this,_t,"f"))p(this,_t,"f").call(this,p(this,Re,"f"),i,p(this,yt,"f"));return i}).catch((i)=>{if(p(this,_t,"f"))p(this,_t,"f")(i,this.parsed.argv,p(this,yt,"f"));throw i}).finally(()=>{this[or](),this.parsed=r});else{if(p(this,_t,"f"))p(this,_t,"f").call(this,p(this,Re,"f"),n,p(this,yt,"f"));this[or](),this.parsed=r}return n}parseAsync(t,e,o){let n=this.parse(t,e,o);return!ht(n)?Promise.resolve(n):n}parseSync(t,e,o){let n=this.parse(t,e,o);if(ht(n))throw new lt(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(t){return I("<object>",[t],arguments.length),j(this,on,t,"f"),this}pkgConf(t,e){I("<string> [string]",[t,e],arguments.length);let o=null,n=this[Zn](e||p(this,Je,"f"));if(n[t]&&typeof n[t]==="object")o=Do(n[t],e||p(this,Je,"f"),this[qe]()["deep-merge-config"]||!1,p(this,V,"f")),p(this,J,"f").configObjects=(p(this,J,"f").configObjects||[]).concat(o);return this}positional(t,e){I("<string> <object>",[t,e],arguments.length);let o=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=Pe(e,(i,s)=>{if(i==="type"&&!["string","number","boolean"].includes(s))return!1;return o.includes(i)});let n=p(this,Fo,"f").fullCommands[p(this,Fo,"f").fullCommands.length-1],r=n?p(this,bt,"f").cmdToParseOptions(n):{array:[],alias:{},default:{},demand:{}};return co(r).forEach((i)=>{let s=r[i];if(Array.isArray(s)){if(s.indexOf(t)!==-1)e[i]=!0}else if(s[t]&&!(i in e))e[i]=s[t]}),this.group(t,p(this,X,"f").getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return I("[boolean]",[t],arguments.length),j(this,nn,t,"f"),this}required(t,e,o){return this.demand(t,e,o)}require(t,e,o){return this.demand(t,e,o)}requiresArg(t){if(I("<array|string|object> [number]",[t],arguments.length),typeof t==="string"&&p(this,J,"f").narg[t])return this;else this[ho](this.requiresArg.bind(this),"narg",t,NaN);return this}showCompletionScript(t,e){return I("[string] [string]",[t,e],arguments.length),t=t||this.$0,p(this,fo,"f").log(p(this,zt,"f").generateCompletionScript(t,e||p(this,jt,"f")||"completion")),this}showHelp(t){if(I("[string|function]",[t],arguments.length),j(this,Tt,!0,"f"),!p(this,X,"f").hasCachedHelpMessage()){if(!this.parsed){let o=this[Bo](p(this,Ee,"f"),void 0,void 0,0,!0);if(ht(o))return o.then(()=>{p(this,X,"f").showHelp(t)}),this}let e=p(this,bt,"f").runDefaultBuilderOn(this);if(ht(e))return e.then(()=>{p(this,X,"f").showHelp(t)}),this}return p(this,X,"f").showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return I("[boolean|string] [string]",[t,e],arguments.length),p(this,X,"f").showHelpOnFail(t,e),this}showVersion(t){return I("[string|function]",[t],arguments.length),p(this,X,"f").showVersion(t),this}skipValidation(t){return I("<array|string>",[t],arguments.length),this[Me]("skipValidation",t),this}strict(t){return I("[boolean]",[t],arguments.length),j(this,Ue,t!==!1,"f"),this}strictCommands(t){return I("[boolean]",[t],arguments.length),j(this,Ke,t!==!1,"f"),this}strictOptions(t){return I("[boolean]",[t],arguments.length),j(this,Ve,t!==!1,"f"),this}string(t){return I("<array|string>",[t],arguments.length),this[Me]("string",t),this[Ze](t),this}terminalWidth(){return I([],0),p(this,V,"f").process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return I("<object>",[t],arguments.length),j(this,ze,!1,"f"),p(this,V,"f").y18n.updateLocale(t),this}usage(t,e,o,n){if(I("<string|null|undefined> [string|boolean] [function|object] [function]",[t,e,o,n],arguments.length),e!==void 0)if(Bt(t,null,p(this,V,"f")),(t||"").match(/^\$0( |$)/))return this.command(t,e,o,n);else throw new lt(".usage() description must start with $0 if being used as alias for .command()");else return p(this,X,"f").usage(t),this}usageConfiguration(t){return I("<object>",[t],arguments.length),j(this,rn,t,"f"),this}version(t,e,o){if(I("[boolean|string] [string] [string]",[t,e,o],arguments.length),p(this,oe,"f"))this[qn](p(this,oe,"f")),p(this,X,"f").version(void 0),j(this,oe,null,"f");if(arguments.length===0)o=this[yi](),t="version";else if(arguments.length===1){if(t===!1)return this;o=t,t="version"}else if(arguments.length===2)o=e,e=void 0;return j(this,oe,typeof t==="string"?t:"version","f"),e=e||p(this,X,"f").deferY18nLookup("Show version number"),p(this,X,"f").version(o||void 0),this.boolean(p(this,oe,"f")),this.describe(p(this,oe,"f"),e),this}wrap(t){return I("<number|null|undefined>",[t],arguments.length),p(this,X,"f").wrap(t),this}[(bt=new WeakMap,Je=new WeakMap,Fo=new WeakMap,zt=new WeakMap,jt=new WeakMap,Zo=new WeakMap,Re=new WeakMap,ze=new WeakMap,Qo=new WeakMap,vt=new WeakMap,Yo=new WeakMap,kt=new WeakMap,ee=new WeakMap,Tt=new WeakMap,Ut=new WeakMap,tn=new WeakMap,fo=new WeakMap,yt=new WeakMap,J=new WeakMap,en=new WeakMap,on=new WeakMap,_t=new WeakMap,ve=new WeakMap,lo=new WeakMap,ke=new WeakMap,Ee=new WeakMap,nn=new WeakMap,V=new WeakMap,Ue=new WeakMap,Ke=new WeakMap,Ve=new WeakMap,X=new WeakMap,rn=new WeakMap,oe=new WeakMap,gt=new WeakMap,wi)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(e){}return t}[bi](){return{log:(...t)=>{if(!this[sn]())console.log(...t);if(j(this,Tt,!0,"f"),p(this,yt,"f").length)j(this,yt,p(this,yt,"f")+`
220
+ `,"f");j(this,yt,p(this,yt,"f")+t.join(" "),"f")},error:(...t)=>{if(!this[sn]())console.error(...t);if(j(this,Tt,!0,"f"),p(this,yt,"f").length)j(this,yt,p(this,yt,"f")+`
221
+ `,"f");j(this,yt,p(this,yt,"f")+t.join(" "),"f")}}}[qn](t){co(p(this,J,"f")).forEach((e)=>{if(((n)=>n==="configObjects")(e))return;let o=p(this,J,"f")[e];if(Array.isArray(o)){if(o.includes(t))o.splice(o.indexOf(t),1)}else if(typeof o==="object")delete o[t]}),delete p(this,X,"f").getDescriptions()[t]}[Ci](t,e,o){if(!p(this,Qo,"f")[o])p(this,V,"f").process.emitWarning(t,e),p(this,Qo,"f")[o]=!0}[$i](){p(this,Yo,"f").push({options:p(this,J,"f"),configObjects:p(this,J,"f").configObjects.slice(0),exitProcess:p(this,vt,"f"),groups:p(this,ee,"f"),strict:p(this,Ue,"f"),strictCommands:p(this,Ke,"f"),strictOptions:p(this,Ve,"f"),completionCommand:p(this,jt,"f"),output:p(this,yt,"f"),exitError:p(this,Re,"f"),hasOutput:p(this,Tt,"f"),parsed:this.parsed,parseFn:p(this,_t,"f"),parseContext:p(this,ve,"f")}),p(this,X,"f").freeze(),p(this,gt,"f").freeze(),p(this,bt,"f").freeze(),p(this,kt,"f").freeze()}[Si](){let t="",e;if(/\b(node|iojs|electron)(\.exe)?$/.test(p(this,V,"f").process.argv()[0]))e=p(this,V,"f").process.argv().slice(1,2);else e=p(this,V,"f").process.argv().slice(0,1);if(t=e.map((o)=>{let n=this[Ii](p(this,Je,"f"),o);return o.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<o.length?n:o}).join(" ").trim(),p(this,V,"f").getEnv("_")&&p(this,V,"f").getProcessArgvBin()===p(this,V,"f").getEnv("_"))t=p(this,V,"f").getEnv("_").replace(`${p(this,V,"f").path.dirname(p(this,V,"f").process.execPath())}/`,"");return t}[qe](){return p(this,on,"f")}[Pi](){return p(this,rn,"f")}[Xn](){if(!p(this,ze,"f"))return;let t=p(this,V,"f").getEnv("LC_ALL")||p(this,V,"f").getEnv("LC_MESSAGES")||p(this,V,"f").getEnv("LANG")||p(this,V,"f").getEnv("LANGUAGE")||"en_US";this.locale(t.replace(/[.:].*/,""))}[yi](){return this[Zn]().version||"unknown"}[Ri](t){let e=t["--"]?t["--"]:t._;for(let o=0,n;(n=e[o])!==void 0;o++)if(p(this,V,"f").Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`))))e[o]=Number(n);return t}[Zn](t){let e=t||"*";if(p(this,lo,"f")[e])return p(this,lo,"f")[e];let o={};try{let n=t||p(this,V,"f").mainFilename;if(!t&&p(this,V,"f").path.extname(n))n=p(this,V,"f").path.dirname(n);let r=p(this,V,"f").findUp(n,(i,s)=>{if(s.includes("package.json"))return"package.json";else return});Bt(r,void 0,p(this,V,"f")),o=JSON.parse(p(this,V,"f").readFileSync(r,"utf8"))}catch(n){}return p(this,lo,"f")[e]=o||{},p(this,lo,"f")[e]}[Me](t,e){e=[].concat(e),e.forEach((o)=>{o=this[tr](o),p(this,J,"f")[t].push(o)})}[ho](t,e,o,n){this[Yn](t,e,o,n,(r,i,s)=>{p(this,J,"f")[r][i]=s})}[Qn](t,e,o,n){this[Yn](t,e,o,n,(r,i,s)=>{p(this,J,"f")[r][i]=(p(this,J,"f")[r][i]||[]).concat(s)})}[Yn](t,e,o,n,r){if(Array.isArray(o))o.forEach((i)=>{t(i,n)});else if(((i)=>typeof i==="object")(o))for(let i of co(o))t(i,o[i]);else r(e,this[tr](o),n)}[tr](t){if(t==="__proto__")return"___proto___";return t}[er](t,e){return this[ho](this[er].bind(this),"key",t,e),this}[or](){var t,e,o,n,r,i,s,c,u,a,l,h;let d=p(this,Yo,"f").pop();Bt(d,void 0,p(this,V,"f"));let g;t=this,e=this,o=this,n=this,r=this,i=this,s=this,c=this,u=this,a=this,l=this,h=this,{options:{set value(x){j(t,J,x,"f")}}.value,configObjects:g,exitProcess:{set value(x){j(e,vt,x,"f")}}.value,groups:{set value(x){j(o,ee,x,"f")}}.value,output:{set value(x){j(n,yt,x,"f")}}.value,exitError:{set value(x){j(r,Re,x,"f")}}.value,hasOutput:{set value(x){j(i,Tt,x,"f")}}.value,parsed:this.parsed,strict:{set value(x){j(s,Ue,x,"f")}}.value,strictCommands:{set value(x){j(c,Ke,x,"f")}}.value,strictOptions:{set value(x){j(u,Ve,x,"f")}}.value,completionCommand:{set value(x){j(a,jt,x,"f")}}.value,parseFn:{set value(x){j(l,_t,x,"f")}}.value,parseContext:{set value(x){j(h,ve,x,"f")}}.value}=d,p(this,J,"f").configObjects=g,p(this,X,"f").unfreeze(),p(this,gt,"f").unfreeze(),p(this,bt,"f").unfreeze(),p(this,kt,"f").unfreeze()}[Ei](t,e){return Ne(e,(o)=>{return t(o),o})}getInternalMethods(){return{getCommandInstance:this[Mi].bind(this),getContext:this[Oi].bind(this),getHasOutput:this[Wi].bind(this),getLoggerInstance:this[Di].bind(this),getParseContext:this[Fi].bind(this),getParserConfiguration:this[qe].bind(this),getUsageConfiguration:this[Pi].bind(this),getUsageInstance:this[Bi].bind(this),getValidationInstance:this[Li].bind(this),hasParseCallback:this[sn].bind(this),isGlobalContext:this[Ai].bind(this),postProcess:this[Xe].bind(this),reset:this[nr].bind(this),runValidation:this[rr].bind(this),runYargsParserAndExecuteCommands:this[Bo].bind(this),setHasOutput:this[ji].bind(this)}}[Mi](){return p(this,bt,"f")}[Oi](){return p(this,Fo,"f")}[Wi](){return p(this,Tt,"f")}[Di](){return p(this,fo,"f")}[Fi](){return p(this,ve,"f")||{}}[Bi](){return p(this,X,"f")}[Li](){return p(this,gt,"f")}[sn](){return!!p(this,_t,"f")}[Ai](){return p(this,tn,"f")}[Xe](t,e,o,n){if(o)return t;if(ht(t))return t;if(!e)t=this[wi](t);if(this[qe]()["parse-positional-numbers"]||this[qe]()["parse-positional-numbers"]===void 0)t=this[Ri](t);if(n)t=He(t,this,p(this,kt,"f").getMiddleware(),!1);return t}[nr](t={}){j(this,J,p(this,J,"f")||{},"f");let e={};e.local=p(this,J,"f").local||[],e.configObjects=p(this,J,"f").configObjects||[];let o={};e.local.forEach((i)=>{o[i]=!0,(t[i]||[]).forEach((s)=>{o[s]=!0})}),Object.assign(p(this,ke,"f"),Object.keys(p(this,ee,"f")).reduce((i,s)=>{let c=p(this,ee,"f")[s].filter((u)=>!(u in o));if(c.length>0)i[s]=c;return i},{})),j(this,ee,{},"f");let n=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(n.forEach((i)=>{e[i]=(p(this,J,"f")[i]||[]).filter((s)=>!o[s])}),r.forEach((i)=>{e[i]=Pe(p(this,J,"f")[i],(s)=>!o[s])}),e.envPrefix=p(this,J,"f").envPrefix,j(this,J,e,"f"),j(this,X,p(this,X,"f")?p(this,X,"f").reset(o):fi(this,p(this,V,"f")),"f"),j(this,gt,p(this,gt,"f")?p(this,gt,"f").reset(o):xi(this,p(this,X,"f"),p(this,V,"f")),"f"),j(this,bt,p(this,bt,"f")?p(this,bt,"f").reset():si(p(this,X,"f"),p(this,gt,"f"),p(this,kt,"f"),p(this,V,"f")),"f"),!p(this,zt,"f"))j(this,zt,pi(this,p(this,X,"f"),p(this,bt,"f"),p(this,V,"f")),"f");return p(this,kt,"f").reset(),j(this,jt,null,"f"),j(this,yt,"","f"),j(this,Re,null,"f"),j(this,Tt,!1,"f"),this.parsed=!1,this}[Ii](t,e){return p(this,V,"f").path.relative(t,e)}[Bo](t,e,o,n=0,r=!1){let i=!!o||r;t=t||p(this,Ee,"f"),p(this,J,"f").__=p(this,V,"f").y18n.__,p(this,J,"f").configuration=this[qe]();let s=!!p(this,J,"f").configuration["populate--"],c=Object.assign({},p(this,J,"f").configuration,{"populate--":!0}),u=p(this,V,"f").Parser.detailed(t,Object.assign({},p(this,J,"f"),{configuration:{"parse-positional-numbers":!1,...c}})),a=Object.assign(u.argv,p(this,ve,"f")),l=void 0,h=u.aliases,d=!1,g=!1;if(Object.keys(a).forEach((x)=>{if(x===p(this,Ut,"f")&&a[x])d=!0;else if(x===p(this,oe,"f")&&a[x])g=!0}),a.$0=this.$0,this.parsed=u,n===0)p(this,X,"f").clearCachedHelpMessage();try{if(this[Xn](),e)return this[Xe](a,s,!!o,!1);if(p(this,Ut,"f")){if([p(this,Ut,"f")].concat(h[p(this,Ut,"f")]||[]).filter((R)=>R.length>1).includes(""+a._[a._.length-1]))a._.pop(),d=!0}j(this,tn,!1,"f");let x=p(this,bt,"f").getCommands(),m=p(this,zt,"f").completionKey in a,b=d||m||r;if(a._.length){if(x.length){let S;for(let R=n||0,y;a._[R]!==void 0;R++)if(y=String(a._[R]),x.includes(y)&&y!==p(this,jt,"f")){let M=p(this,bt,"f").runCommand(y,this,u,R+1,r,d||g||r);return this[Xe](M,s,!!o,!1)}else if(!S&&y!==p(this,jt,"f")){S=y;break}if(!p(this,bt,"f").hasDefaultCommand()&&p(this,nn,"f")&&S&&!b)p(this,gt,"f").recommendCommands(S,x)}if(p(this,jt,"f")&&a._.includes(p(this,jt,"f"))&&!m){if(p(this,vt,"f"))ye(!0);this.showCompletionScript(),this.exit(0)}}if(p(this,bt,"f").hasDefaultCommand()&&!b){let S=p(this,bt,"f").runCommand(null,this,u,0,r,d||g||r);return this[Xe](S,s,!!o,!1)}if(m){if(p(this,vt,"f"))ye(!0);t=[].concat(t);let S=t.slice(t.indexOf(`--${p(this,zt,"f").completionKey}`)+1);return p(this,zt,"f").getCompletion(S,(R,y)=>{if(R)throw new lt(R.message);(y||[]).forEach((M)=>{p(this,fo,"f").log(M)}),this.exit(0)}),this[Xe](a,!s,!!o,!1)}if(!p(this,Tt,"f")){if(d){if(p(this,vt,"f"))ye(!0);i=!0,this.showHelp("log"),this.exit(0)}else if(g){if(p(this,vt,"f"))ye(!0);i=!0,p(this,X,"f").showVersion("log"),this.exit(0)}}if(!i&&p(this,J,"f").skipValidation.length>0)i=Object.keys(a).some((S)=>p(this,J,"f").skipValidation.indexOf(S)>=0&&a[S]===!0);if(!i){if(u.error)throw new lt(u.error.message);if(!m){let S=this[rr](h,{},u.error);if(!o)l=He(a,this,p(this,kt,"f").getMiddleware(),!0);if(l=this[Ei](S,l!==null&&l!==void 0?l:a),ht(l)&&!o)l=l.then(()=>{return He(a,this,p(this,kt,"f").getMiddleware(),!1)})}}}catch(x){if(x instanceof lt)p(this,X,"f").fail(x.message,x);else throw x}return this[Xe](l!==null&&l!==void 0?l:a,s,!!o,!0)}[rr](t,e,o,n){let r={...this.getDemandedOptions()};return(i)=>{if(o)throw new lt(o.message);p(this,gt,"f").nonOptionCount(i),p(this,gt,"f").requiredArguments(i,r);let s=!1;if(p(this,Ke,"f"))s=p(this,gt,"f").unknownCommands(i);if(p(this,Ue,"f")&&!s)p(this,gt,"f").unknownArguments(i,t,e,!!n);else if(p(this,Ve,"f"))p(this,gt,"f").unknownArguments(i,t,{},!1,!1);p(this,gt,"f").limitedChoices(i),p(this,gt,"f").implications(i),p(this,gt,"f").conflicting(i)}}[ji](){j(this,Tt,!0,"f")}[Ze](t){if(typeof t==="string")p(this,J,"f").key[t]=!0;else for(let e of t)p(this,J,"f").key[e]=!0}}function ci(t){return!!t&&typeof t.getInternalMethods==="function"}var $f=Ti(zn),Gi=$f;import{readFileSync as lp}from"fs";import{join as hp}from"path";var up=JSON.parse(lp(hp(import.meta.dir,"../../package.json"),"utf-8"));if(process.argv.length===2){let{launchTUI:t}=await Promise.resolve().then(() => (tc(),Ys));await t()}else{let[t,e,o,n,r,i,s,c,u,a,l,h,d,g,x,m,b,S,R,y]=await Promise.all([Promise.resolve().then(() => (ac(),cc)),Promise.resolve().then(() => (lc(),fc)),Promise.resolve().then(() => (pc(),uc)),Promise.resolve().then(() => (mc(),dc)),Promise.resolve().then(() => (Cc(),bc)),Promise.resolve().then(() => (Oc(),Mc)),Promise.resolve().then(() => (Dc(),Wc)),Promise.resolve().then(() => (Ac(),Lc)),Promise.resolve().then(() => (Tc(),jc)),Promise.resolve().then(() => (Hc(),Gc)),Promise.resolve().then(() => (zc(),Jc)),Promise.resolve().then(() => (kc(),vc)),Promise.resolve().then(() => (Kc(),Uc)),Promise.resolve().then(() => (qc(),Vc)),Promise.resolve().then(() => (ia(),ra)),Promise.resolve().then(() => (ca(),sa)),Promise.resolve().then(() => (fa(),aa)),Promise.resolve().then(() => (xa(),ma)),Promise.resolve().then(() => (wa(),ga)),Promise.resolve().then(() => (Ea(),Ra))]);Gi(Jn(process.argv)).locale("en").scriptName("omw").version(`oh-my-worktree v${up.version}`).alias("version","v").help("help").alias("help","h").option("no-color",{type:"boolean",description:"Disable color output"}).command(t.default).command(e.default).command(o.default).command(n.default).command(r.default).command(i.default).command(s.default).command(c.default).command(u.default).command(a.default).command(l.default).command(h.default).command(d.default).command(g.default).command(x.default).command(m.default).command(b.default).command(S.default).command(R.default).command(y.default).completion("completion","Generate shell completion script").demandCommand(1,"Please specify a command. Run --help to see available commands.").strict().parse()}