@kaisers-io/refs 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/refs.mjs +21 -17
  2. package/package.json +1 -1
package/dist/refs.mjs CHANGED
@@ -311,7 +311,7 @@ let ks=/^[a-z0-9-_]+$/i;function As(e){let t=typeof e;if(t===`object`){if(Array.
311
311
  `)+Ls(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=Ns(t[c],e,r,i),a+=`
312
312
  `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function Rs(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(As(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=Ls(0,e,``,t,n);return r[r.length-1]===`
313
313
  `?r:r+`
314
- `}const V=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,zs=async(e,t)=>{await a(ne(e),{recursive:!0});let n=`${e}.tmp-${se()}`;await ee(n,t,`utf8`),await l(n,e)},H=e=>{let t=ae(e.REFS_HOME??m(de(),`.kaisers-io`,`refs`));return{configPath:m(t,`config.toml`),hooksDir:m(t,`hooks`),locksDir:m(t,`locks`),root:t,sourcesDir:m(t,`sources`),statePath:m(t,`state.json`)}},U=(e,t)=>m(e.sourcesDir,...t.split(`/`)),Bs=e=>`${e.configPath}.bak`,Vs=e=>{let t=[],n=e;for(;!le(n);){let e=ne(n);if(e===n)break;t.unshift(te(n)),n=e}return{ancestor:n,missing:t}},Hs=e=>{let{ancestor:t,missing:n}=Vs(e),r=ue(t);return n.length===0?r:m(r,...n)},Us=(e,t)=>{let n=ie(Hs(e.sourcesDir),Hs(t)),r=n===`..`||n.startsWith(`..`+oe);if(!(n!==``&&!r&&!re(n)))throw b(`path escapes sources directory (containment violation): ${t}`)},Ws=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gs=(e,t)=>Ws(e)?e:t,Ks=async e=>{try{return await o(e.configPath,`utf8`)}catch(e){throw V(e)?v(`no config found — run: refs init`):e}},qs=(e,t)=>{try{return Os(e)}catch(e){throw e instanceof B?b(`invalid TOML in ${t}: ${e.message}`):e}},Js=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,Ys=e=>{let{meta:t}=e;if(!Ws(t))return;let n=t.schema_version;if(Js(n))return n},Xs=(e,t)=>{let n=Ys(e);if(n===void 0)throw b(`config schema version is missing or invalid in ${t} — run: refs migrate`);if(n>1)throw b(`config schema ${n} is newer than this CLI supports — upgrade refs`);if(n<1)throw b(`config schema ${n} is older than expected 1 — run: refs migrate`)},W=async e=>{let t=await Ks(e),n=qs(t,e.configPath);Xs(n,e.configPath);let r=ss.safeParse(n);if(!r.success)throw b(O(r.error));return r.data},Zs=async(e,t)=>{let n=ss.safeParse(t);if(!n.success)throw b(O(n.error));await zs(e.configPath,Rs(n.data))},Qs=async e=>{try{return await f(e),!0}catch(e){if(V(e))return!1;throw e}},$s=async(e,t)=>await Qs(e.configPath)?`noop`:(await zs(e.configPath,`# refs configuration
314
+ `}const V=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,zs=async(e,t)=>{await a(ne(e),{recursive:!0});let n=`${e}.tmp-${se()}`;await ee(n,t,`utf8`),await l(n,e)},H=e=>{let t=ae(e.REFS_HOME??m(de(),`.kaisers-io`,`refs`));return{configPath:m(t,`config.toml`),hooksDir:m(t,`hooks`),locksDir:m(t,`locks`),root:t,sourcesDir:m(t,`sources`),statePath:m(t,`state.json`)}},U=(e,t)=>m(e.sourcesDir,...t.split(`/`)),Bs=e=>`${e.configPath}.bak`,Vs=e=>{let t=[],n=e;for(;!le(n);){let e=ne(n);if(e===n)break;t.unshift(te(n)),n=e}return{ancestor:n,missing:t}},Hs=e=>{let{ancestor:t,missing:n}=Vs(e),r=ue(t);return n.length===0?r:m(r,...n)},Us=(e,t,n)=>{let r=ie(Hs(e),Hs(t)),i=r===`..`||r.startsWith(`..`+oe);if(!(r!==``&&!i&&!re(r)))throw b(`path escapes ${n} (containment violation): ${t}`)},Ws=(e,t)=>{Us(e.sourcesDir,t,`sources directory`)},Gs=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ks=(e,t)=>Gs(e)?e:t,qs=async e=>{try{return await o(e.configPath,`utf8`)}catch(e){throw V(e)?v(`no config found — run: refs init`):e}},Js=(e,t)=>{try{return Os(e)}catch(e){throw e instanceof B?b(`invalid TOML in ${t}: ${e.message}`):e}},Ys=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,Xs=e=>{let{meta:t}=e;if(!Gs(t))return;let n=t.schema_version;if(Ys(n))return n},Zs=(e,t)=>{let n=Xs(e);if(n===void 0)throw b(`config schema version is missing or invalid in ${t} — run: refs migrate`);if(n>1)throw b(`config schema ${n} is newer than this CLI supports — upgrade refs`);if(n<1)throw b(`config schema ${n} is older than expected 1 — run: refs migrate`)},W=async e=>{let t=await qs(e),n=Js(t,e.configPath);Zs(n,e.configPath);let r=ss.safeParse(n);if(!r.success)throw b(O(r.error));return r.data},Qs=async(e,t)=>{let n=ss.safeParse(t);if(!n.success)throw b(O(n.error));await zs(e.configPath,Rs(n.data))},$s=async e=>{try{return await f(e),!0}catch(e){if(V(e))return!1;throw e}},ec=async(e,t)=>await $s(e.configPath)?`noop`:(await zs(e.configPath,`# refs configuration
315
315
  #
316
316
  # Every global setting under [settings] can also be set per-ref: add the same
317
317
  # key directly inside a [refs."host/owner/repo"] table to override it just for
@@ -342,29 +342,33 @@ sync_ttl = "1h"
342
342
  # tag_format = "v{version}"
343
343
  # # Per-ref overrides of [settings] go in the same table, e.g.:
344
344
  # # clone_mode = "full"
345
- `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),ec=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:Ws(t)&&Ws(r)&&(n[e]=ec(t,r))}return n},tc={meta:{},refs:{},settings:{}},nc=async e=>{try{return await Ks(e)}catch(e){if(e instanceof _&&e.code===`not_found`)return;throw e}},rc=e=>{if(e!==void 0&&e>1)throw b(`config schema ${e} is newer than this CLI supports — upgrade refs`)},ic=async(e,t,n)=>{let r=Gs(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await zs(e.configPath,Rs(i))},ac=async(e,t,n)=>{await r(e.configPath,Bs(e));let i=ec(t,tc),a=Gs(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=ss.safeParse(o);if(!s.success)throw b(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${Bs(e)}): ${O(s.error)}`);await zs(e.configPath,Rs(o))},oc=async(e,t)=>(await $s(e,t),`seeded`),sc=async(e,t,n)=>{let r=qs(t,e.configPath),i=Ys(r);return rc(i),i===1?(await ic(e,r,n),`noop`):(await ac(e,r,n),`migrated`)},cc=async(e,t)=>{let n=await nc(e);return n===void 0?oc(e,t):sc(e,n,t)},lc=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
346
- `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},uc=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,dc=(e,t)=>{let n=[];if(e&&n.push(`checkout had local changes (managed checkouts are read-only) — discarded and restored to the remote state`),t!==void 0&&n.push(t),n.length!==0)return n.join(` | `)},fc=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:uc(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=dc(n,r);return o!==void 0&&(a.warning=o),a},pc=(e,t,n)=>{let r={dirty:t,shas:n};return e.branchRenamedTo!==void 0&&(r.branchRenamedTo=e.branchRenamedTo),e.warning!==void 0&&(r.setHeadWarning=e.warning),r},G=e=>le(m(e,`.git`)),mc=e=>`refusing to sync ${e}: not a refs-managed checkout`,hc=async(e,t)=>{if(!G(t))throw b(mc(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw b(mc(t))},gc=/filtering not recognized/iu,_c=e=>e===void 0?{}:{cwd:e},K=(e,t,n)=>({action:e,args:t,cmd:`git`,..._c(n)}),vc=async(e,t)=>{let n=await e.run(t.cmd,t.args,_c(t.cwd));if(n.exitCode===0)return n;let r=n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`;throw b(`${t.action} failed: ${r}`)},yc=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(t.cloneUrl,t.dest);let r=await vc(e,K(`git clone`,n));return await vc(e,K(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&gc.test(r.stderr)?{effectiveMode:`full`,warning:`server did not honour the partial-clone filter (blob:none); fell back to a full clone`}:{effectiveMode:t.mode}},bc=async(e,t)=>{let n=await e.run(`git`,[`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],{cwd:t});if(n.exitCode!==0)return;let r=n.stdout.trim();return r.startsWith(`origin/`)?r.slice(7):r},xc=async(e,t)=>{let n=await bc(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await bc(e,t);if(r!==void 0)return r;throw b(`could not detect the default branch for checkout: ${t}`)},Sc=async(e,t)=>(await vc(e,K(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),Cc=async(e,t)=>(await vc(e,K(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,wc=async(e,t)=>{await vc(e,K(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await xc(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${lc(n)}`),i},Tc=e=>[K(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),K(`git clean -fd`,[`clean`,`-fd`],e)],Ec=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Tc(r)),a.push(K(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),K(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await vc(e,t)},Dc=async(e,t)=>{await hc(e,t.dir);let n=await Sc(e,t.dir),r=await wc(e,t),i=await Cc(e,t.dir);return await Ec(e,{branch:r.branch,dir:t.dir,dirty:i}),fc(pc(r,i,{newSha:await Sc(e,t.dir),oldSha:n}))},Oc=async(e,t,n=20)=>(await vc(e,K(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
347
- `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),kc=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,Ac=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
348
- `),jc=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await zs(r,Ac),await t(r,493)}))},Mc=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Nc=/\d+\.\d+\.\d+/gu,Pc=e=>es.safeParse(e).success,Fc=e=>{let t=e.match(Nc);return t!==null&&t.length>1},Ic=e=>{let t=Mc.exec(e);if(!t||Fc(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Pc(r))return r},Lc=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},Rc=e=>{let t=new Map;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===void 0)continue;let i=Ic(r);i&&Lc(t,i,n)}return t},zc=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Bc=e=>{let t=[...e.entries()];if(t.length===0)return null;let n=t[0];if(!n)return null;let[r,i]=n;return t.slice(1).reduce(({format:e,data:t},[n,r])=>zc(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Vc=e=>{let t=Rc(e);return Bc(t)},Hc=(e,t)=>e.replaceAll(`{version}`,()=>t),Uc=async(e,t,n,r)=>{let i=Hc(n,r);if(!await kc(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Wc=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,q=e=>{let t=e.replace(Wc,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},Gc=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,Kc=/^git\+/u,qc={"https:":`443`,"ssh:":`22`},Jc=e=>e.replace(/\.git$/u,``),Yc=e=>e.split(`/`).some(e=>e===`.`||e===`..`),Xc=e=>e.includes(`\\`),Zc=e=>e.includes(`%`),Qc=e=>{let t=z.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${q(e)}' is invalid`);return t.data},$c=({host:e,port:t,protocol:n})=>{let r=qc[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},el=e=>{let t=Jc(e.path.replace(/^\/+/u,``).replace(/\/+$/u,``));return Qc(`${$c(e)}/${t}`)},tl=e=>{let t=decodeURIComponent(e).split(`/`).filter(e=>e!==``);if(t.length<2)throw b(`not a supported git url: file url path must have at least 2 segments`);let n=t.at(-2)??``,r=t.at(-1)??``;return Qc(`local/${n}/${r}`)},nl=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${q(t)}`)}},rl=e=>{if(e.password!==``)throw b(`not a supported git url: credentials embedded in url`);if(e.protocol===`https:`&&e.username!==``)throw b(`not a supported git url: credentials embedded in https url`)},il=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return tl(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return rl(e),el({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},al=(e,t)=>{if(Zc(e))throw b(`not a supported git url: percent-encoding not supported in ${q(t)}`);if(e.includes(`:`))throw b(`not a supported git url: ambiguous ':' in scp-style path ${q(t)}; use the ssh:// url form instead`);if(e.startsWith(`/`)||e.startsWith(`~`))throw b(`not a supported git url: ambiguous absolute/home-relative scp path in ${q(t)}; use the ssh:// url form instead`)},ol=(e,t)=>{let n=e.groups?.path??``;return al(n,t),el({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},sl=(e,t)=>{if(Xc(e))throw b(`not a supported git url: backslash not allowed in ${q(t)}`)},cl=(e,t)=>{if(Yc(e))throw b(`not a supported git url: path traversal segment in ${q(t)}`)},ll=(e,t,n)=>{if(e.protocol!==`file:`&&Zc(t))throw b(`not a supported git url: percent-encoding not supported in ${q(n)}`)},J=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(Kc,``);sl(r,e),cl(r,e);let i=Gc.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:ol(i,e)};let a=nl(r,e);return ll(a,r,e),{cloneUrl:r,key:il(a,n)}},ul=`.git`,dl=e=>e.replace(/^\/+/u,``).replace(/\/+$/u,``),fl=e=>e.endsWith(ul)?e:`${e}${ul}`,pl=(e,t)=>`https://${e.toLowerCase()}/${dl(t)}`,ml=(e,t)=>`git@${e.toLowerCase()}:${fl(dl(t))}`,hl=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},gl=(e,t,n)=>{let r=qc[e.protocol];if(e.port!==``&&e.port!==r)throw b(`cannot apply git_transport=${t} to ${q(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},_l=(e,t)=>t===`https`?pl(e.hostname,e.pathname):ml(e.hostname,e.pathname),vl=(e,t,n)=>{let r=J(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${q(e)}' → '${t}' (key '${n}' → '${r}')`);return t},yl=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return vl(t.cloneUrl,pl(n,r),t.originalKey)},bl=e=>{let t=nl(e.cloneUrl,e.cloneUrl);return hl(t.protocol)===e.transport?e.cloneUrl:(gl(t,e.transport,e.cloneUrl),vl(e.cloneUrl,_l(t,e.transport),e.originalKey))},xl=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:J(e).key,transport:t},r=Gc.exec(e);return r?.groups===void 0?bl(n):yl(r,n)},Sl=`meta.json`,Cl=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},wl=e=>{try{return process.kill(e,0),!0}catch(e){return Cl(e)!==`ESRCH`}},Tl=e=>{try{return JSON.parse(e)}catch{return}},El=async e=>{try{return await o(e,`utf8`)}catch{return}},Dl=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Ol=e=>{if(typeof e!=`object`||!e)return;let t=e,{pid:n}=t,r=Dl(t.acquired_at);if(!(typeof n!=`number`||r===void 0))return{acquiredAtMs:r,pid:n}},kl=async e=>{let t=await El(m(e,Sl));if(t!==void 0)return Ol(Tl(t))},Al=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},jl=async e=>{let t=await El(m(e,Sl));if(t!==void 0)return Al(Tl(t))},Ml=async e=>{try{return(await f(e)).mtimeMs}catch{return}},Nl=async(e,t)=>{let n=m(e,Sl),r=`${n}.tmp-${se()}`;await ee(r,t,`utf8`),await l(r,n)},Pl=async(e,t)=>{await Nl(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Fl=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/u,Il=async e=>{let t=await kl(e);if(t===void 0){let t=await Ml(e);return t===void 0?!1:Date.now()-t>5e3}return Date.now()-t.acquiredAtMs>6e5?!0:!wl(t.pid)},Ll=async(e,t)=>{try{await Pl(e,t)}catch(e){if(Cl(e)===`ENOENT`)return`retry`;throw e}return t},Rl=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){if(Cl(e)===`EEXIST`)return!1;throw e}},zl=async e=>{if(!await Rl(e))return;let t=await Ll(e,se());return t===`retry`?zl(e):t},Bl=e=>m(e.locksDir,`${e.name}.steal-claim`),Vl=e=>m(e.locksDir,`${e.name}.steal.${se()}`),Hl=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){if(Cl(e)===`EEXIST`)return!1;throw e}},Ul=async e=>{let t=await Ml(e);return t!==void 0&&Date.now()-t>2e3},Wl=async e=>await Hl(e)?!0:await Ul(e)?(await u(e,{force:!0,recursive:!0}),Hl(e)):!1,Gl=async e=>{let t=Vl(e);try{await l(e.lockPath,t)}catch(e){if(Cl(e)===`ENOENT`)return;throw e}return t},Kl=async e=>{if(!await Il(e.lockPath))return;let t=await Gl(e);t!==void 0&&await u(t,{force:!0,recursive:!0})},ql=async e=>{let t=Bl(e);if(await Wl(t))try{await Kl(e)}finally{await u(t,{force:!0,recursive:!0})}},Jl=async(e,t)=>{if(await Il(e.lockPath)){await ql(e);return}if(Date.now()>=t)throw ve(`lock ${e.name} is held — another refs process is running`);await fe(100)},Yl=async(e,t)=>{let n=await zl(e.lockPath);return n===void 0?(await Jl(e,t),Yl(e,t)):n},Xl=async(e,t)=>{await jl(e)===t&&await u(e,{force:!0,recursive:!0})},Zl=e=>{if(e===`.`||e===`..`||!Fl.test(e))throw b(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.:-" are allowed, and it may not be "." or "..": ${e}`)},Y=async(e,t,n,r)=>{Zl(t);let i={lockPath:m(e.locksDir,t),locksDir:e.locksDir,name:t};await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await Yl(i,o);try{return await n()}finally{await Xl(i.lockPath,s)}},Ql=no({directory:I().optional(),url:I().optional()}),$l=no({repository:io([I(),Ql]).optional()}),eu=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,tu=new Set([`node_modules`,`favicon.ico`]),nu=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),ru=e=>{let t=e.split(`/`);return t.length>=2?t[1]:e},iu=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!eu.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=ru(e);if(tu.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},au=e=>e.replace(`/`,`%2F`),ou=e=>typeof e==`string`?e:e?.url,su=e=>{if(typeof e==`object`&&e?.directory){let t=ts.safeParse(e.directory);if(t.success)return t.data}},cu=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},lu=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${au(t)}`);if(n.status===404)throw v(`npm package '${t}' not found`);if(n.status!==200)throw b(`failed to fetch npm package '${t}': status ${n.status}`);let r=await cu(n,t),i=$l.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},uu=(e,t)=>{try{return J(e)}catch{throw nu(t)}},du=async(e,t)=>{iu(t);let n=await lu(e,t),r=ou(n.repository);if(r===void 0||r===``)throw nu(t);let{cloneUrl:i,key:a}=uu(r,t),o=su(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},fu=new Set;let pu=!1;const mu=()=>{for(let e of fu)try{e.kill(`SIGKILL`)}catch{}},hu=[`SIGINT`,`SIGTERM`,`SIGHUP`],gu=e=>{let t=()=>{mu(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},_u=()=>{pu||(pu=!0,hu.forEach(e=>{gu(e)}),process.on(`exit`,mu))},vu=()=>{let e=[],t=0,n=!1;return{finish:()=>({text:Buffer.concat(e).toString(`utf8`),truncated:n}),push:r=>{if(n)return;let i=67108864-t;if(r.length<=i){e.push(r),t+=r.length;return}i>0&&e.push(r.subarray(0,i)),n=!0}}},yu=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
349
- `),bu=(e,t,n)=>{let r=e;return t.truncated&&(r=yu(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=yu(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},xu={clear:()=>{},markedTimedOut:()=>!1},Su=(e,t)=>{if(t===void 0)return xu;let n=!1,r,i=setTimeout(()=>{n=!0,e.kill(`SIGTERM`),r=setTimeout(()=>{e.kill(`SIGKILL`)},2e3)},t);return{clear:()=>{clearTimeout(i),r!==void 0&&clearTimeout(r)},markedTimedOut:()=>n}},Cu=e=>e===void 0?{}:{cwd:e},wu=(e,t)=>yu(e,`refs: command timed out after ${String(t)}ms`),Tu=(e,t)=>({exitCode:124,stderr:wu(e,t),stdout:``,timedOut:!0}),Eu=(e,t,n)=>{let r=ge(e,t,{...Cu(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});fu.add(r);let i=vu(),a=vu();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:Su(r,n?.timeoutMs)}},Du=(e,t,n)=>{try{return Eu(e,t,n)}catch(e){return{exitCode:127,stderr:ku(e),stdout:``}}},Ou=e=>!(`child`in e),ku=e=>e instanceof Error?e.message:String(e),Au=async e=>{try{let[t]=await me(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:ku(e)}}},ju=e=>e===null?1:e,Mu=e=>e.timedOut?Tu(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?{exitCode:ju(e.code),stderr:bu(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text}:{exitCode:127,stderr:yu(e.stderr.text,e.errorMessage),stdout:e.stdout.text};var Nu=class{async run(e,t,n){_u();let r=Du(e,t,n);if(Ou(r))return r;let i=await Au(r.child);return fu.delete(r.child),r.timeout.clear(),Mu({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Pu=as.partial({description:!0}),Fu=R({default_branch:I().min(1),key:z,tag_format_candidate:es.nullable(),url:I().min(1)});Fu.extend({description:I().default(``),packages:Bo(Pu)});const Iu=Fu.extend({description:I().min(1),packages:Bo(as)}),Lu=R({effective_clone_mode:Qo.optional(),head_sha:I().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:I().optional(),last_fetched_at:ra().optional(),pending_proposal_at:ra().optional()}),Ru=R({refs:Ro(e=>e.length>=1&&!Lo.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,co(I(),Lu)).default({})}),X=(e,t,n)=>t?.[e]??n[e],zu=async e=>{try{return await o(e.statePath,`utf8`)}catch(e){if(V(e))return;throw e}},Bu=e=>{try{return JSON.parse(e)}catch{return}},Z=async e=>{let t=await zu(e);if(t===void 0)return Ru.parse({});let n=Bu(t);if(n===void 0)return Ru.parse({});let r=Ru.safeParse(n);return r.success?r.data:Ru.parse({})},Vu=async(e,t)=>{let n=Ru.safeParse(t);if(!n.success)throw b(O(n.error));await zs(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Hu=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,Uu=/^packages:\s*(?:#.*)?$/u,Wu=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gu=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!Wu(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},Ku=e=>{let t=[],n=!1;for(let r of e){let e=r.trim();if(Uu.test(r)){n=!0;continue}if(!n)continue;if(e&&!e.startsWith(`-`)&&e.includes(`:`))break;if(!e.startsWith(`-`))continue;let i=Hu.exec(r)?.groups?.pattern?.trim();i&&i!==``&&t.push(i)}return t},qu=e=>{let{name:t}=e;if(typeof t==`string`)return t},Ju=e=>{let{description:t}=e;if(typeof t==`string`)return t},Yu=/[/\\]/u,Xu=e=>re(e)?!1:e.split(Yu).every(e=>e!==`.`&&e!==`..`),Zu=async(e,t,n=!1)=>{try{let r=ie(await c(e),await c(t));if(n&&r===``)return!0;let i=r===`..`||r.startsWith(`..`+oe);return r!==``&&!i&&!re(r)}catch{return!1}},Qu=async(e,t)=>{try{let n=m(t,`package.json`);return await Zu(e,n)?(await o(n,`utf8`),!0):!1}catch{return!1}},$u=async(e,t)=>{try{let n=m(e,t);if(!await Zu(e,n,t===`.`))return[];let r=(await s(n,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(async r=>{if(await Qu(e,m(n,r.name)))return m(t,r.name)});return(await Promise.all(r)).filter(e=>e!==void 0)}catch{return[]}},ed=async(e,t)=>{if(!Xu(t)||t.startsWith(`!`)||t.includes(`**`)||(t.match(/\*/gu)??[]).length>1)return[];if(t.endsWith(`/*`)){let n=t.slice(0,-2);return $u(e,n)}if(t===`*`)return $u(e,`.`);if(!t.includes(`*`)){let n=m(e,t);if(await Zu(e,n)&&await Qu(e,n))return[t]}return[]},td=async(e,t)=>{try{let n=m(t,`package.json`);if(!await Zu(e,n))return;let r=await o(n,`utf8`),i=JSON.parse(r);return{description:Ju(i),name:qu(i)}}catch{return}},nd=e=>{let t=e.map(e=>[e.path,e]),n=[...new Map(t).values()];return n.sort((e,t)=>e.path.localeCompare(t.path)),n},rd=async(e,t)=>{let n=new Set;try{if(!await Zu(e,t))return n;let r=await o(t,`utf8`);Gu(JSON.parse(r).workspaces).forEach(e=>n.add(e))}catch{}return n},id=async(e,t)=>{let n=new Set;try{if(!await Zu(e,t))return n;Ku((await o(t,`utf8`)).split(`
350
- `)).forEach(e=>n.add(e))}catch{}return n},ad=async(e,t)=>{let n=new Set,r=[...t].map(t=>ed(e,t));return(await Promise.all(r)).forEach(e=>{e.forEach(e=>n.add(e))}),n},od=async(e,t)=>{let n=m(e,t);if(!await Zu(e,n))return;let r=await td(e,n);if(r?.name)return{description:r.description,name:r.name,path:t}},sd=async(e,t)=>{let n=[...t].map(t=>od(e,t));return(await Promise.all(n)).filter(e=>e!==void 0)},cd=async e=>{let t=m(e,`package.json`),n=m(e,`pnpm-workspace.yaml`),r=await rd(e,t),i=await id(e,n),a=new Set;if(r.forEach(e=>a.add(e)),i.forEach(e=>a.add(e)),a.size===0)return[];let o=await ad(e,a),s=await sd(e,o);return nd(s)},ld=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},ud=()=>({env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:e=>fetch(e),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:ld,runner:new Nu});var dd=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},fd=class extends dd{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},pd=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new fd(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function md(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var hd=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(e=>md(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
345
+ `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),tc=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:Gs(t)&&Gs(r)&&(n[e]=tc(t,r))}return n},nc={meta:{},refs:{},settings:{}},rc=async e=>{try{return await qs(e)}catch(e){if(e instanceof _&&e.code===`not_found`)return;throw e}},ic=e=>{if(e!==void 0&&e>1)throw b(`config schema ${e} is newer than this CLI supports — upgrade refs`)},ac=async(e,t,n)=>{let r=Ks(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await zs(e.configPath,Rs(i))},oc=async(e,t,n)=>{await r(e.configPath,Bs(e));let i=tc(t,nc),a=Ks(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=ss.safeParse(o);if(!s.success)throw b(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${Bs(e)}): ${O(s.error)}`);await zs(e.configPath,Rs(o))},sc=async(e,t)=>(await ec(e,t),`seeded`),cc=async(e,t,n)=>{let r=Js(t,e.configPath),i=Xs(r);return ic(i),i===1?(await ac(e,r,n),`noop`):(await oc(e,r,n),`migrated`)},lc=async(e,t)=>{let n=await rc(e);return n===void 0?sc(e,t):cc(e,n,t)},uc=/^[CR]/u,dc=/^\s*(?<files>\d+) files? changed(?:, (?<insertions>\d+) insertions?\(\+\))?(?:, (?<deletions>\d+) deletions?\(-\))?\s*$/u,fc=e=>e===void 0?0:Number(e),pc=e=>{if(e.trim()===``)return{deletions:0,files_changed:0,insertions:0};let t=dc.exec(e);if(t===null)throw b(`git diff --shortstat returned unrecognized output: ${e.trim().slice(0,200)}`);let{deletions:n,files:r,insertions:i}=t.groups??{};return{deletions:fc(n),files_changed:fc(r),insertions:fc(i)}},mc=e=>uc.test(e)?2:1,hc=(e,t)=>{let n=e[t];if(n===void 0||n===``)return;let r=mc(n),i=e[t+r];if(i!==void 0)return{entry:{path:i,status:n.slice(0,1)},next:t+r+1}},gc=e=>{let t=e.split(`\0`),n=[],r=0;for(;r<t.length;){let e=hc(t,r);if(e===void 0)break;n.push(e.entry),r=e.next}return n},_c=async(e,t)=>{let n=await e.run(`git`,t.args,{cwd:t.cwd});if(n.exitCode===0)return n.stdout;let r=n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`;throw b(`${t.action} failed: ${r}`)},vc=e=>`refs/tags/${e}`,yc=e=>`${vc(e.oldTag)}..${vc(e.newTag)}`,bc=e=>e===void 0?[]:[`--`,`:(literal)${e}`],xc=e=>e.split(`
346
+ `).filter(e=>e!==``),Sc=async(e,t,n)=>{let r=await _c(e,{action:`git rev-list --count`,args:[`rev-list`,`--count`,`--no-merges`,`--end-of-options`,yc(n)],cwd:t});return Number(r.trim())},Cc=e=>{let[t,n,...r]=e.split(` `);if(!(t===void 0||n===void 0||r.length===0))return{date:n,sha:t,subject:r.join(` `)}},wc=async(e,t,n)=>{let r=await _c(e,{action:`git log`,args:[`log`,`--no-merges`,`--max-count=${String(n.limit)}`,`--pretty=format:%h%x09%ad%x09%s`,`--date=short`,`--end-of-options`,yc(n)],cwd:t});return xc(r).map(e=>Cc(e)).filter(e=>e!==void 0)},Tc=async(e,t,n)=>pc(await _c(e,{action:`git diff --shortstat`,args:[`diff`,`--shortstat`,`--end-of-options`,yc(n),...bc(n.pathScope)],cwd:t})),Ec=async(e,t,n)=>{let r=gc(await _c(e,{action:`git diff --name-status`,args:[`diff`,`--name-status`,`-z`,`--end-of-options`,yc(n),...bc(n.pathScope)],cwd:t}));return{paths:r.slice(0,n.limit),truncated:r.length>n.limit}},Dc=/does not exist in|exists on disk, but not in/iu,Oc=async(e,t,n)=>{let r=`${vc(n.tag)}:${n.path}`,i=await e.run(`git`,[`show`,`--end-of-options`,r],{cwd:t});if(i.exitCode===0)return i.stdout;if(!Dc.test(i.stderr))throw b(`git show failed: ${i.stderr.trim()||i.stdout.trim()||`exit code ${i.exitCode}`}`)},kc=`CHANGELOG.md`,Ac=/[$()*+.?[\\\]^{|}]/gu,jc=e=>e.replace(Ac,String.raw`\$&`),Mc=e=>RegExp(`(?<![0-9.])${jc(e)}(?![0-9A-Za-z-])`,`u`),Nc=(e,t)=>e.startsWith(`#`)&&t.test(e),Pc=/^#+/u,Fc=e=>e.match(Pc)?.[0]?.length??0,Ic=(e,t,n)=>{let r=e.slice(t+1),i=e=>Nc(e,n.pattern),a=r.findIndex(e=>i(e)&&Fc(e)<=n.maxDepth);return a===-1&&(a=r.findIndex(e=>i(e))),a===-1?e.length:t+1+a},Lc=(e,t,n)=>{let r={maxDepth:Fc(e[t]??``),pattern:Mc(n)};return e.slice(t,Ic(e,t,r)).join(`
347
+ `)},Rc=(e,t)=>{let n=e.split(`
348
+ `),r=Mc(t.newVersion),i=n.findIndex(e=>Nc(e,r));if(i===-1)return;let a=Lc(n,i,t.oldVersion);return a.length<=t.maxChars?{excerpt:a,truncated:!1}:{excerpt:a.slice(0,t.maxChars),truncated:!0}},zc=e=>e===void 0||e===`.`?[kc]:[`${e}/${kc}`,kc],Bc=async(e,t,n)=>{for(let r of zc(n.packagePath)){let i=await Oc(e,t,{path:r,tag:n.newTag});if(i!==void 0){let e=Rc(i,n);if(e!==void 0)return e}}},Vc=/^\d+$/u,Hc=(e,t,n)=>{let r=e[t],i=e[t+1];if(r===void 0||i===void 0||!Vc.test(r))return;let a=i.indexOf(`
349
+ `);if(a===-1)return;let o=i.slice(0,a);return{match:{line:Number(r),path:n,snippet:o.trim().slice(0,200)},nextPath:i.slice(a+1)}},Uc=e=>{let t=e.split(`\0`),n=[],r=t[0]??``;for(let e=1;e<t.length;e+=2){let i=Hc(t,e,r);if(i===void 0)break;n.push(i.match),r=i.nextPath}return{complete:r===``,matches:n}},Wc=(e,t)=>{let{complete:n,matches:r}=Uc(e);return{matches:r.slice(0,t),truncated:r.length>t||!n}},Gc=(e,t)=>{let{matches:n}=Wc(e,t);return{matches:n,truncated:!0}},Kc=e=>{let t=[`grep`,`-z`,`-n`,`-I`,`--extended-regexp`,`-e`,e.pattern];return e.pathspecs.length>0&&t.push(`--`,...e.pathspecs),t},qc=async(e,t)=>{let n=await e.run(`git`,Kc(t),{cwd:t.dir});if(n.exitCode===0)return n.stdoutTruncated===!0?Gc(n.stdout,t.limit):Wc(n.stdout,t.limit);if(n.exitCode===1)return{matches:[],truncated:!1};throw b(`git grep failed: ${n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`}`)},Jc=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
350
+ `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},Yc=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,Xc=(e,t)=>{let n=[];if(e&&n.push(`checkout had local changes (managed checkouts are read-only) discarded and restored to the remote state`),t!==void 0&&n.push(t),n.length!==0)return n.join(` | `)},Zc=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:Yc(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=Xc(n,r);return o!==void 0&&(a.warning=o),a},Qc=(e,t,n)=>{let r={dirty:t,shas:n};return e.branchRenamedTo!==void 0&&(r.branchRenamedTo=e.branchRenamedTo),e.warning!==void 0&&(r.setHeadWarning=e.warning),r},G=e=>le(m(e,`.git`)),$c=e=>`refusing to sync ${e}: not a refs-managed checkout`,el=async(e,t)=>{if(!G(t))throw b($c(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw b($c(t))},tl=/filtering not recognized/iu,nl=e=>e===void 0?{}:{cwd:e},K=(e,t,n)=>({action:e,args:t,cmd:`git`,...nl(n)}),rl=async(e,t)=>{let n=await e.run(t.cmd,t.args,nl(t.cwd));if(n.exitCode===0)return n;let r=n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`;throw b(`${t.action} failed: ${r}`)},il=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(t.cloneUrl,t.dest);let r=await rl(e,K(`git clone`,n));return await rl(e,K(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&tl.test(r.stderr)?{effectiveMode:`full`,warning:`server did not honour the partial-clone filter (blob:none); fell back to a full clone`}:{effectiveMode:t.mode}},al=async(e,t)=>{let n=await e.run(`git`,[`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],{cwd:t});if(n.exitCode!==0)return;let r=n.stdout.trim();return r.startsWith(`origin/`)?r.slice(7):r},ol=async(e,t)=>{let n=await al(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await al(e,t);if(r!==void 0)return r;throw b(`could not detect the default branch for checkout: ${t}`)},sl=async(e,t)=>(await rl(e,K(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),cl=async(e,t)=>(await rl(e,K(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,ll=async(e,t)=>{await rl(e,K(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await ol(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${Jc(n)}`),i},ul=e=>[K(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),K(`git clean -fd`,[`clean`,`-fd`],e)],dl=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...ul(r)),a.push(K(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),K(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await rl(e,t)},fl=async(e,t)=>{await el(e,t.dir);let n=await sl(e,t.dir),r=await ll(e,t),i=await cl(e,t.dir);return await dl(e,{branch:r.branch,dir:t.dir,dirty:i}),Zc(Qc(r,i,{newSha:await sl(e,t.dir),oldSha:n}))},pl=async(e,t,n=20)=>(await rl(e,K(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
351
+ `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),ml=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,hl=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
352
+ `),gl=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await zs(r,hl),await t(r,493)}))},_l=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,vl=/\d+\.\d+\.\d+/gu,yl=e=>es.safeParse(e).success,bl=e=>{let t=e.match(vl);return t!==null&&t.length>1},xl=e=>{let t=_l.exec(e);if(!t||bl(e))return;let[n]=t,r=e.replace(n,`{version}`);if(yl(r))return r},Sl=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},Cl=e=>{let t=new Map;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===void 0)continue;let i=xl(r);i&&Sl(t,i,n)}return t},wl=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Tl=e=>{let t=[...e.entries()];if(t.length===0)return null;let n=t[0];if(!n)return null;let[r,i]=n;return t.slice(1).reduce(({format:e,data:t},[n,r])=>wl(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},El=e=>{let t=Cl(e);return Tl(t)},Dl=(e,t)=>e.replaceAll(`{version}`,()=>t),Ol=async(e,t,n,r)=>{let i=Dl(n,r);if(!await ml(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},kl=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,q=e=>{let t=e.replace(kl,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},Al=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,jl=/^git\+/u,Ml={"https:":`443`,"ssh:":`22`},Nl=e=>e.replace(/\.git$/u,``),Pl=e=>e.split(`/`).some(e=>e===`.`||e===`..`),Fl=e=>e.includes(`\\`),Il=e=>e.includes(`%`),Ll=e=>{let t=z.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${q(e)}' is invalid`);return t.data},Rl=({host:e,port:t,protocol:n})=>{let r=Ml[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},zl=e=>{let t=Nl(e.path.replace(/^\/+/u,``).replace(/\/+$/u,``));return Ll(`${Rl(e)}/${t}`)},Bl=e=>{let t=decodeURIComponent(e).split(`/`).filter(e=>e!==``);if(t.length<2)throw b(`not a supported git url: file url path must have at least 2 segments`);let n=t.at(-2)??``,r=t.at(-1)??``;return Ll(`local/${n}/${r}`)},Vl=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${q(t)}`)}},Hl=e=>{if(e.password!==``)throw b(`not a supported git url: credentials embedded in url`);if(e.protocol===`https:`&&e.username!==``)throw b(`not a supported git url: credentials embedded in https url`)},Ul=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return Bl(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return Hl(e),zl({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},Wl=(e,t)=>{if(Il(e))throw b(`not a supported git url: percent-encoding not supported in ${q(t)}`);if(e.includes(`:`))throw b(`not a supported git url: ambiguous ':' in scp-style path ${q(t)}; use the ssh:// url form instead`);if(e.startsWith(`/`)||e.startsWith(`~`))throw b(`not a supported git url: ambiguous absolute/home-relative scp path in ${q(t)}; use the ssh:// url form instead`)},Gl=(e,t)=>{let n=e.groups?.path??``;return Wl(n,t),zl({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},Kl=(e,t)=>{if(Fl(e))throw b(`not a supported git url: backslash not allowed in ${q(t)}`)},ql=(e,t)=>{if(Pl(e))throw b(`not a supported git url: path traversal segment in ${q(t)}`)},Jl=(e,t,n)=>{if(e.protocol!==`file:`&&Il(t))throw b(`not a supported git url: percent-encoding not supported in ${q(n)}`)},Yl=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(jl,``);Kl(r,e),ql(r,e);let i=Al.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:Gl(i,e)};let a=Vl(r,e);return Jl(a,r,e),{cloneUrl:r,key:Ul(a,n)}},Xl=`.git`,Zl=e=>e.replace(/^\/+/u,``).replace(/\/+$/u,``),Ql=e=>e.endsWith(Xl)?e:`${e}${Xl}`,$l=(e,t)=>`https://${e.toLowerCase()}/${Zl(t)}`,eu=(e,t)=>`git@${e.toLowerCase()}:${Ql(Zl(t))}`,tu=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},nu=(e,t,n)=>{let r=Ml[e.protocol];if(e.port!==``&&e.port!==r)throw b(`cannot apply git_transport=${t} to ${q(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},ru=(e,t)=>t===`https`?$l(e.hostname,e.pathname):eu(e.hostname,e.pathname),iu=(e,t,n)=>{let r=Yl(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${q(e)}' → '${t}' (key '${n}' → '${r}')`);return t},au=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return iu(t.cloneUrl,$l(n,r),t.originalKey)},ou=e=>{let t=Vl(e.cloneUrl,e.cloneUrl);return tu(t.protocol)===e.transport?e.cloneUrl:(nu(t,e.transport,e.cloneUrl),iu(e.cloneUrl,ru(t,e.transport),e.originalKey))},su=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:Yl(e).key,transport:t},r=Al.exec(e);return r?.groups===void 0?ou(n):au(r,n)},cu=`meta.json`,lu=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},uu=e=>{try{return process.kill(e,0),!0}catch(e){return lu(e)!==`ESRCH`}},du=e=>{try{return JSON.parse(e)}catch{return}},fu=async e=>{try{return await o(e,`utf8`)}catch{return}},pu=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},mu=e=>{if(typeof e!=`object`||!e)return;let t=e,{pid:n}=t,r=pu(t.acquired_at);if(!(typeof n!=`number`||r===void 0))return{acquiredAtMs:r,pid:n}},hu=async e=>{let t=await fu(m(e,cu));if(t!==void 0)return mu(du(t))},gu=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},_u=async e=>{let t=await fu(m(e,cu));if(t!==void 0)return gu(du(t))},vu=async e=>{try{return(await f(e)).mtimeMs}catch{return}},yu=async(e,t)=>{let n=m(e,cu),r=`${n}.tmp-${se()}`;await ee(r,t,`utf8`),await l(r,n)},bu=async(e,t)=>{await yu(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},xu=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/u,Su=async e=>{let t=await hu(e);if(t===void 0){let t=await vu(e);return t===void 0?!1:Date.now()-t>5e3}return Date.now()-t.acquiredAtMs>6e5?!0:!uu(t.pid)},Cu=async(e,t)=>{try{await bu(e,t)}catch(e){if(lu(e)===`ENOENT`)return`retry`;throw e}return t},wu=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){if(lu(e)===`EEXIST`)return!1;throw e}},Tu=async e=>{if(!await wu(e))return;let t=await Cu(e,se());return t===`retry`?Tu(e):t},Eu=e=>m(e.locksDir,`${e.name}.steal-claim`),Du=e=>m(e.locksDir,`${e.name}.steal.${se()}`),Ou=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){if(lu(e)===`EEXIST`)return!1;throw e}},ku=async e=>{let t=await vu(e);return t!==void 0&&Date.now()-t>2e3},Au=async e=>await Ou(e)?!0:await ku(e)?(await u(e,{force:!0,recursive:!0}),Ou(e)):!1,ju=async e=>{let t=Du(e);try{await l(e.lockPath,t)}catch(e){if(lu(e)===`ENOENT`)return;throw e}return t},Mu=async e=>{if(!await Su(e.lockPath))return;let t=await ju(e);t!==void 0&&await u(t,{force:!0,recursive:!0})},Nu=async e=>{let t=Eu(e);if(await Au(t))try{await Mu(e)}finally{await u(t,{force:!0,recursive:!0})}},Pu=async(e,t)=>{if(await Su(e.lockPath)){await Nu(e);return}if(Date.now()>=t)throw ve(`lock ${e.name} is held — another refs process is running`);await fe(100)},Fu=async(e,t)=>{let n=await Tu(e.lockPath);return n===void 0?(await Pu(e,t),Fu(e,t)):n},Iu=async(e,t)=>{await _u(e)===t&&await u(e,{force:!0,recursive:!0})},Lu=e=>{if(e===`.`||e===`..`||!xu.test(e))throw b(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.:-" are allowed, and it may not be "." or "..": ${e}`)},J=async(e,t,n,r)=>{Lu(t);let i={lockPath:m(e.locksDir,t),locksDir:e.locksDir,name:t};await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await Fu(i,o);try{return await n()}finally{await Iu(i.lockPath,s)}},Ru=no({directory:I().optional(),url:I().optional()}),zu=no({repository:io([I(),Ru]).optional()}),Bu=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,Vu=new Set([`node_modules`,`favicon.ico`]),Hu=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),Uu=e=>{let t=e.split(`/`);return t.length>=2?t[1]:e},Wu=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!Bu.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=Uu(e);if(Vu.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},Gu=e=>e.replace(`/`,`%2F`),Ku=e=>typeof e==`string`?e:e?.url,qu=e=>{if(typeof e==`object`&&e?.directory){let t=ts.safeParse(e.directory);if(t.success)return t.data}},Ju=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},Yu=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${Gu(t)}`);if(n.status===404)throw v(`npm package '${t}' not found`);if(n.status!==200)throw b(`failed to fetch npm package '${t}': status ${n.status}`);let r=await Ju(n,t),i=zu.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},Xu=(e,t)=>{try{return Yl(e)}catch{throw Hu(t)}},Zu=async(e,t)=>{Wu(t);let n=await Yu(e,t),r=Ku(n.repository);if(r===void 0||r===``)throw Hu(t);let{cloneUrl:i,key:a}=Xu(r,t),o=qu(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},Qu=new Set;let $u=!1;const ed=()=>{for(let e of Qu)try{e.kill(`SIGKILL`)}catch{}},td=[`SIGINT`,`SIGTERM`,`SIGHUP`],nd=e=>{let t=()=>{ed(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},rd=()=>{$u||($u=!0,td.forEach(e=>{nd(e)}),process.on(`exit`,ed))},id=()=>{let e=[],t=0,n=!1;return{finish:()=>({text:Buffer.concat(e).toString(`utf8`),truncated:n}),push:r=>{if(n)return;let i=67108864-t;if(r.length<=i){e.push(r),t+=r.length;return}i>0&&e.push(r.subarray(0,i)),n=!0}}},ad=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
353
+ `),od=(e,t,n)=>{let r=e;return t.truncated&&(r=ad(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=ad(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},sd={clear:()=>{},markedTimedOut:()=>!1},cd=(e,t)=>{if(t===void 0)return sd;let n=!1,r,i=setTimeout(()=>{n=!0,e.kill(`SIGTERM`),r=setTimeout(()=>{e.kill(`SIGKILL`)},2e3)},t);return{clear:()=>{clearTimeout(i),r!==void 0&&clearTimeout(r)},markedTimedOut:()=>n}},ld=e=>e===void 0?{}:{cwd:e},ud=(e,t)=>ad(e,`refs: command timed out after ${String(t)}ms`),dd=(e,t)=>({exitCode:124,stderr:ud(e,t),stdout:``,timedOut:!0}),fd=(e,t,n)=>{let r=ge(e,t,{...ld(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});Qu.add(r);let i=id(),a=id();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:cd(r,n?.timeoutMs)}},pd=(e,t,n)=>{try{return fd(e,t,n)}catch(e){return{exitCode:127,stderr:hd(e),stdout:``}}},md=e=>!(`child`in e),hd=e=>e instanceof Error?e.message:String(e),gd=async e=>{try{let[t]=await me(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:hd(e)}}},_d=e=>e===null?1:e,vd=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,yd=e=>e.timedOut?dd(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?vd({exitCode:_d(e.code),stderr:od(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):vd({exitCode:127,stderr:ad(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var bd=class{async run(e,t,n){rd();let r=pd(e,t,n);if(md(r))return r;let i=await gd(r.child);return Qu.delete(r.child),r.timeout.clear(),yd({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const xd=as.partial({description:!0}),Sd=R({default_branch:I().min(1),key:z,tag_format_candidate:es.nullable(),url:I().min(1)});Sd.extend({description:I().default(``),packages:Bo(xd)});const Cd=Sd.extend({description:I().min(1),packages:Bo(as)}),wd=R({effective_clone_mode:Qo.optional(),head_sha:I().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:I().optional(),last_fetched_at:ra().optional(),pending_proposal_at:ra().optional()}),Td=R({refs:Ro(e=>e.length>=1&&!Lo.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,co(I(),wd)).default({})}),Y=(e,t,n)=>t?.[e]??n[e],Ed=async e=>{try{return await o(e.statePath,`utf8`)}catch(e){if(V(e))return;throw e}},Dd=e=>{try{return JSON.parse(e)}catch{return}},X=async e=>{let t=await Ed(e);if(t===void 0)return Td.parse({});let n=Dd(t);if(n===void 0)return Td.parse({});let r=Td.safeParse(n);return r.success?r.data:Td.parse({})},Od=async(e,t)=>{let n=Td.safeParse(t);if(!n.success)throw b(O(n.error));await zs(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},kd=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,Ad=/^packages:\s*(?:#.*)?$/u,jd=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Md=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!jd(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},Nd=e=>{let t=[],n=!1;for(let r of e){let e=r.trim();if(Ad.test(r)){n=!0;continue}if(!n)continue;if(e&&!e.startsWith(`-`)&&e.includes(`:`))break;if(!e.startsWith(`-`))continue;let i=kd.exec(r)?.groups?.pattern?.trim();i&&i!==``&&t.push(i)}return t},Pd=e=>{let{name:t}=e;if(typeof t==`string`)return t},Fd=e=>{let{description:t}=e;if(typeof t==`string`)return t},Id=/[/\\]/u,Ld=e=>re(e)?!1:e.split(Id).every(e=>e!==`.`&&e!==`..`),Rd=async(e,t,n=!1)=>{try{let r=ie(await c(e),await c(t));if(n&&r===``)return!0;let i=r===`..`||r.startsWith(`..`+oe);return r!==``&&!i&&!re(r)}catch{return!1}},zd=async(e,t)=>{try{let n=m(t,`package.json`);return await Rd(e,n)?(await o(n,`utf8`),!0):!1}catch{return!1}},Bd=async(e,t)=>{try{let n=m(e,t);if(!await Rd(e,n,t===`.`))return[];let r=(await s(n,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(async r=>{if(await zd(e,m(n,r.name)))return m(t,r.name)});return(await Promise.all(r)).filter(e=>e!==void 0)}catch{return[]}},Vd=async(e,t)=>{if(!Ld(t)||t.startsWith(`!`)||t.includes(`**`)||(t.match(/\*/gu)??[]).length>1)return[];if(t.endsWith(`/*`)){let n=t.slice(0,-2);return Bd(e,n)}if(t===`*`)return Bd(e,`.`);if(!t.includes(`*`)){let n=m(e,t);if(await Rd(e,n)&&await zd(e,n))return[t]}return[]},Hd=async(e,t)=>{try{let n=m(t,`package.json`);if(!await Rd(e,n))return;let r=await o(n,`utf8`),i=JSON.parse(r);return{description:Fd(i),name:Pd(i)}}catch{return}},Ud=e=>{let t=e.map(e=>[e.path,e]),n=[...new Map(t).values()];return n.sort((e,t)=>e.path.localeCompare(t.path)),n},Wd=async(e,t)=>{let n=new Set;try{if(!await Rd(e,t))return n;let r=await o(t,`utf8`);Md(JSON.parse(r).workspaces).forEach(e=>n.add(e))}catch{}return n},Gd=async(e,t)=>{let n=new Set;try{if(!await Rd(e,t))return n;Nd((await o(t,`utf8`)).split(`
354
+ `)).forEach(e=>n.add(e))}catch{}return n},Kd=async(e,t)=>{let n=new Set,r=[...t].map(t=>Vd(e,t));return(await Promise.all(r)).forEach(e=>{e.forEach(e=>n.add(e))}),n},qd=async(e,t)=>{let n=m(e,t);if(!await Rd(e,n))return;let r=await Hd(e,n);if(r?.name)return{description:r.description,name:r.name,path:t}},Jd=async(e,t)=>{let n=[...t].map(t=>qd(e,t));return(await Promise.all(n)).filter(e=>e!==void 0)},Yd=async e=>{let t=m(e,`package.json`),n=m(e,`pnpm-workspace.yaml`),r=await Wd(e,t),i=await Gd(e,n),a=new Set;if(r.forEach(e=>a.add(e)),i.forEach(e=>a.add(e)),a.size===0)return[];let o=await Kd(e,a),s=await Jd(e,o);return Ud(s)},Xd=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Zd=()=>({env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:e=>fetch(e),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:Xd,runner:new bd});var Qd=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},$d=class extends Qd{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},ef=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new $d(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function tf(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var nf=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(e=>tf(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
351
355
  `)}displayWidth(e){return _e(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
352
356
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
353
- `)}},gd=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=yd(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new fd(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?vd(this.name().replace(/^no-/,``)):vd(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},_d=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r===void 0?!1:r;return t.negate===(i===e)}};function vd(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function yd(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
357
+ `)}},rf=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=sf(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new $d(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?of(this.name().replace(/^no-/,``)):of(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},af=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r===void 0?!1:r;return t.negate===(i===e)}};function of(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function sf(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
354
358
  - a short flag is a single dash and a single character
355
359
  - either use a single dash and a single character (for a short flag)
356
360
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
357
361
  - too many short flags`):i.test(t)?Error(`${n}
358
362
  - too many long flags`):Error(`${n}
359
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function bd(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function xd(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=bd(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var Sd=class e extends pe{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>h.stdout.write(e),writeErr:e=>h.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>wd()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>wd()??(h.stderr.isTTY&&h.stderr.hasColors?.()),stripColor:e=>_e(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new hd,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
360
- - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new pd(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
361
- Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new dd(e,t,n)),h.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new gd(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
362
- - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof gd)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){h.versions?.electron&&(t.from=`electron`);let e=h.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=h.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:h.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
363
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function cf(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function lf(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=cf(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var uf=class e extends pe{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>h.stdout.write(e),writeErr:e=>h.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>ff()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>ff()??(h.stderr.isTTY&&h.stderr.hasColors?.()),stripColor:e=>_e(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new nf,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
364
+ - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new ef(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
365
+ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Qd(e,t,n)),h.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new rf(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
366
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof rf)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){h.versions?.electron&&(t.from=`electron`);let e=h.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=h.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:h.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
363
367
  - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(ce.existsSync(e))return;let r=`'${e}' does not exist
364
368
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
365
369
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
366
- - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=p.resolve(e,t);if(ce.existsSync(r))return r;if(n.includes(p.extname(t)))return;let i=n.find(e=>ce.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||``;if(this._scriptPath){let e;try{e=ce.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=p.resolve(p.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=p.basename(this._scriptPath,p.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(p.extname(i)),s;h.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=Cd(h.execArgv).concat(t),s=he.spawn(h.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=Cd(h.execArgv).concat(t),s=he.spawn(h.argv[0],t,{stdio:`inherit`})):s=he.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{h.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new dd(e,`commander.executeSubCommandAsync`,`(close)`)):h.exit(e)}),s.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(i,a,e._name);else if(t.code===`EACCES`)throw Error(`'${i}' not executable`);if(!c)h.exit(1);else{let e=new dd(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,c(e)}}),this.runningCommand=s}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
367
- `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in h.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,h.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new _d(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=xd(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=xd(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>md(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=p.basename(e,p.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(h.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
368
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function Cd(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function wd(){if(h.env.NO_COLOR||h.env.FORCE_COLOR===`0`||h.env.FORCE_COLOR===`false`)return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}new Sd;const Td=[],Ed=e=>Array.isArray(e)?e:[e],Q=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??Td};e.out(JSON.stringify(t));return}for(let t of Ed(n))e.out(t);for(let t of i??Td)e.errLine(`refs: warning: ${t}`)},Dd=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},Od=(e,t)=>{e.errLine(`refs: ${t}`)},$=(e,t,n)=>async()=>{try{await n()}catch(n){let r=be(n,{verbose:t.verbose});Dd(e,t,r),process.exitCode=r.exitCode}};var kd=`0.2.0`;const Ad=async e=>{let t=await e.runner.run(`git`,[`--version`]);return t.exitCode===0?{detail:t.stdout.trim(),name:`git`,status:`ok`}:{detail:t.stderr.trim()||`git --version exited with code ${t.exitCode}`,name:`git`,status:`fail`}},jd=/^v(?<major>\d+)\.(?<minor>\d+)/u,Md=e=>{let t=jd.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(!(n===void 0||r===void 0))return{major:Number(n),minor:Number(r)}},Nd=e=>e===void 0?!1:e.major>24?!0:e.major===24&&e.minor>=12,Pd=e=>{let{nodeVersion:t}=e;return Nd(Md(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.12`,name:`node`,status:`fail`}},Fd=e=>e instanceof Error?e.message:String(e),Id=()=>ss.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),Ld=async e=>{try{return{config:await W(e)}}catch(e){return{config:Id(),errorMessage:Fd(e)}}},Rd=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},zd=[`.claude`,`skills`,`refs`,`SKILL.md`],Bd=[`.codex`,`skills`,`refs`,`SKILL.md`],Vd=e=>e===void 0?[]:[m(e,...zd),m(e,...Bd)],Hd=async t=>{try{return await e(t),!0}catch{return!1}},Ud=async e=>{let t=Vd(e.env.HOME);return(await Promise.all(t.map(e=>Hd(e)))).some(Boolean)?{detail:`the refs skill is installed`,name:`skill`,status:`ok`}:{detail:`refs skill not found — install it: npx skills add kaisers-io/refs`,name:`skill`,status:`warn`}},Wd=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),Gd=[`pre-commit`,`pre-push`],Kd=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},qd=async e=>{let t=await Promise.all(Gd.map(t=>Kd(e,t)));return Gd.filter((e,n)=>!t[n])},Jd=async(e,t,n)=>{let r=await e.runner.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:n});return r.exitCode===0&&r.stdout.trim()===t.hooksDir},Yd=e=>e.missingHooks.length>0?{detail:`${e.missingHooks.map(e=>`hooks/${e}`).join(`, `)} missing or not executable — run: refs init`,name:`hooks-guard`,status:`fail`}:e.badKeys.length>0?{detail:`core.hooksPath not set for: ${e.badKeys.join(`, `)} — run: refs init`,name:`hooks-guard`,status:`fail`}:{detail:`${Gd.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},Xd=async(e,t,n)=>{let r=Wd(t,n),[i,a]=await Promise.all([qd(t),Promise.all(r.map(n=>Jd(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return Yd({badKeys:o,checkoutCount:r.length,missingHooks:i})},Zd=async(e,t)=>{let n=await e.runner.run(`git`,[`status`,`--porcelain`],{cwd:t.dest});return n.exitCode===0?{broken:!1,detail:``,dirty:n.stdout.trim()!==``,key:t.key}:{broken:!0,detail:n.stderr.trim(),dirty:!1,key:t.key}},Qd=e=>{let t=e.filter(e=>e.broken);if(t.length>0)return{detail:t.map(e=>`${e.key}: git status failed — ${e.detail}`).join(`; `),name:`dirty-checkouts`,status:`fail`};let n=e.filter(e=>e.dirty).map(e=>e.key);return n.length===0?{detail:`no local changes in any checkout`,name:`dirty-checkouts`,status:`ok`}:{detail:`local changes will be discarded on next sync: ${n.join(`, `)}`,name:`dirty-checkouts`,status:`warn`}},$d=async(e,t,n)=>{let r=Wd(t,n),i=await Promise.all(r.map(t=>Zd(e,t)));return Qd(i)},ef=async e=>{try{return await Z(e)}catch{return Ru.parse({})}},tf=async e=>{try{return(await s(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(V(e))return[];throw e}},nf=async(e,t)=>{if(G(e))return[[...t]];let n=await tf(e);return(await Promise.all(n.map(n=>nf(m(e,n),[...t,n])))).flat()},rf=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r===void 0?!1:n-Date.parse(r)<864e5},af=(e,t,n)=>rf(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,of=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),sf=async(e,t,n)=>{let r=(await nf(e.sourcesDir,[])).map(t=>of(e,t)).filter(e=>!Object.hasOwn(t.refs,e.key));if(r.length===0)return{detail:`no orphaned checkouts under sources/`,name:`orphans`,status:`ok`};let i=Date.now();return{detail:r.map(e=>af(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},cf=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,lf=e=>e===``?{}:{user:e},uf=e=>e===``?{}:{port:e},df=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...lf(t.username),...uf(t.port)}:void 0}catch{return}},ff=e=>{let t=cf.exec(e),n=t?.groups?.host;return n===void 0?df(e):{host:n,user:t?.groups?.user??`git`}},pf=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,mf=e=>e.user===void 0?pf(e):`${e.user}@${pf(e)}`,hf=e=>{let t=Object.values(e.refs).map(e=>ff(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(mf(e),e);return[...n.values()].toSorted((e,t)=>mf(e).localeCompare(mf(t)))},gf=/Permission denied/u,_f=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],vf=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,yf=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=vf(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},bf=async(e,t,n)=>{let r=mf(t),i=await e.runner.run(`ssh`,yf(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:gf.test(i.stderr)?{host:r,outcome:`denied`}:_f.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},xf=(e,t)=>{let n=e.filter(e=>e.outcome===`timeout`).map(e=>e.host);if(n.length!==0)return{detail:`ssh probe timed out after ${t/1e3}s: ${n.join(`, `)}`,name:`ssh-auth`,status:`fail`}},Sf=e=>{let t=e.filter(e=>e.outcome===`denied`).map(e=>e.host);if(t.length!==0)return{detail:`ssh permission denied for: ${t.join(`, `)}`,name:`ssh-auth`,status:`fail`}},Cf=e=>{let t=e.filter(e=>e.outcome===`connection-warn`);if(t.length!==0)return{detail:`ssh connection issue, treated as warn: ${t.map(e=>`${e.host} (${e.detail??``})`).join(`; `)}`,name:`ssh-auth`,status:`warn`}},wf=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),Tf=(e,t)=>xf(e,t)??Sf(e)??Cf(e)??wf(e),Ef=async(e,t,n)=>{let r=hf(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>bf(e,t,i)));return Tf(a,i)},Df=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${Fd(t)}`,name:e.name,status:`fail`}}},Of=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await Df(t),i=await Of(n);return r===void 0?i:[r,...i]},kf=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Ad(n)},{name:`node`,run:()=>Promise.resolve(Pd(n))},{name:`config`,run:()=>Promise.resolve(Rd(t.errorMessage))},{name:`hooks-guard`,run:()=>Xd(n,r,t.config)},{name:`dirty-checkouts`,run:()=>$d(n,r,t.config)},{name:`orphans`,run:()=>sf(r,t.config,i)},{name:`skill`,run:()=>Ud(n)},{name:`ssh-auth`,run:()=>Ef(n,t.config)}]},Af=async e=>{let t=H(e.env),n=await Ld(t),r=await ef(t);return Of(kf({configLoad:n,ctx:e,home:t,state:r}))},jf={fail:`FAIL`,ok:`OK`,warn:`WARN`},Mf=e=>e.map(e=>`[${jf[e.status]}] ${e.name}: ${e.detail}`),Nf=e=>e.some(e=>e.status===`fail`),Pf=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, ssh).`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return $(t,i,async()=>{let e=await Af(t);Q(t,i,Mf(e),{checks:e}),Nf(e)&&(process.exitCode=g.UNEXPECTED)})()})},Ff=async e=>{let t=H(e.env),n=await Y(t,`home`,()=>cc(t,kd));return n===`migrated`?{backup:Bs(t),result:n}:{backup:null,result:n}},If=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${te(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,Lf=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return $(t,i,async()=>{let e=await Ff(t);Q(t,i,If(e),e)})()})},Rf=(e,t,n)=>e===void 0?!0:n-Date.parse(e)>t,zf=(e,t,n)=>{let r=e.state.refs[t],i=Zo(X(`sync_ttl`,n,e.settings));return{clone_mode:X(`clone_mode`,n,e.settings),description:n.description,key:t,missing:!G(U(e.home,z.parse(t))),packages:Object.keys(n.packages??{}).toSorted(),stale:Rf(r?.last_fetched_at,i,e.now)}},Bf=e=>{let t={home:e.home,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>zf(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},Vf=async e=>{let t=H(e.env),n=await W(t),r=await Z(t);return Bf({config:n,home:t,now:Date.now(),state:r})},Hf=e=>{let t=[];return e.stale&&t.push(`[stale]`),e.missing&&t.push(`[missing]`),t.length===0?``:` ${t.join(` `)}`},Uf=e=>e.length===0?[`no refs configured — run: refs add <source>`]:e.map(e=>`${e.key} ${e.description}${Hf(e)}`),Wf=e=>e.split(`/`),Gf=(e,t)=>{let n=Wf(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Kf=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=Wf(t),r=Object.keys(e.refs).filter(e=>Gf(e,n)).toSorted(),[i]=r;if(i===void 0)throw v(`no ref matches '${t}'`);if(r.length>1)throw y(`'${t}' matches more than one ref: ${r.join(`, `)}`);return z.parse(i)},qf=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return $(t,i,async()=>{let e=await Vf(t);Q(t,i,Uf(e),e)})()})},Jf=e=>`ref:${e.replaceAll(`/`,`_`)}`,Yf=e=>e.REFS_ALLOW_FILE_URLS===`1`,Xf=(e,t)=>{let n=J(t,{allowFileUrls:Yf(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},Zf=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);Od(e,`resolving npm package '${t}'…`);let n=await du(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},Qf=(e,t)=>t.startsWith(`npm:`)?Zf(e,t.slice(4)):Promise.resolve(Xf(e,t)),$f=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=X(`git_transport`,void 0,t);return{...e,cloneUrl:xl(e.cloneUrl,n)}},ep=e=>`ref '${e}' already exists — use refs edit or refs remove`,tp=(e,t)=>{if(e.refs[t]!==void 0)throw ve(ep(t))},np=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},rp=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),ip=async(e,t)=>{let n=await np(e);if(n===void 0)return{kind:`stop`};let r=rp(n);if(r.includes(t))return{kind:`continue`,nextDir:m(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},ap=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await ip(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):ap(a.nextDir,i,[...n,r])},op=[],sp=async(e,t)=>{let n=await ap(e.sourcesDir,t.split(`/`),op);if(n!==void 0)throw ve(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},cp=[],lp=e=>e===void 0?cp:[e],up=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},dp=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},fp=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},pp=async e=>{let t=await dp(e);if(t===void 0)return!0;if(t.length!==0)return!1;try{await d(e)}catch(e){if(!V(e))throw e}return!0},mp=async e=>{let t=await fp(e);return t===void 0?!0:t?pp(e):!1},hp=async(e,t)=>{t!==e.sourcesDir&&await mp(t)&&await hp(e,ne(t))},gp=async(e,t)=>await up(t)?(Us(e,t),await u(t,{force:!0,recursive:!0}),await hp(e,ne(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},_p=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),vp=async(e,t)=>{let n=await W(e);await Zs(e,{...n,refs:_p(n.refs,t)});let r=await Z(e);await Vu(e,{...r,refs:_p(r.refs,t)})},yp=async(e,t)=>{let n=H(e.env),r=Kf(await W(n),t),i=U(n,r),{removedCheckout:a,warning:o}=await Y(n,Jf(r),()=>gp(n,i));return await Y(n,`home`,()=>vp(n,r)),{data:{key:r,removed_checkout:a},warnings:lp(o)}},bp=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],xp=(e,t)=>{e.command(`remove`).description(`Remove a configured ref: its config/state entry AND its checkout directory.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return $(t,a,async()=>{let{data:n,warnings:r}=await yp(t,e);Q(t,a,bp(n),n,r)})()})},Sp=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,Cp=/^[a-z][a-z0-9+.-]*:\/\//iu,wp=/^git@[^:/\s]+:[^\s]+$/u,Tp=e=>Cp.test(e)||wp.test(e),Ep=(e,t)=>{try{return J(e,t)}catch{if(Tp(e))throw b(`query looks like a git url but is not a supported form — check the url (credentials are never accepted) or run: refs resolve <package|ref-suffix>`);return}},Dp=(e,t,n)=>{let r=Ep(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(Sp(t))}},Op=(e,t)=>{let n=[];for(let r of Object.keys(e.refs).toSorted()){let i=e.refs[r]?.packages?.[t];i!==void 0&&n.push({entry:i,key:z.parse(r)})}return n},kp=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,Ap=(e,t)=>{let n=Op(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(kp(t,n.map(e=>e.key)));return r}},jp=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=Ap(e,r);if(i!==void 0)return{...i,name:r}}},Mp=(e,t)=>{try{return Kf(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(Sp(t)):e}},Np=(e,t,n)=>{let r=Dp(e,t,n);if(r!==void 0)return r;let i=Ap(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=jp(e,t);return a===void 0?{key:Mp(e,t)}:{key:a.key,packageMatch:a}},Pp=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: resolved ref key '${t}' is missing from config.refs`);return n},Fp=(e,t)=>{if(e.packageMatch===void 0)return null;let{entry:n,name:r}=e.packageMatch;return{local_path:m(t,n.path),name:r,path:n.path}},Ip=async(e,t)=>{let n=H(e.env),r=await W(n),i=Np(r,t,{allowFileUrls:Yf(e.env)}),a=Pp(r,i.key),o=await Z(n),s=U(n,i.key),c=Zo(X(`sync_ttl`,a,r.settings));return{key:i.key,local_path:s,missing:!G(s),package:Fp(i,s),stale:Rf(o.refs[i.key]?.last_fetched_at,c,Date.now())}},Lp=e=>{let t=[e.key,`local_path: ${e.local_path}`];return e.package!==null&&t.push(`package: ${e.package.name}`,`local_path: ${e.package.local_path}`),t},Rp=(e,t)=>{e.command(`resolve`).description(`Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.`).argument(`<query>`,`git url, npm package name, import path, or unique ref-key suffix`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return $(t,a,async()=>{let n=await Ip(t,e);Q(t,a,Lp(n),n)})()})},zp={},Bp=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},Vp=e=>e instanceof Error?e.message:String(e),Hp=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await Oc(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${Vp(e)}`}}},Up=[],Wp=e=>e===void 0?Up:[e],Gp=async(e,t)=>{let n=H(e.env),r=await W(n),i=Kf(r,t),a=Bp(r,i),o=await Z(n),s=U(n,i),{tags:c,warning:l}=await Hp(e,s);return{data:{...a,key:i,local_path:s,sample_tags:c,state:o.refs[i]??zp},warnings:Wp(l)}},Kp=e=>{let t=[`${e.key} ${e.description}`,`url: ${e.url}`,`local_path: ${e.local_path}`];return e.sample_tags.length>0&&t.push(`tags: ${e.sample_tags.join(`, `)}`),t},qp=(e,t)=>{e.command(`show`).description(`Show a configured ref: full entry, state, local path, and sample tags.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return $(t,a,async()=>{let{data:n,warnings:r}=await Gp(t,e);Q(t,a,Kp(n),n,r)})()})},Jp=(e,t)=>{let n={head_sha:t.headSha,last_fetched_at:new Date().toISOString()},r=t.effectiveCloneMode??e?.effective_clone_mode;return r!==void 0&&(n.effective_clone_mode=r),n},Yp=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await Zs(e,r))},Xp=(e,t,n)=>Y(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Yp(e,t,n.branchRenamedTo);let r=await Z(e);r.refs[t]=Jp(r.refs[t],n),await Vu(e,r)}),Zp=async(e,t,n)=>{try{await Y(e,`home`,async()=>{let r=await Z(e);r.refs[t]={...r.refs[t],last_error:n},await Vu(e,r)})}catch{}},Qp=e=>{let t=0,n=[];return{acquire:()=>{if(t<e)return t+=1,Promise.resolve();let{promise:r,resolve:i}=Promise.withResolvers();return n.push(()=>{t+=1,i()}),r},release:()=>{--t;let e=n.shift();e!==void 0&&e()}}},$p=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},em=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,tm=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,nm=(e,t)=>{try{return J(e,{allowFileUrls:t}).key}catch{return}},rm=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=tm(n),i=nm(t.expectedUrl,t.allowFileUrls),a=nm(r,t.allowFileUrls);if(!(i!==void 0&&a===i))throw ve(em(t.dest,r,t.expectedUrl))},im=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,am=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw ve(im(t.dest))},om=async(e,t)=>{await a(ne(t.dest),{recursive:!0}),Od(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await yc(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},sm=async(e,t)=>(Us(t.home,t.dest),G(t.dest)?(await rm(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await am(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):om(e,t)),cm=(e,t)=>`checkout for '${e}' at ${t} is missing or corrupt (git rev-parse HEAD failed) — run: refs remove ${e}, then refs add <source> --dry-run again`,lm=(e,t,n)=>`checkout for '${e}' at ${t} has a HEAD sha refs cannot store yet (${n.length} hex chars, expected 40) — only SHA-1 repositories are supported for now; \`--object-format=sha256\` repositories are not yet supported`,um=async(e,t)=>{await rm(e,t),await am(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw b(cm(t.key,t.dest));let r=n.stdout.trim();if(!Lu.shape.head_sha.safeParse(r).success)throw b(lm(t.key,t.dest,r));return r},dm=(e,t,n)=>`sync produced a HEAD sha for '${e}' at ${t} that refs cannot store yet (${n.length} hex chars) — only SHA-1 repositories are supported for now`,fm=(e,t,n)=>{if(!Lu.shape.head_sha.safeParse(n).success)throw b(dm(e,t,n));return n},pm=(e,t,n)=>{let r={effectiveCloneMode:t.effectiveMode,headSha:n.headSha,status:`cloned`};return n.actualBranch!==e.ref.default_branch&&(r.branchRenamedTo=n.actualBranch),t.warning!==void 0&&(r.warning=t.warning),r},mm=async(e,t,n)=>{await a(ne(n),{recursive:!0});let r=X(`clone_mode`,t.ref,t.settings),i=await yc(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await xc(e.runner,n),s=await um(e.runner,{allowFileUrls:Yf(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return pm(t,i,{actualBranch:o,headSha:s})},hm=async(e,t,n)=>{await am(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await rm(e.runner,{allowFileUrls:Yf(e.env),dest:n,expectedUrl:t.ref.url});let r=await Dc(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:fm(t.key,n,r.newSha),status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},gm=(e,t)=>Y(t.home,Jf(t.key),()=>{let n=U(t.home,t.key);return Us(t.home,n),G(n)?hm(e,t,n):mm(e,t,n)}),_m=e=>e instanceof Error?e.message:String(e),vm=e=>{let t=[];e.branchRenamedTo!==void 0&&t.push(`default branch renamed to ${e.branchRenamedTo}`),e.warning!==void 0&&t.push(e.warning);let[n]=t;if(n!==void 0)return t.join(` | `)},ym=(e,t)=>{let n={key:e,status:t.status},r=vm(t);return r!==void 0&&(n.warning=r),n},bm=async(e,t)=>{try{let n=await gm(e,t);return await Xp(t.home,t.key,n),ym(t.key,n)}catch(e){let n=_m(e);return await Zp(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},xm=(e,t)=>e.status===`fulfilled`?e.value:{error:_m(e.reason),key:t,status:`failed`},Sm=async(e,t)=>{let n=Qp(4);return(await Promise.allSettled(t.map(t=>$p(n,()=>bm(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return xm(e,r.key)})},Cm=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},wm=(e,t,n)=>({home:e,key:n,ref:Cm(t,n),settings:t.settings}),Tm=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>wm(e,t,z.parse(n))):n.map(n=>wm(e,t,Kf(t,n))),Em=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=Zo(X(`sync_ttl`,t.ref,t.settings)),a=Rf(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},Dm=async(e,t,n)=>{if(!n)return t;let r=await Z(e);return Em(e,t,r)},Om=async(e,t)=>{let n=H(e.env),r=await W(n),i=Tm(n,r,t.refs),a=await Sm(e,await Dm(n,i,t.staleOnly));return{failedCount:a.filter(e=>e.status===`failed`).length,results:a}},km=[`updated`,`fresh`,`cloned`,`restored`,`failed`],Am={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},jm=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},Mm=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,Nm=e=>{let t=jm(e),n=[km.map(e=>`${Am[e]} (${t[e].length})`).join(` / `)];for(let e of km)for(let r of t[e])n.push(Mm(r));return n},Pm=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),Fm=(e,t)=>{e.command(`sync`).description(`Fetch (or re-clone, if the checkout is missing) configured refs — all by default.`).argument(`[refs...]`,`ref keys or unique suffixes to sync (default: every configured ref)`).option(`--stale-only`,`skip refs whose last sync is still within their ref's sync_ttl`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return $(t,a,async()=>{let r=await Om(t,Pm(e,n));Q(t,a,Nm(r.results),{results:r.results}),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},Im=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},Lm=(e,t,n)=>{if(n===void 0)return e.tag_format;let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r.tag_format??e.tag_format},Rm=(e,t)=>{if(!G(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},zm=async(e,t)=>{let n=H(e.env),r=await W(n),i=Kf(r,t.query),a=Im(r,i),o=Lm(a,i,t.opts.packageName),s=U(n,i);Rm(s,i);let c=await Uc(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},Bm=e=>[`${e.key}@${e.version} -> ${e.tag}`],Vm=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Hm=[Pf,Lf,xp,Rp,qp,Fm,(e,t)=>{e.command(`tag`).description(`Resolve a version to its git tag, via the ref's (or a package's) tag_format.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<version>`,`version to resolve, e.g. 4.1.0`).option(`--package <name>`,`resolve against this package's tag_format instead of the ref's`).action((e,n,r,i)=>{let a=i.optsWithGlobals(),o={json:a.json===!0,verbose:a.verbose===!0};return $(t,o,async()=>{let i=await zm(t,{opts:Vm(r),query:e,version:n});Q(t,o,Bm(i),i)})()})}],Um=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},Wm=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,Um(e)])):n===void 0?{}:{[n]:{path:t??`.`}},Gm=e=>{let t=e.description??``;return e.tag_format===void 0?{description:t,path:e.path}:{description:t,path:e.path,tag_format:e.tag_format}},Km=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,Gm(t)]))},qm=e=>e.description===void 0||e.description===``,Jm=e=>Object.entries(e).filter(([,e])=>qm(e)).map(([e])=>e).toSorted(),Ym=e=>{let t=Jm(e);if(t.length!==0)throw b(`packages without a detected description: ${t.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},Xm=e=>{if(Object.keys(e).length!==0)return e},Zm=e=>{if(e===null)throw b(`tag_format_candidate must be set to a valid tag format (containing '{version}') before finalizing — edit the proposal and provide one, or add the ref manually`);return e},Qm=e=>e.packages===void 0?{default_branch:e.default_branch,description:e.description,tag_format:e.tag_format,url:e.url}:{default_branch:e.default_branch,description:e.description,packages:e.packages,tag_format:e.tag_format,url:e.url},$m=[],eh=e=>e===void 0?[...$m]:[e],th=async(e,t,n)=>{let r=await xc(e.runner,t),i=Vc(await Oc(e.runner,t));return Od(e,`detecting workspace packages…`),{defaultBranch:r,packages:Wm(await cd(t),n.npmDirectory,n.npmPkgName),tagFormatCandidate:i}},nh=(e,t)=>Y(t.home,Jf(t.resolved.key),async()=>{let n=await sm(e,{allowFileUrls:Yf(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await th(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),rh=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},ih=async(e,t)=>{let n=H(e.env),r=await W(n),i=$f(await Qf(e,t),r.settings);tp(r,i.key),await sp(n,i.key);let a=U(n,i.key),o=X(`clone_mode`,void 0,r.settings),s=await nh(e,{cloneMode:o,dest:a,home:n,resolved:i});return rh({cloneResult:s,dest:a,resolved:i})},ah=(e,t,n)=>Y(e,`home`,async()=>{tp(await W(e),t);let r=await Z(e),i=r.refs[t],a=n??i?.effective_clone_mode,o={...i,pending_proposal_at:new Date().toISOString()};a!==void 0&&(o.effective_clone_mode=a),r.refs[t]=o,await Vu(e,r)}),oh=(e,t)=>{let n=ss.safeParse(e);if(!n.success)throw b(O(n.error));let r=Ru.safeParse(t);if(!r.success)throw b(O(r.error));return{config:n.data,state:r.data}},sh=async(e,t)=>{let n=await W(e.home);tp(n,e.ref.key);let r=Qm(e.ref);n.refs[e.ref.key]=r;let i=await Z(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??X(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...oh(n,i),entry:r}},ch=async(e,t)=>{let n=Yf(e.env),r=await Y(t.home,Jf(t.ref.key),()=>(Us(t.home,t.dest),um(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return Y(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await sh(t,r);return await Vu(t.home,i),await Zs(t.home,e),{entry:n,key:t.ref.key}})},lh=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),uh=e=>e instanceof Error?e.message:String(e),dh=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${uh(e)}`)}},fh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ph=e=>fh(e)&&`ok`in e&&!(`key`in e),mh=e=>{if(!ph(e))return e;if(e.ok===!1)throw b(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(fh(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},hh=e=>e.code===`unrecognized_keys`,gh=e=>e.path.length===0,_h=(e,t)=>{let n=t.toSorted().map(e=>`"${e}"`).join(`, `);return e===``?`✖ unrecognized key(s) in proposal: ${n}`:`✖ unrecognized key(s) in proposal at ${e}: ${n}`},vh=e=>{let t=new Map;for(let n of e){let e=ct(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>_h(e,t))},yh=e=>`✖ invalid proposal: ${e.message}`,bh=e=>{let t=e.issues.filter(e=>hh(e)),n=e.issues.filter(e=>!hh(e)),r=n.filter(e=>gh(e));if(t.length===0&&r.length===0)return O(e);let i=n.filter(e=>!gh(e)),a=[...vh(t),...r.map(e=>yh(e))];return i.length>0&&a.push(O({issues:i})),a.join(`
369
- `)},xh=e=>{let t=Iu.safeParse(e);if(!t.success)throw b(bh(t.error));return t.data},Sh=async(e,t)=>{let n=await lh(e,t);return xh(mh(dh(n)))},Ch=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],wh=async(e,t)=>{let n=await ih(e,t);await ah(H(e.env),n.proposal.key,n.effectiveCloneMode);let r=eh(n.warning);return{data:n.proposal,human:Ch(n.proposal.key,n.dest),warnings:r}},Th=e=>[`refs add: '${e}' added to config`],Eh=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,tag_format:Zm(e.tag_format_candidate),url:e.url},n=Xm(e.packages);return n!==void 0&&(t.packages=n),t},Dh=async(e,t)=>{let n=await Sh(e,t),r=H(e.env),i=U(r,n.key);if(!G(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let{entry:a,key:o}=await ch(e,{dest:i,home:r,ref:Eh(n)});return{data:{entry:a,key:o},human:Th(o),warnings:[]}},Oh=(e,t)=>{Ym(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,tag_format:Zm(e.proposal.tag_format_candidate),url:e.proposal.url},r=Km(e.proposal.packages);return r!==void 0&&(n.packages=r),n},kh=async(e,t,n)=>{let r=await ih(e,t),i=H(e.env),a=Oh(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await ch(e,o),l=eh(r.warning);return{data:{entry:s,key:c},human:Th(c),warnings:l}},Ah=e=>{let t=[e.dryRun,e.proposal!==void 0,e.description!==void 0].filter(Boolean).length;if(t>1)throw y(`refs add: use only one of --dry-run, --proposal, or --description`);if(t===0)throw y(`refs add needs --dry-run, --proposal, or --description`)},jh=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},Mh=(e,t)=>(Ah(t),t.proposal===void 0?t.description===void 0?wh(e,jh(t.source)):kh(e,jh(t.source),t.description):Dh(e,t.proposal)),Nh=(e,t)=>{let n={dryRun:t.dryRun===!0};return e!==void 0&&(n.source=e),t.proposal!==void 0&&(n.proposal=t.proposal),t.description!==void 0&&(n.description=t.description),n},Ph=(e,t)=>{e.command(`add`).description(`Add a git reference in two phases: propose (--dry-run), then finalize (--proposal).`).argument(`[source]`,`git url or npm:<package> (omit when finalizing with --proposal)`).option(`--dry-run`,`resolve and clone the source, writing a reviewable proposal`).option(`--proposal <file>`,`finalize from a completed proposal JSON file (- for stdin)`).option(`--description <text>`,`one-shot: dry-run then finalize immediately with this description`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return $(t,a,async()=>{let r=await Mh(t,Nh(e,n));Q(t,a,r.human,r.data,r.warnings)})()})},Fh=e=>e===void 0?null:e,Ih=()=>Object.keys(as.shape).toSorted().join(`, `),Lh=e=>`unknown package field '${e}' — valid fields: ${Ih()}`,Rh=e=>Object.hasOwn(as.shape,e),zh=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},Bh=(e,t,n)=>{if(!Rh(t))throw y(Lh(t));let r=e[t],i=as.safeParse({...e,[t]:n});if(!i.success)throw b(O(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},Vh=async e=>{let t=zh(e.entry,e.key,e.packageName),n=Bh(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await Zs(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:Fh(n.newValue),old:Fh(n.oldValue)}},Hh=`packages`,Uh=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},Wh=()=>Object.keys(os.shape).filter(e=>e!==Hh).toSorted().join(`, `),Gh=e=>`unknown ref field '${e}' — valid fields: ${Wh()}`,Kh=e=>Object.hasOwn(os.shape,e),qh=(e,t,n)=>`failed to rewrite git remote at ${e} to '${q(t)}': ${n.trim()}`,Jh=async(e,t)=>{if(Us(t.home,t.dest),!G(t.dest))return;let n=await e.runner.run(`git`,[`remote`,`set-url`,`origin`,t.cloneUrl],{cwd:t.dest});if(n.exitCode!==0)throw b(qh(t.dest,t.cloneUrl,n.stderr))},Yh=async(e,t)=>{let n=J(t.value,{allowFileUrls:Yf(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=U(t.home,t.key);return await Jh(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},Xh=(e,t,n)=>{let r={...e,[t]:n},i=os.safeParse(r);if(!i.success)throw b(O(i.error));return i.data},Zh=(e,t)=>t.field===`url`?Yh(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(Xh(t.entry,t.field,t.value)),Qh=async(e,t)=>{let{field:n}=t;if(n===Hh)throw y(`use --package <name> <field> <value>`);if(!Kh(n))throw y(Gh(n));let r=t.entry[n],i=await Zh(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},$h=(e,t)=>{let n=H(e.env),{field:r,opts:i,query:a,value:o}=t;return Y(n,`home`,async()=>{let t=await W(n),s=Kf(t,a),c=Uh(t,s);if(i.packageName!==void 0)return Vh({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await Qh(e,{entry:c,field:r,home:n,key:s,value:o});return await Zs(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:Fh(l.new),old:Fh(l.old)}})},eg=`settings`,tg=[],ng=()=>Object.keys(rs.shape).toSorted().join(`, `),rg=e=>`unknown setting '${e}' — valid settings: ${ng()}`,ig=e=>Object.hasOwn(rs.shape,e),ag=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,og=e=>{try{let t=Kf(e,eg);return[ag(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[ag("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return tg;throw e}},sg=e=>({data:{field:e.key,key:eg,new:Fh(e.parsed[e.key]),old:Fh(e.old)},warnings:og(e.config)}),cg=(e,t)=>{let n=H(e.env);return Y(n,`home`,async()=>{let e=await W(n);if(!ig(t.key))throw y(rg(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=rs.safeParse(i);if(!a.success)throw b(O(a.error));return await Zs(n,{...e,settings:a.data}),sg({config:e,key:t.key,old:r,parsed:a.data})})},lg=[],ug=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},dg=async(e,t)=>{if(t.first===`settings`){if(t.opts.packageName!==void 0)throw y(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return cg(e,{key:t.second,value:t.value})}return{data:await $h(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:lg}},fg=e=>e==null?`(unset)`:String(e),pg=e=>[`${e.key}: ${e.field} '${fg(e.old)}' -> '${fg(e.new)}'`],mg=(e,t)=>{e.command(`edit`).description(`Edit one field: 'refs edit settings <key> <value>' for a global setting, or 'refs edit <ref> <field> <value> [--package <name>]' for a ref or package field.`).argument(`<ref-or-settings>`,`a ref key/unique suffix, or the literal 'settings'`).argument(`<field-or-key>`,`field to edit (or, in settings mode, the setting key)`).argument(`<value>`,`the new value`).option(`--package <name>`,`edit this package's field instead of a top-level ref field`).action((e,n,r,i,a)=>{let o=a.optsWithGlobals(),s={json:o.json===!0,verbose:o.verbose===!0};return $(t,s,async()=>{let{data:a,warnings:o}=await dg(t,{first:e,opts:ug(i),second:n,value:r});Q(t,s,pg(a),a,o)})()})},hg=`Install the agent skill: npx skills add kaisers-io/refs (private phase: npx skills add <path-to-this-repo> --skill refs)`,gg=async e=>{await a(e.root,{recursive:!0}),await a(e.sourcesDir,{recursive:!0}),await a(e.locksDir,{recursive:!0}),await a(e.hooksDir,{recursive:!0})},_g=async e=>{let t=H(e.env);return await gg(t),{config:await Y(t,`home`,async()=>{let e=await cc(t,kd);return await jc(t),e}),home:t.root,skill_hint:hg}},vg=[(e,t)=>{e.command(`init`).description(`Seed or migrate the refs home directory, its config, and the git hooks guard.`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return $(t,i,async()=>{let e=await _g(t);Q(t,i,[`refs home: ${e.home} (${e.config})`,hg],e)})()})},Ph,mg,qf,...Hm],yg=(e,t)=>{for(let n of vg)n(e,t)},bg=[``,`Examples:`,` $ refs list --json`,` $ refs sync --stale-only --json`,` $ refs resolve zod/mini --json`,``,`Every command accepts --json for structured output and --verbose for stack traces on error.`].join(`
370
- `),xg=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),Sg=`--json`,Cg=`--verbose`,wg=/\n$/u,Tg=/^error: /u,Eg=e=>e.replace(Tg,``),Dg=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},Og=e=>Dg(e,Sg),kg=e=>Dg(e,Cg),Ag=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,jg=e=>{let t=new Sd().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(kd).option(Sg,`emit machine-readable JSON on stdout instead of human-readable text`).option(Cg,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(wg,``))},writeOut:t=>{e.out(t.replace(wg,``))}});return t.addHelpText(`after`,bg),yg(t,e),t},Mg=()=>{process.exitCode=g.OK},Ng=(e,t,n)=>{Dd(e,t,{code:`usage`,message:Ag(Eg(n.message),n.stack,t.verbose)}),process.exitCode=g.USAGE},Pg=(e,t,n)=>{if(xg.has(n.code)){Mg();return}Ng(e,t,n)},Fg=(e,t,n)=>{let r=be(n,{verbose:t.verbose});Dd(e,t,r),process.exitCode=r.exitCode},Ig=async(e,t,n)=>{let r={json:Og(n),verbose:kg(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof dd){Pg(e,r,t);return}Fg(e,r,t)}},Lg=(e,t)=>Ig(e,jg(e),t);import.meta.main&&await Lg(ud(),process.argv);export{jg as buildProgram,Q as emit,Dd as emitError,Od as progress,ud as realContext,yg as registerCommands,Lg as run,Ig as runProgram,$ as wrapAction};
370
+ - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=p.resolve(e,t);if(ce.existsSync(r))return r;if(n.includes(p.extname(t)))return;let i=n.find(e=>ce.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||``;if(this._scriptPath){let e;try{e=ce.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=p.resolve(p.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=p.basename(this._scriptPath,p.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(p.extname(i)),s;h.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=df(h.execArgv).concat(t),s=he.spawn(h.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=df(h.execArgv).concat(t),s=he.spawn(h.argv[0],t,{stdio:`inherit`})):s=he.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{h.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new Qd(e,`commander.executeSubCommandAsync`,`(close)`)):h.exit(e)}),s.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(i,a,e._name);else if(t.code===`EACCES`)throw Error(`'${i}' not executable`);if(!c)h.exit(1);else{let e=new Qd(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,c(e)}}),this.runningCommand=s}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
371
+ `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in h.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,h.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new af(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=lf(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=lf(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>tf(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=p.basename(e,p.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(h.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
372
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function df(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function ff(){if(h.env.NO_COLOR||h.env.FORCE_COLOR===`0`||h.env.FORCE_COLOR===`false`)return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}new uf;const pf=[],mf=e=>Array.isArray(e)?e:[e],Z=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??pf};e.out(JSON.stringify(t));return}for(let t of mf(n))e.out(t);for(let t of i??pf)e.errLine(`refs: warning: ${t}`)},hf=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},gf=(e,t)=>{e.errLine(`refs: ${t}`)},Q=(e,t,n)=>async()=>{try{await n()}catch(n){let r=be(n,{verbose:t.verbose});hf(e,t,r),process.exitCode=r.exitCode}};var _f=`0.3.0`;const vf=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},yf=(e,t)=>{if(!G(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},bf=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},xf=(e,t)=>{if(e===void 0)return t.def;let n=Number(e);if(!Number.isInteger(n)||n<1)throw y(`--limit must be a positive integer, got '${e}'`);return n},Sf=(e,t,n)=>e===void 0?!0:n-Date.parse(e)>t,Cf=(e,t,n)=>{let r=e.state.refs[t],i=Zo(Y(`sync_ttl`,n,e.settings));return{clone_mode:Y(`clone_mode`,n,e.settings),description:n.description,key:t,missing:!G(U(e.home,z.parse(t))),packages:Object.keys(n.packages??{}).toSorted(),stale:Sf(r?.last_fetched_at,i,e.now)}},wf=e=>{let t={home:e.home,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>Cf(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},Tf=async e=>{let t=H(e.env),n=await W(t),r=await X(t);return wf({config:n,home:t,now:Date.now(),state:r})},Ef=e=>{let t=[];return e.stale&&t.push(`[stale]`),e.missing&&t.push(`[missing]`),t.length===0?``:` ${t.join(` `)}`},Df=e=>e.length===0?[`no refs configured — run: refs add <source>`]:e.map(e=>`${e.key} ${e.description}${Ef(e)}`),Of=e=>e.split(`/`),kf=(e,t)=>{let n=Of(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},$=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=Of(t),r=Object.keys(e.refs).filter(e=>kf(e,n)).toSorted(),[i]=r;if(i===void 0)throw v(`no ref matches '${t}'`);if(r.length>1)throw y(`'${t}' matches more than one ref: ${r.join(`, `)}`);return z.parse(i)},Af=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return Q(t,i,async()=>{let e=await Tf(t);Z(t,i,Df(e),e)})()})},jf=(e,t,n)=>{if(n===void 0)return{format:e.tag_format};let r=bf(e,t,n);return{format:r.tag_format??e.tag_format,path:r.path}},Mf=e=>{let t={newTag:e.newTag,oldTag:e.oldTag};return e.packagePath!==void 0&&(t.pathScope=e.packagePath),t},Nf=async(e,t)=>{let n={newTag:t.newTag,oldTag:t.oldTag},r=Mf(t),[i,a,o,s]=await Promise.all([Sc(e.runner,t.dest,n),wc(e.runner,t.dest,{...n,limit:t.limit}),Tc(e.runner,t.dest,r),Ec(e.runner,t.dest,{...r,limit:200})]);return{commitCount:i,commits:a,diff:o,paths:s}},Pf=e=>{let t={maxChars:4e3,newTag:e.newTag,newVersion:e.args.newVersion,oldVersion:e.args.oldVersion};return e.scope.path!==void 0&&(t.packagePath=e.scope.path),t},Ff=e=>{let t={dest:e.dest,limit:e.args.opts.limit,newTag:e.newTag,oldTag:e.oldTag};return e.scope.path!==void 0&&(t.packagePath=e.scope.path),t},If=e=>e===void 0?null:e,Lf=async(e,t)=>{let[n,r]=await Promise.all([Nf(e,Ff(t)),Bc(e.runner,t.dest,Pf(t))]);return{changed_paths:n.paths.paths,changelog:If(r?.excerpt),commit_count:n.commitCount,commits:n.commits,diff:n.diff,key:t.key,new:{tag:t.newTag,version:t.args.newVersion},old:{tag:t.oldTag,version:t.args.oldVersion},package:If(t.args.opts.packageName),truncated:{changelog:r?.truncated??!1,commits:n.commitCount>n.commits.length,paths:n.paths.truncated}}},Rf=async(e,t)=>{let n=H(e.env),r=await W(n),i=$(r,t.query),a=vf(r,i),o=jf(a,i,t.opts.packageName),s=U(n,i);yf(s,i);let[c,l]=await Promise.all([Ol(e.runner,s,o.format,t.oldVersion),Ol(e.runner,s,o.format,t.newVersion)]);return Lf(e,{args:t,dest:s,key:i,newTag:l,oldTag:c,scope:o})},zf=e=>e.changelog===null?`changelog: not found`:e.truncated.changelog?`changelog: found (truncated)`:`changelog: found`,Bf=e=>[`${e.key}: ${e.old.tag} -> ${e.new.tag}`,`commits: ${e.commit_count} (showing ${e.commits.length})`,`files changed: ${e.diff.files_changed} (+${e.diff.insertions} -${e.diff.deletions})`,zf(e)],Vf=e=>{let t={limit:xf(e.limit,{def:50})};return e.package!==void 0&&(t.packageName=e.package),t},Hf=(e,t)=>{e.command(`range`).description(`Digest of what changed between two versions of a ref: commits, diff, changelog.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<old-version>`,`older version, e.g. 4.0.0`).argument(`<new-version>`,`newer version, e.g. 4.1.0`).option(`--package <name>`,`resolve tags via this package's tag_format and scope the diff`).option(`--limit <n>`,`maximum commits to list (default 50)`).action((e,n,r,i,a)=>{let o=a.optsWithGlobals(),s={json:o.json===!0,verbose:o.verbose===!0};return Q(t,s,async()=>{let a=await Rf(t,{newVersion:r,oldVersion:n,opts:Vf(i),query:e});Z(t,s,Bf(a),a)})()})},Uf=[`dist`,`build`,`out`,`vendor`,`node_modules`,`coverage`],Wf=[`*.min.*`,`*.lock`],Gf=[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`],Kf=[...Uf.map(e=>`:(glob,exclude)**/${e}/**`),...Wf.map(e=>`:(exclude)${e}`),...Gf.map(e=>`:(glob,exclude)**/${e}`)],qf=e=>e?[...Kf]:[],Jf=e=>e.startsWith(`/`)||e.split(`/`).includes(`..`),Yf=e=>{if(e.startsWith(`:`))throw y(`--glob takes a plain glob pattern, not a git pathspec`);if(Jf(e))throw y(`--glob takes a pattern inside the search root, not an absolute path or a '..' segment`);return`:(glob)${e}`},Xf=[],Zf=(e,t,n)=>{if(n!==void 0)return bf(e,t,n).path},Qf=(e,t)=>t===void 0||t===`.`?e:m(e,t),$f=(e,t,n)=>{if(!le(e))throw v(`package path '${e}' is missing from the checkout — run: refs sync ${n}`);e!==t&&Us(t,e,`checkout for '${n}'`)},ep=(e,t)=>t===void 0||t===`.`?e:{matches:e.matches.map(e=>({...e,path:`${t}/${e.path}`})),truncated:e.truncated},tp=e=>e===void 0?null:e,np=(e,t)=>({excludes_applied:t.excludes,key:t.key,match_count:t.result.matches.length,matches:t.result.matches,package:tp(e.opts.packageName),pattern:e.pattern,truncated:t.result.truncated}),rp=async(e,t)=>{let n=H(e.env),r=await W(n),i=$(r,t),a=vf(r,i),o=U(n,i);return yf(o,i),{dest:o,entry:a,key:i}},ip=async(e,t)=>{let{dest:n,entry:r,key:i}=await rp(e,t.query),a=t.opts.globs.map(e=>Yf(e)),o=Zf(r,i,t.opts.packageName),s=qf(t.opts.defaultExcludes),c=Qf(n,o);$f(c,n,i);let l=await qc(e.runner,{dir:c,limit:t.opts.limit,pathspecs:[...a,...s],pattern:t.pattern}),u=ep(l,o);return np(t,{excludes:s,key:i,result:u})},ap=e=>`${e.path}:${e.line}: ${e.snippet}`,op=e=>e.truncated?`${e.match_count} matches shown (truncated at --limit; more matches exist)`:`${e.match_count} match(es)`,sp=e=>[...e.matches.map(ap),op(e)],cp=(e,t)=>[...t,e],lp=e=>{let t={defaultExcludes:e.defaultExcludes,globs:e.glob,limit:xf(e.limit,{def:50})};return e.package!==void 0&&(t.packageName=e.package),t},up=[Hf,(e,t)=>{e.command(`search`).description(`Bounded structured code search (git grep) over a ref checkout.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<pattern>`,`extended regular expression, passed to git grep --extended-regexp`).option(`--package <name>`,`scope the search to this package's registered path`).option(`--limit <n>`,`maximum matches to return (default 50)`).option(`--glob <pattern>`,`plain glob pattern to scope the search (repeatable; relative to the package path when --package is given)`,cp,Xf).option(`--no-default-excludes`,`also search build output, vendored deps, and lockfiles`).action((e,n,r,i)=>{let a=i.optsWithGlobals(),o={json:a.json===!0,verbose:a.verbose===!0};return Q(t,o,async()=>{let i=await ip(t,{opts:lp(r),pattern:n,query:e});Z(t,o,sp(i),i)})()})}],dp=async e=>{let t=await e.runner.run(`git`,[`--version`]);return t.exitCode===0?{detail:t.stdout.trim(),name:`git`,status:`ok`}:{detail:t.stderr.trim()||`git --version exited with code ${t.exitCode}`,name:`git`,status:`fail`}},fp=/^v(?<major>\d+)\.(?<minor>\d+)/u,pp=e=>{let t=fp.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(!(n===void 0||r===void 0))return{major:Number(n),minor:Number(r)}},mp=e=>e===void 0?!1:e.major>24?!0:e.major===24&&e.minor>=12,hp=e=>{let{nodeVersion:t}=e;return mp(pp(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.12`,name:`node`,status:`fail`}},gp=e=>e instanceof Error?e.message:String(e),_p=()=>ss.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),vp=async e=>{try{return{config:await W(e)}}catch(e){return{config:_p(),errorMessage:gp(e)}}},yp=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},bp=[`.claude`,`skills`,`refs`,`SKILL.md`],xp=[`.codex`,`skills`,`refs`,`SKILL.md`],Sp=e=>e===void 0?[]:[m(e,...bp),m(e,...xp)],Cp=async t=>{try{return await e(t),!0}catch{return!1}},wp=async e=>{let t=Sp(e.env.HOME);return(await Promise.all(t.map(e=>Cp(e)))).some(Boolean)?{detail:`the refs skill is installed`,name:`skill`,status:`ok`}:{detail:`refs skill not found — install it: npx skills add kaisers-io/refs`,name:`skill`,status:`warn`}},Tp=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),Ep=[`pre-commit`,`pre-push`],Dp=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},Op=async e=>{let t=await Promise.all(Ep.map(t=>Dp(e,t)));return Ep.filter((e,n)=>!t[n])},kp=async(e,t,n)=>{let r=await e.runner.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:n});return r.exitCode===0&&r.stdout.trim()===t.hooksDir},Ap=e=>e.missingHooks.length>0?{detail:`${e.missingHooks.map(e=>`hooks/${e}`).join(`, `)} missing or not executable — run: refs init`,name:`hooks-guard`,status:`fail`}:e.badKeys.length>0?{detail:`core.hooksPath not set for: ${e.badKeys.join(`, `)} — run: refs init`,name:`hooks-guard`,status:`fail`}:{detail:`${Ep.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},jp=async(e,t,n)=>{let r=Tp(t,n),[i,a]=await Promise.all([Op(t),Promise.all(r.map(n=>kp(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return Ap({badKeys:o,checkoutCount:r.length,missingHooks:i})},Mp=async(e,t)=>{let n=await e.runner.run(`git`,[`status`,`--porcelain`],{cwd:t.dest});return n.exitCode===0?{broken:!1,detail:``,dirty:n.stdout.trim()!==``,key:t.key}:{broken:!0,detail:n.stderr.trim(),dirty:!1,key:t.key}},Np=e=>{let t=e.filter(e=>e.broken);if(t.length>0)return{detail:t.map(e=>`${e.key}: git status failed — ${e.detail}`).join(`; `),name:`dirty-checkouts`,status:`fail`};let n=e.filter(e=>e.dirty).map(e=>e.key);return n.length===0?{detail:`no local changes in any checkout`,name:`dirty-checkouts`,status:`ok`}:{detail:`local changes will be discarded on next sync: ${n.join(`, `)}`,name:`dirty-checkouts`,status:`warn`}},Pp=async(e,t,n)=>{let r=Tp(t,n),i=await Promise.all(r.map(t=>Mp(e,t)));return Np(i)},Fp=async e=>{try{return await X(e)}catch{return Td.parse({})}},Ip=async e=>{try{return(await s(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(V(e))return[];throw e}},Lp=async(e,t)=>{if(G(e))return[[...t]];let n=await Ip(e);return(await Promise.all(n.map(n=>Lp(m(e,n),[...t,n])))).flat()},Rp=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r===void 0?!1:n-Date.parse(r)<864e5},zp=(e,t,n)=>Rp(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,Bp=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),Vp=async(e,t,n)=>{let r=(await Lp(e.sourcesDir,[])).map(t=>Bp(e,t)).filter(e=>!Object.hasOwn(t.refs,e.key));if(r.length===0)return{detail:`no orphaned checkouts under sources/`,name:`orphans`,status:`ok`};let i=Date.now();return{detail:r.map(e=>zp(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},Hp=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,Up=e=>e===``?{}:{user:e},Wp=e=>e===``?{}:{port:e},Gp=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...Up(t.username),...Wp(t.port)}:void 0}catch{return}},Kp=e=>{let t=Hp.exec(e),n=t?.groups?.host;return n===void 0?Gp(e):{host:n,user:t?.groups?.user??`git`}},qp=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,Jp=e=>e.user===void 0?qp(e):`${e.user}@${qp(e)}`,Yp=e=>{let t=Object.values(e.refs).map(e=>Kp(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(Jp(e),e);return[...n.values()].toSorted((e,t)=>Jp(e).localeCompare(Jp(t)))},Xp=/Permission denied/u,Zp=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Qp=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,$p=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Qp(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},em=async(e,t,n)=>{let r=Jp(t),i=await e.runner.run(`ssh`,$p(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:Xp.test(i.stderr)?{host:r,outcome:`denied`}:Zp.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},tm=(e,t)=>{let n=e.filter(e=>e.outcome===`timeout`).map(e=>e.host);if(n.length!==0)return{detail:`ssh probe timed out after ${t/1e3}s: ${n.join(`, `)}`,name:`ssh-auth`,status:`fail`}},nm=e=>{let t=e.filter(e=>e.outcome===`denied`).map(e=>e.host);if(t.length!==0)return{detail:`ssh permission denied for: ${t.join(`, `)}`,name:`ssh-auth`,status:`fail`}},rm=e=>{let t=e.filter(e=>e.outcome===`connection-warn`);if(t.length!==0)return{detail:`ssh connection issue, treated as warn: ${t.map(e=>`${e.host} (${e.detail??``})`).join(`; `)}`,name:`ssh-auth`,status:`warn`}},im=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),am=(e,t)=>tm(e,t)??nm(e)??rm(e)??im(e),om=async(e,t,n)=>{let r=Yp(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>em(e,t,i)));return am(a,i)},sm=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${gp(t)}`,name:e.name,status:`fail`}}},cm=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await sm(t),i=await cm(n);return r===void 0?i:[r,...i]},lm=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>dp(n)},{name:`node`,run:()=>Promise.resolve(hp(n))},{name:`config`,run:()=>Promise.resolve(yp(t.errorMessage))},{name:`hooks-guard`,run:()=>jp(n,r,t.config)},{name:`dirty-checkouts`,run:()=>Pp(n,r,t.config)},{name:`orphans`,run:()=>Vp(r,t.config,i)},{name:`skill`,run:()=>wp(n)},{name:`ssh-auth`,run:()=>om(n,t.config)}]},um=async e=>{let t=H(e.env),n=await vp(t),r=await Fp(t);return cm(lm({configLoad:n,ctx:e,home:t,state:r}))},dm={fail:`FAIL`,ok:`OK`,warn:`WARN`},fm=e=>e.map(e=>`[${dm[e.status]}] ${e.name}: ${e.detail}`),pm=e=>e.some(e=>e.status===`fail`),mm=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, ssh).`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return Q(t,i,async()=>{let e=await um(t);Z(t,i,fm(e),{checks:e}),pm(e)&&(process.exitCode=g.UNEXPECTED)})()})},hm=async e=>{let t=H(e.env),n=await J(t,`home`,()=>lc(t,_f));return n===`migrated`?{backup:Bs(t),result:n}:{backup:null,result:n}},gm=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${te(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,_m=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return Q(t,i,async()=>{let e=await hm(t);Z(t,i,gm(e),e)})()})},vm=e=>`ref:${e.replaceAll(`/`,`_`)}`,ym=e=>e.REFS_ALLOW_FILE_URLS===`1`,bm=(e,t)=>{let n=Yl(t,{allowFileUrls:ym(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},xm=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);gf(e,`resolving npm package '${t}'…`);let n=await Zu(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},Sm=(e,t)=>t.startsWith(`npm:`)?xm(e,t.slice(4)):Promise.resolve(bm(e,t)),Cm=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Y(`git_transport`,void 0,t);return{...e,cloneUrl:su(e.cloneUrl,n)}},wm=e=>`ref '${e}' already exists — use refs edit or refs remove`,Tm=(e,t)=>{if(e.refs[t]!==void 0)throw ve(wm(t))},Em=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},Dm=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),Om=async(e,t)=>{let n=await Em(e);if(n===void 0)return{kind:`stop`};let r=Dm(n);if(r.includes(t))return{kind:`continue`,nextDir:m(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},km=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await Om(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):km(a.nextDir,i,[...n,r])},Am=[],jm=async(e,t)=>{let n=await km(e.sourcesDir,t.split(`/`),Am);if(n!==void 0)throw ve(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},Mm=[],Nm=e=>e===void 0?Mm:[e],Pm=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},Fm=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},Im=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},Lm=async e=>{let t=await Fm(e);if(t===void 0)return!0;if(t.length!==0)return!1;try{await d(e)}catch(e){if(!V(e))throw e}return!0},Rm=async e=>{let t=await Im(e);return t===void 0?!0:t?Lm(e):!1},zm=async(e,t)=>{t!==e.sourcesDir&&await Rm(t)&&await zm(e,ne(t))},Bm=async(e,t)=>await Pm(t)?(Ws(e,t),await u(t,{force:!0,recursive:!0}),await zm(e,ne(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},Vm=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),Hm=async(e,t)=>{let n=await W(e);await Qs(e,{...n,refs:Vm(n.refs,t)});let r=await X(e);await Od(e,{...r,refs:Vm(r.refs,t)})},Um=async(e,t)=>{let n=H(e.env),r=$(await W(n),t),i=U(n,r),{removedCheckout:a,warning:o}=await J(n,vm(r),()=>Bm(n,i));return await J(n,`home`,()=>Hm(n,r)),{data:{key:r,removed_checkout:a},warnings:Nm(o)}},Wm=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],Gm=(e,t)=>{e.command(`remove`).description(`Remove a configured ref: its config/state entry AND its checkout directory.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return Q(t,a,async()=>{let{data:n,warnings:r}=await Um(t,e);Z(t,a,Wm(n),n,r)})()})},Km=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,qm=/^[a-z][a-z0-9+.-]*:\/\//iu,Jm=/^git@[^:/\s]+:[^\s]+$/u,Ym=e=>qm.test(e)||Jm.test(e),Xm=(e,t)=>{try{return Yl(e,t)}catch{if(Ym(e))throw b(`query looks like a git url but is not a supported form — check the url (credentials are never accepted) or run: refs resolve <package|ref-suffix>`);return}},Zm=(e,t,n)=>{let r=Xm(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(Km(t))}},Qm=(e,t)=>{let n=[];for(let r of Object.keys(e.refs).toSorted()){let i=e.refs[r]?.packages?.[t];i!==void 0&&n.push({entry:i,key:z.parse(r)})}return n},$m=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,eh=(e,t)=>{let n=Qm(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y($m(t,n.map(e=>e.key)));return r}},th=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=eh(e,r);if(i!==void 0)return{...i,name:r}}},nh=(e,t)=>{try{return $(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(Km(t)):e}},rh=(e,t,n)=>{let r=Zm(e,t,n);if(r!==void 0)return r;let i=eh(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=th(e,t);return a===void 0?{key:nh(e,t)}:{key:a.key,packageMatch:a}},ih=(e,t)=>{if(e.packageMatch===void 0)return null;let{entry:n,name:r}=e.packageMatch;return{local_path:m(t,n.path),name:r,path:n.path}},ah=async(e,t)=>{let n=H(e.env),r=await W(n),i=rh(r,t,{allowFileUrls:ym(e.env)}),a=vf(r,i.key),o=await X(n),s=U(n,i.key),c=Zo(Y(`sync_ttl`,a,r.settings));return{key:i.key,local_path:s,missing:!G(s),package:ih(i,s),stale:Sf(o.refs[i.key]?.last_fetched_at,c,Date.now())}},oh=e=>{let t=[e.key,`local_path: ${e.local_path}`];return e.package!==null&&t.push(`package: ${e.package.name}`,`local_path: ${e.package.local_path}`),t},sh=(e,t)=>{e.command(`resolve`).description(`Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.`).argument(`<query>`,`git url, npm package name, import path, or unique ref-key suffix`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return Q(t,a,async()=>{let n=await ah(t,e);Z(t,a,oh(n),n)})()})},ch={},lh=e=>e instanceof Error?e.message:String(e),uh=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await pl(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${lh(e)}`}}},dh=[],fh=e=>e===void 0?dh:[e],ph=async(e,t)=>{let n=H(e.env),r=await W(n),i=$(r,t),a=vf(r,i),o=await X(n),s=U(n,i),{tags:c,warning:l}=await uh(e,s);return{data:{...a,key:i,local_path:s,sample_tags:c,state:o.refs[i]??ch},warnings:fh(l)}},mh=e=>{let t=[`${e.key} ${e.description}`,`url: ${e.url}`,`local_path: ${e.local_path}`];return e.sample_tags.length>0&&t.push(`tags: ${e.sample_tags.join(`, `)}`),t},hh=(e,t)=>{e.command(`show`).description(`Show a configured ref: full entry, state, local path, and sample tags.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return Q(t,a,async()=>{let{data:n,warnings:r}=await ph(t,e);Z(t,a,mh(n),n,r)})()})},gh=(e,t)=>{let n={head_sha:t.headSha,last_fetched_at:new Date().toISOString()},r=t.effectiveCloneMode??e?.effective_clone_mode;return r!==void 0&&(n.effective_clone_mode=r),n},_h=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await Qs(e,r))},vh=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await _h(e,t,n.branchRenamedTo);let r=await X(e);r.refs[t]=gh(r.refs[t],n),await Od(e,r)}),yh=async(e,t,n)=>{try{await J(e,`home`,async()=>{let r=await X(e);r.refs[t]={...r.refs[t],last_error:n},await Od(e,r)})}catch{}},bh=e=>{let t=0,n=[];return{acquire:()=>{if(t<e)return t+=1,Promise.resolve();let{promise:r,resolve:i}=Promise.withResolvers();return n.push(()=>{t+=1,i()}),r},release:()=>{--t;let e=n.shift();e!==void 0&&e()}}},xh=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Sh=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,Ch=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,wh=(e,t)=>{try{return Yl(e,{allowFileUrls:t}).key}catch{return}},Th=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=Ch(n),i=wh(t.expectedUrl,t.allowFileUrls),a=wh(r,t.allowFileUrls);if(!(i!==void 0&&a===i))throw ve(Sh(t.dest,r,t.expectedUrl))},Eh=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,Dh=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw ve(Eh(t.dest))},Oh=async(e,t)=>{await a(ne(t.dest),{recursive:!0}),gf(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await il(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},kh=async(e,t)=>(Ws(t.home,t.dest),G(t.dest)?(await Th(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await Dh(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Oh(e,t)),Ah=(e,t)=>`checkout for '${e}' at ${t} is missing or corrupt (git rev-parse HEAD failed) — run: refs remove ${e}, then refs add <source> --dry-run again`,jh=(e,t,n)=>`checkout for '${e}' at ${t} has a HEAD sha refs cannot store yet (${n.length} hex chars, expected 40) — only SHA-1 repositories are supported for now; \`--object-format=sha256\` repositories are not yet supported`,Mh=async(e,t)=>{await Th(e,t),await Dh(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw b(Ah(t.key,t.dest));let r=n.stdout.trim();if(!wd.shape.head_sha.safeParse(r).success)throw b(jh(t.key,t.dest,r));return r},Nh=(e,t,n)=>`sync produced a HEAD sha for '${e}' at ${t} that refs cannot store yet (${n.length} hex chars) — only SHA-1 repositories are supported for now`,Ph=(e,t,n)=>{if(!wd.shape.head_sha.safeParse(n).success)throw b(Nh(e,t,n));return n},Fh=(e,t,n)=>{let r={effectiveCloneMode:t.effectiveMode,headSha:n.headSha,status:`cloned`};return n.actualBranch!==e.ref.default_branch&&(r.branchRenamedTo=n.actualBranch),t.warning!==void 0&&(r.warning=t.warning),r},Ih=async(e,t,n)=>{await a(ne(n),{recursive:!0});let r=Y(`clone_mode`,t.ref,t.settings),i=await il(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await ol(e.runner,n),s=await Mh(e.runner,{allowFileUrls:ym(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return Fh(t,i,{actualBranch:o,headSha:s})},Lh=async(e,t,n)=>{await Dh(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await Th(e.runner,{allowFileUrls:ym(e.env),dest:n,expectedUrl:t.ref.url});let r=await fl(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Ph(t.key,n,r.newSha),status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Rh=(e,t)=>J(t.home,vm(t.key),()=>{let n=U(t.home,t.key);return Ws(t.home,n),G(n)?Lh(e,t,n):Ih(e,t,n)}),zh=e=>e instanceof Error?e.message:String(e),Bh=e=>{let t=[];e.branchRenamedTo!==void 0&&t.push(`default branch renamed to ${e.branchRenamedTo}`),e.warning!==void 0&&t.push(e.warning);let[n]=t;if(n!==void 0)return t.join(` | `)},Vh=(e,t)=>{let n={key:e,status:t.status},r=Bh(t);return r!==void 0&&(n.warning=r),n},Hh=async(e,t)=>{try{let n=await Rh(e,t);return await vh(t.home,t.key,n),Vh(t.key,n)}catch(e){let n=zh(e);return await yh(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},Uh=(e,t)=>e.status===`fulfilled`?e.value:{error:zh(e.reason),key:t,status:`failed`},Wh=async(e,t)=>{let n=bh(4);return(await Promise.allSettled(t.map(t=>xh(n,()=>Hh(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return Uh(e,r.key)})},Gh=(e,t,n)=>({home:e,key:n,ref:vf(t,n),settings:t.settings}),Kh=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>Gh(e,t,z.parse(n))):n.map(n=>Gh(e,t,$(t,n))),qh=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=Zo(Y(`sync_ttl`,t.ref,t.settings)),a=Sf(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},Jh=async(e,t,n)=>{if(!n)return t;let r=await X(e);return qh(e,t,r)},Yh=async(e,t)=>{let n=H(e.env),r=await W(n),i=Kh(n,r,t.refs),a=await Wh(e,await Jh(n,i,t.staleOnly));return{failedCount:a.filter(e=>e.status===`failed`).length,results:a}},Xh=[`updated`,`fresh`,`cloned`,`restored`,`failed`],Zh={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},Qh=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},$h=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,eg=e=>{let t=Qh(e),n=[Xh.map(e=>`${Zh[e]} (${t[e].length})`).join(` / `)];for(let e of Xh)for(let r of t[e])n.push($h(r));return n},tg=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),ng=(e,t)=>{e.command(`sync`).description(`Fetch (or re-clone, if the checkout is missing) configured refs — all by default.`).argument(`[refs...]`,`ref keys or unique suffixes to sync (default: every configured ref)`).option(`--stale-only`,`skip refs whose last sync is still within their ref's sync_ttl`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return Q(t,a,async()=>{let r=await Yh(t,tg(e,n));Z(t,a,eg(r.results),{results:r.results}),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},rg=(e,t,n)=>{if(n===void 0)return e.tag_format;let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r.tag_format??e.tag_format},ig=async(e,t)=>{let n=H(e.env),r=await W(n),i=$(r,t.query),a=vf(r,i),o=rg(a,i,t.opts.packageName),s=U(n,i);yf(s,i);let c=await Ol(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},ag=e=>[`${e.key}@${e.version} -> ${e.tag}`],og=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},sg=[mm,_m,Gm,sh,hh,ng,(e,t)=>{e.command(`tag`).description(`Resolve a version to its git tag, via the ref's (or a package's) tag_format.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<version>`,`version to resolve, e.g. 4.1.0`).option(`--package <name>`,`resolve against this package's tag_format instead of the ref's`).action((e,n,r,i)=>{let a=i.optsWithGlobals(),o={json:a.json===!0,verbose:a.verbose===!0};return Q(t,o,async()=>{let i=await ig(t,{opts:og(r),query:e,version:n});Z(t,o,ag(i),i)})()})}],cg=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},lg=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,cg(e)])):n===void 0?{}:{[n]:{path:t??`.`}},ug=e=>{let t=e.description??``;return e.tag_format===void 0?{description:t,path:e.path}:{description:t,path:e.path,tag_format:e.tag_format}},dg=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,ug(t)]))},fg=e=>e.description===void 0||e.description===``,pg=e=>Object.entries(e).filter(([,e])=>fg(e)).map(([e])=>e).toSorted(),mg=e=>{let t=pg(e);if(t.length!==0)throw b(`packages without a detected description: ${t.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},hg=e=>{if(Object.keys(e).length!==0)return e},gg=e=>{if(e===null)throw b(`tag_format_candidate must be set to a valid tag format (containing '{version}') before finalizing — edit the proposal and provide one, or add the ref manually`);return e},_g=e=>e.packages===void 0?{default_branch:e.default_branch,description:e.description,tag_format:e.tag_format,url:e.url}:{default_branch:e.default_branch,description:e.description,packages:e.packages,tag_format:e.tag_format,url:e.url},vg=[],yg=e=>e===void 0?[...vg]:[e],bg=async(e,t,n)=>{let r=await ol(e.runner,t),i=El(await pl(e.runner,t));return gf(e,`detecting workspace packages…`),{defaultBranch:r,packages:lg(await Yd(t),n.npmDirectory,n.npmPkgName),tagFormatCandidate:i}},xg=(e,t)=>J(t.home,vm(t.resolved.key),async()=>{let n=await kh(e,{allowFileUrls:ym(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await bg(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),Sg=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},Cg=async(e,t)=>{let n=H(e.env),r=await W(n),i=Cm(await Sm(e,t),r.settings);Tm(r,i.key),await jm(n,i.key);let a=U(n,i.key),o=Y(`clone_mode`,void 0,r.settings),s=await xg(e,{cloneMode:o,dest:a,home:n,resolved:i});return Sg({cloneResult:s,dest:a,resolved:i})},wg=(e,t,n)=>J(e,`home`,async()=>{Tm(await W(e),t);let r=await X(e),i=r.refs[t],a=n??i?.effective_clone_mode,o={...i,pending_proposal_at:new Date().toISOString()};a!==void 0&&(o.effective_clone_mode=a),r.refs[t]=o,await Od(e,r)}),Tg=(e,t)=>{let n=ss.safeParse(e);if(!n.success)throw b(O(n.error));let r=Td.safeParse(t);if(!r.success)throw b(O(r.error));return{config:n.data,state:r.data}},Eg=async(e,t)=>{let n=await W(e.home);Tm(n,e.ref.key);let r=_g(e.ref);n.refs[e.ref.key]=r;let i=await X(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Y(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...Tg(n,i),entry:r}},Dg=async(e,t)=>{let n=ym(e.env),r=await J(t.home,vm(t.ref.key),()=>(Ws(t.home,t.dest),Mh(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return J(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await Eg(t,r);return await Od(t.home,i),await Qs(t.home,e),{entry:n,key:t.ref.key}})},Og=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),kg=e=>e instanceof Error?e.message:String(e),Ag=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${kg(e)}`)}},jg=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Mg=e=>jg(e)&&`ok`in e&&!(`key`in e),Ng=e=>{if(!Mg(e))return e;if(e.ok===!1)throw b(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(jg(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},Pg=e=>e.code===`unrecognized_keys`,Fg=e=>e.path.length===0,Ig=(e,t)=>{let n=t.toSorted().map(e=>`"${e}"`).join(`, `);return e===``?`✖ unrecognized key(s) in proposal: ${n}`:`✖ unrecognized key(s) in proposal at ${e}: ${n}`},Lg=e=>{let t=new Map;for(let n of e){let e=ct(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Ig(e,t))},Rg=e=>`✖ invalid proposal: ${e.message}`,zg=e=>{let t=e.issues.filter(e=>Pg(e)),n=e.issues.filter(e=>!Pg(e)),r=n.filter(e=>Fg(e));if(t.length===0&&r.length===0)return O(e);let i=n.filter(e=>!Fg(e)),a=[...Lg(t),...r.map(e=>Rg(e))];return i.length>0&&a.push(O({issues:i})),a.join(`
373
+ `)},Bg=e=>{let t=Cd.safeParse(e);if(!t.success)throw b(zg(t.error));return t.data},Vg=async(e,t)=>{let n=await Og(e,t);return Bg(Ng(Ag(n)))},Hg=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],Ug=async(e,t)=>{let n=await Cg(e,t);await wg(H(e.env),n.proposal.key,n.effectiveCloneMode);let r=yg(n.warning);return{data:n.proposal,human:Hg(n.proposal.key,n.dest),warnings:r}},Wg=e=>[`refs add: '${e}' added to config`],Gg=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,tag_format:gg(e.tag_format_candidate),url:e.url},n=hg(e.packages);return n!==void 0&&(t.packages=n),t},Kg=async(e,t)=>{let n=await Vg(e,t),r=H(e.env),i=U(r,n.key);if(!G(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let{entry:a,key:o}=await Dg(e,{dest:i,home:r,ref:Gg(n)});return{data:{entry:a,key:o},human:Wg(o),warnings:[]}},qg=(e,t)=>{mg(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,tag_format:gg(e.proposal.tag_format_candidate),url:e.proposal.url},r=dg(e.proposal.packages);return r!==void 0&&(n.packages=r),n},Jg=async(e,t,n)=>{let r=await Cg(e,t),i=H(e.env),a=qg(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await Dg(e,o),l=yg(r.warning);return{data:{entry:s,key:c},human:Wg(c),warnings:l}},Yg=e=>{let t=[e.dryRun,e.proposal!==void 0,e.description!==void 0].filter(Boolean).length;if(t>1)throw y(`refs add: use only one of --dry-run, --proposal, or --description`);if(t===0)throw y(`refs add needs --dry-run, --proposal, or --description`)},Xg=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},Zg=(e,t)=>(Yg(t),t.proposal===void 0?t.description===void 0?Ug(e,Xg(t.source)):Jg(e,Xg(t.source),t.description):Kg(e,t.proposal)),Qg=(e,t)=>{let n={dryRun:t.dryRun===!0};return e!==void 0&&(n.source=e),t.proposal!==void 0&&(n.proposal=t.proposal),t.description!==void 0&&(n.description=t.description),n},$g=(e,t)=>{e.command(`add`).description(`Add a git reference in two phases: propose (--dry-run), then finalize (--proposal).`).argument(`[source]`,`git url or npm:<package> (omit when finalizing with --proposal)`).option(`--dry-run`,`resolve and clone the source, writing a reviewable proposal`).option(`--proposal <file>`,`finalize from a completed proposal JSON file (- for stdin)`).option(`--description <text>`,`one-shot: dry-run then finalize immediately with this description`).action((e,n,r)=>{let i=r.optsWithGlobals(),a={json:i.json===!0,verbose:i.verbose===!0};return Q(t,a,async()=>{let r=await Zg(t,Qg(e,n));Z(t,a,r.human,r.data,r.warnings)})()})},e_=e=>e===void 0?null:e,t_=()=>Object.keys(as.shape).toSorted().join(`, `),n_=e=>`unknown package field '${e}' — valid fields: ${t_()}`,r_=e=>Object.hasOwn(as.shape,e),i_=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},a_=(e,t,n)=>{if(!r_(t))throw y(n_(t));let r=e[t],i=as.safeParse({...e,[t]:n});if(!i.success)throw b(O(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},o_=async e=>{let t=i_(e.entry,e.key,e.packageName),n=a_(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await Qs(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:e_(n.newValue),old:e_(n.oldValue)}},s_=`packages`,c_=()=>Object.keys(os.shape).filter(e=>e!==s_).toSorted().join(`, `),l_=e=>`unknown ref field '${e}' — valid fields: ${c_()}`,u_=e=>Object.hasOwn(os.shape,e),d_=(e,t,n)=>`failed to rewrite git remote at ${e} to '${q(t)}': ${n.trim()}`,f_=async(e,t)=>{if(Ws(t.home,t.dest),!G(t.dest))return;let n=await e.runner.run(`git`,[`remote`,`set-url`,`origin`,t.cloneUrl],{cwd:t.dest});if(n.exitCode!==0)throw b(d_(t.dest,t.cloneUrl,n.stderr))},p_=async(e,t)=>{let n=Yl(t.value,{allowFileUrls:ym(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=U(t.home,t.key);return await f_(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},m_=(e,t,n)=>{let r={...e,[t]:n},i=os.safeParse(r);if(!i.success)throw b(O(i.error));return i.data},h_=(e,t)=>t.field===`url`?p_(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(m_(t.entry,t.field,t.value)),g_=async(e,t)=>{let{field:n}=t;if(n===s_)throw y(`use --package <name> <field> <value>`);if(!u_(n))throw y(l_(n));let r=t.entry[n],i=await h_(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},__=(e,t)=>{let n=H(e.env),{field:r,opts:i,query:a,value:o}=t;return J(n,`home`,async()=>{let t=await W(n),s=$(t,a),c=vf(t,s);if(i.packageName!==void 0)return o_({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await g_(e,{entry:c,field:r,home:n,key:s,value:o});return await Qs(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:e_(l.new),old:e_(l.old)}})},v_=`settings`,y_=[],b_=()=>Object.keys(rs.shape).toSorted().join(`, `),x_=e=>`unknown setting '${e}' — valid settings: ${b_()}`,S_=e=>Object.hasOwn(rs.shape,e),C_=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,w_=e=>{try{let t=$(e,v_);return[C_(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[C_("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return y_;throw e}},T_=e=>({data:{field:e.key,key:v_,new:e_(e.parsed[e.key]),old:e_(e.old)},warnings:w_(e.config)}),E_=(e,t)=>{let n=H(e.env);return J(n,`home`,async()=>{let e=await W(n);if(!S_(t.key))throw y(x_(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=rs.safeParse(i);if(!a.success)throw b(O(a.error));return await Qs(n,{...e,settings:a.data}),T_({config:e,key:t.key,old:r,parsed:a.data})})},D_=[],O_=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},k_=async(e,t)=>{if(t.first===`settings`){if(t.opts.packageName!==void 0)throw y(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return E_(e,{key:t.second,value:t.value})}return{data:await __(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:D_}},A_=e=>e==null?`(unset)`:String(e),j_=e=>[`${e.key}: ${e.field} '${A_(e.old)}' -> '${A_(e.new)}'`],M_=(e,t)=>{e.command(`edit`).description(`Edit one field: 'refs edit settings <key> <value>' for a global setting, or 'refs edit <ref> <field> <value> [--package <name>]' for a ref or package field.`).argument(`<ref-or-settings>`,`a ref key/unique suffix, or the literal 'settings'`).argument(`<field-or-key>`,`field to edit (or, in settings mode, the setting key)`).argument(`<value>`,`the new value`).option(`--package <name>`,`edit this package's field instead of a top-level ref field`).action((e,n,r,i,a)=>{let o=a.optsWithGlobals(),s={json:o.json===!0,verbose:o.verbose===!0};return Q(t,s,async()=>{let{data:a,warnings:o}=await k_(t,{first:e,opts:O_(i),second:n,value:r});Z(t,s,j_(a),a,o)})()})},N_=`Install the agent skill: npx skills add kaisers-io/refs (private phase: npx skills add <path-to-this-repo> --skill refs)`,P_=async e=>{await a(e.root,{recursive:!0}),await a(e.sourcesDir,{recursive:!0}),await a(e.locksDir,{recursive:!0}),await a(e.hooksDir,{recursive:!0})},F_=async e=>{let t=H(e.env);return await P_(t),{config:await J(t,`home`,async()=>{let e=await lc(t,_f);return await gl(t),e}),home:t.root,skill_hint:N_}},I_=[(e,t)=>{e.command(`init`).description(`Seed or migrate the refs home directory, its config, and the git hooks guard.`).action((e,n)=>{let r=n.optsWithGlobals(),i={json:r.json===!0,verbose:r.verbose===!0};return Q(t,i,async()=>{let e=await F_(t);Z(t,i,[`refs home: ${e.home} (${e.config})`,N_],e)})()})},$g,M_,Af,...sg,...up],L_=(e,t)=>{for(let n of I_)n(e,t)},R_=[``,`Examples:`,` $ refs list --json`,` $ refs sync --stale-only --json`,` $ refs resolve zod/mini --json`,``,`Every command accepts --json for structured output and --verbose for stack traces on error.`].join(`
374
+ `),z_=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),B_=`--json`,V_=`--verbose`,H_=/\n$/u,U_=/^error: /u,W_=e=>e.replace(U_,``),G_=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},K_=e=>G_(e,B_),q_=e=>G_(e,V_),J_=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,Y_=e=>{let t=new uf().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(_f).option(B_,`emit machine-readable JSON on stdout instead of human-readable text`).option(V_,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(H_,``))},writeOut:t=>{e.out(t.replace(H_,``))}});return t.addHelpText(`after`,R_),L_(t,e),t},X_=()=>{process.exitCode=g.OK},Z_=(e,t,n)=>{hf(e,t,{code:`usage`,message:J_(W_(n.message),n.stack,t.verbose)}),process.exitCode=g.USAGE},Q_=(e,t,n)=>{if(z_.has(n.code)){X_();return}Z_(e,t,n)},$_=(e,t,n)=>{let r=be(n,{verbose:t.verbose});hf(e,t,r),process.exitCode=r.exitCode},ev=async(e,t,n)=>{let r={json:K_(n),verbose:q_(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof Qd){Q_(e,r,t);return}$_(e,r,t)}},tv=(e,t)=>ev(e,Y_(e),t);import.meta.main&&await tv(Zd(),process.argv);export{Y_ as buildProgram,Z as emit,hf as emitError,gf as progress,Zd as realContext,L_ as registerCommands,tv as run,ev as runProgram,Q as wrapAction};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaisers-io/refs",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Managed read-only git checkouts of reference repositories for coding agents.",
5
5
  "license": "MIT",
6
6
  "repository": {