@kaisers-io/refs 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,70 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.13.1] - 2026-09-12
9
+
10
+ ### Upgrading
11
+
12
+ **A repository declaring a workspace pattern like `crates/*/js` will suddenly report packages refs
13
+ could not see before.** The pattern was classified as unsupported, which also made the whole scan
14
+ unreliable and stood the unregistered-package pass down for that ref. `refs doctor` may therefore
15
+ name members on a ref that reported nothing for months. They are not new; they were invisible.
16
+ Register the ones worth routing to, and leave the rest.
17
+
18
+ ### Added
19
+
20
+ - **Every drift finding that has a repair now prints it as a command.** `unregistered` has printed
21
+ a runnable `refs edit --create` since the probe shipped; `missing` and `relocated` described the
22
+ repair in prose and left the reader to construct it. The asymmetry was not deliberate — one of
23
+ the two repairs did not exist as a command at all. `refs doctor` now ends those findings with
24
+ `refs edit --package='<name>' --remove '<ref>'` and
25
+ `refs edit --package='<name>' '<ref>' 'path' '<new>'`, quoted for a shell like every other
26
+ command refs prints. A new path the configuration could not hold is still reported, without a command
27
+ that would only fail validation.
28
+
29
+ Every printed `refs edit` now attaches its option values with `=` and, where a positional would
30
+ otherwise begin with `-`, ends the options with `--`. Quoting gets a value past the shell; refs'
31
+ own parser reads it next, and `refs edit '<ref>' path '-new/pkg'` — a path `zPackagePath` accepts
32
+ — arrived correctly quoted and exited `2` with `unknown option '-new/pkg'`. The terminator is
33
+ printed only where it is needed, so appending `--json` to an ordinary printed line still works.
34
+
35
+ - **`refs edit <ref> --package <name> --remove` unregisters a package.** The counterpart to
36
+ `--create`, and the repair the `missing` finding needed: a package that left a repository's
37
+ workspaces leaves an entry behind that `refs resolve` keeps answering with, pointing at a path no
38
+ checkout has. The only instruction refs could give was to hand-edit `config.toml`. Removal
39
+ touches configuration alone and never consults a checkout — it has to work while the checkout is
40
+ stale, absent, or still carrying the directory. Removing the last entry drops the `packages`
41
+ table rather than leaving an empty one, which `add` and the drift probe read differently.
42
+
43
+ ### Fixed
44
+
45
+ - **A workspace pattern whose wildcard is not in its last segment is expanded.** `crates/*/js` —
46
+ the spelling a Rust/JS monorepo uses — was reported as `unsupported_pattern` and every package
47
+ beneath it went undetected. That pattern costs one `readdir` and a literal probe per child, the
48
+ same shape `packages/*` has, so the budget that refused it was measuring the wrong thing. Two
49
+ wildcards still mean two levels and `packages/*/nested/*` is still refused. Measured on a
50
+ repository declaring `crates/*/js` and `turbopack/crates/*/js`: 41 packages detected instead of
51
+ 37, with no diagnostics; three other monorepos detect exactly what they did before.
52
+
53
+ - **`tag_format` is detected from every tag, not from the top twenty of a refname sort.** Detection
54
+ counted formats among the first 20 tags of `git tag --sort=-version:refname`. That sort is
55
+ version-aware over the whole refname, so in a monorepo that tags per package it groups by prefix:
56
+ those twenty are one package's tags, not a sample of the repository's. Measured against two real
57
+ repositories, `refs add` proposed `create-astro@{version}` for a repository with 839
58
+ `astro@{version}` tags, and `keystatic@{version}` — a package whose last tag is `0.0.36` and whose
59
+ directory no longer exists — for one where `@keystatic/core@{version}` is the live package with 183 of
60
+ them. Both now resolve correctly, and the two repositories whose detection was already right are
61
+ unchanged.
62
+
63
+ A tag list that could not be read whole now yields no candidate at all rather than one derived
64
+ from whatever survived. `git tag` output is capped at the subprocess stream limit, and the note
65
+ saying so was written to stderr and never read — which did not matter while only twenty lines
66
+ were needed, and does once the count is a claim about all of them.
67
+
68
+ What this establishes is historical plurality, not which package is primary or still alive: a
69
+ retired package with a thousand tags still outvotes its replacement's hundred. The two-phase flow
70
+ shows the candidate for exactly that reason.
71
+
8
72
  ## [0.13.0] - 2026-09-12
9
73
 
10
74
  ### Upgrading
package/dist/refs.mjs CHANGED
@@ -322,10 +322,10 @@ sync_ttl = "1h"
322
322
  `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),pu=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:ru(t)&&ru(r)&&(n[e]=pu(t,r))}return n},mu={meta:{},refs:{},settings:{}},hu=async e=>{try{return await au(e)}catch(e){if(e instanceof _&&e.code===`not_found`)return;throw e}},gu=e=>{if(e!==void 0&&e>1)throw b(`config schema ${e} is newer than this CLI supports — upgrade refs`)},_u=async(e,t,n)=>{let r=iu(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await Zl(e.configPath,Xl(i))},vu=async(e,t,n)=>{await r(e.configPath,Ql(e));let i=pu(t,mu),a=iu(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=vl.safeParse(o);if(!s.success)throw b(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${Ql(e)}): ${E(s.error)}`);await Zl(e.configPath,Xl(o))},yu=async(e,t,n)=>{let r=ou(t,e.configPath),i=cu(r);return gu(i),i===1?(await _u(e,r,n),`noop`):(await vu(e,r,n),`migrated`)},bu=async(e,t)=>{let n=await hu(e);return n===void 0?(await fu(e,t),`seeded`):yu(e,n,t)},xu=new Set([`ENOENT`,`ENOTDIR`]),Su=e=>e.code??String(e),Cu=async e=>{try{return await i(e),!0}catch{return!1}},wu=(e,t)=>{let n=se(e,t);return n===``||n!==`..`&&!n.startsWith(`..`+le)&&!ae(n)},Tu=async e=>{try{return{real:await l(e)}}catch(e){return{code:Su(e)}}},Eu=async(e,t)=>{let n=await Tu(e);if(`code`in n)return{code:n.code,kind:`unreadable`};let r=await Tu(t);return`code`in r?xu.has(r.code)?await Cu(t)?{code:r.code,kind:`unreadable`}:{kind:`missing`}:{code:r.code,kind:`unreadable`}:wu(n.real,r.real)?{kind:`inside`,real:r.real}:{kind:`outside`}},Du=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,Ou=/^packages:\s*(?:#.*)?$/u,ku=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Au=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!ku(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},ju=Symbol(`end-of-section`),Mu=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!Ou.test(e))return ju;if(!t.startsWith(`-`))return;let n=Du.exec(e)?.groups?.pattern?.trim();if(n)return n},Nu=e=>{let t=[];for(let n of e){let e=Mu(n);if(e===ju)break;e!==void 0&&t.push(e)}return t},Pu=e=>{let t=e.findIndex(e=>Ou.test(e));return t===-1?[]:Nu(e.slice(t+1))},Fu=e=>{let{name:t}=e;if(typeof t==`string`)return t},Iu=async(e,t)=>{let n=await Eu(e,t);if(n.kind===`missing`)return{ok:!0};if(n.kind!==`inside`)return{ok:!1};try{return{content:await s(n.real,`utf8`),ok:!0}}catch{return{ok:!1}}},Lu=async(e,t)=>{let n=await Iu(e,t);return n.ok?n.content===void 0?{ok:!0,patterns:[]}:Ru(n.content):{ok:!1,patterns:[]}},Ru=e=>{try{let t=JSON.parse(e);return{ok:!0,patterns:Au(t.workspaces)}}catch{return{ok:!1,patterns:[]}}},zu=/^packages:/mu,Bu=(e,t)=>t.length===0&&zu.test(e),Vu=async(e,t)=>{let n=await Iu(e,t);if(!n.ok)return{ok:!1,patterns:[]};if(n.content===void 0)return{ok:!0,patterns:[]};let r=Pu(n.content.split(`
323
323
  `));return{ok:!0,patterns:r,unparsed:Bu(n.content,r)}},Hu=async e=>{let[t,n]=await Promise.all([Lu(e,m(e,`package.json`)),Vu(e,m(e,`pnpm-workspace.yaml`))]),r=[];return t.ok||r.push({file:`package.json`,kind:`workspace_file_unreadable`}),n.ok||r.push({file:`pnpm-workspace.yaml`,kind:`workspace_file_unreadable`}),n.unparsed===!0&&r.push({file:`pnpm-workspace.yaml`,kind:`workspace_declaration_unparsed`}),{diagnostics:r,npm:t.patterns,pnpm:n.patterns}},Uu=`\0unreadable`,Wu=`pnpm-workspace.yaml`,Gu=async(e,t)=>{let n=await e.run(`git`,[`ls-tree`,`-z`,`--name-only`,t.rev,`--`,t.path],{cwd:t.dir});return n.exitCode===0?n.stdout.includes(t.path):void 0},Ku=async(e,t)=>{let n=await Gu(e,t);if(n===void 0)return{kind:`unreadable`};if(!n)return{kind:`absent`};let r=await e.run(`git`,[`show`,`${t.rev}:${t.path}`],{cwd:t.dir});return r.exitCode===0?{contents:r.stdout}:{kind:`unreadable`}},qu=async(e,t,n)=>{let r=await Ku(e,{dir:t.dir,path:`package.json`,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[Uu];try{let e=JSON.parse(r.contents);return Au(e.workspaces)}catch{return[Uu]}},Ju=async(e,t,n)=>{let r=await Ku(e,{dir:t.dir,path:Wu,rev:n});if(`kind`in r)return r.kind===`absent`?[]:[Uu];let{contents:i}=r,a=Pu(i.split(`
324
324
  `));return Bu(i,a)?[Uu]:a},Yu=async(e,t,n)=>{let[r,i]=await Promise.all([qu(e,t,n),Ju(e,t,n)]);return{npm:r,pnpm:i}},Xu=(e,t)=>{let n=0;for(let r of t)if(n<e.length&&e[n]===r)n+=1;else if(r.startsWith(`!`))return!1;return n===e.length},Zu=async(e,t)=>{if(!t.touched)return!1;let[n,r]=await Promise.all([Yu(e,t,t.from),Yu(e,t,t.to)]);return!Xu(n.npm,r.npm)||!Xu(n.pnpm,r.pnpm)},Qu=e=>re(e)===`package.json`,$u=async(e,t,n)=>{let r=await e.run(`git`,[...n],{cwd:t});return r.exitCode===0?r.stdout:void 0},ed=e=>e.split(`\0`).filter(e=>e.length>0&&Qu(e)),td=async(e,t)=>{let n=await $u(e,t.dir,[`diff`,`--name-only`,`-z`,`--no-renames`,`${t.from}..${t.to}`,`--`,`*package.json`,Wu]);return n===void 0?void 0:n.split(`\0`).filter(e=>e.length>0)},nd=async(e,t)=>{if(t.paths.length===0)return new Set;let n=await $u(e,t.dir,[`ls-tree`,`-r`,`-z`,`--name-only`,t.rev,`--`,...t.paths]);return n===void 0?void 0:new Set(ed(n))},rd=async(e,t)=>{let n=await $u(e,t.dir,[`show`,`${t.rev}:${t.path}`]);if(n!==void 0)try{let e=JSON.parse(n);return{name:Fu(e)}}catch{return}},id=async(e,t,n)=>{let r=[];for(let i of n){let n=await rd(e,{dir:t.dir,path:i,rev:t.rev});if(n===void 0)return;n.name!==void 0&&r.push(n.name)}return r},ad={changedDirs:[],namesBefore:[]},od=(e,t,n)=>Zu(e,{...t,touched:n.some(e=>e===`pnpm-workspace.yaml`||e===`package.json`)}),sd=e=>[...new Set(e.map(e=>ie(e)))].filter(e=>e!==`.`).toSorted(),cd=async(e,t,n)=>{let r=await nd(e,{dir:t.dir,paths:n,rev:t.from});if(r!==void 0)return id(e,{dir:t.dir,rev:t.from},n.filter(e=>r.has(e)))},ld=async(e,t)=>{if(t.from===t.to)return ad;let n=await td(e,t);if(n===void 0||await od(e,t,n))return;let r=n.filter(e=>Qu(e));if(r.length>200)return;let i=await cd(e,t,r);return i===void 0?void 0:{changedDirs:sd(r),namesBefore:i}},ud=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
325
- `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},dd=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,fd=(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(` | `)},pd=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:dd(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=fd(n,r);return o!==void 0&&(a.warning=o),a},md=(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},U=e=>pe(m(e,`.git`)),hd=e=>`refusing to sync ${e}: not a refs-managed checkout`,gd=async(e,t)=>{if(!U(t))throw b(hd(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw b(hd(t))},_d=/filtering not recognized/iu,vd=e=>e===void 0?{}:{cwd:e},yd=(e,t,n)=>({action:e,args:t,cmd:`git`,...vd(n)}),bd=async(e,t)=>{let n=await e.run(t.cmd,t.args,vd(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}`)},xd=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await bd(e,yd(`git clone`,n));return await bd(e,yd(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&_d.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}},Sd=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},Cd=async(e,t)=>{let n=await Sd(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await Sd(e,t);if(r!==void 0)return r;throw b(`could not detect the default branch for checkout: ${t}`)},wd=async(e,t)=>(await bd(e,yd(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),Td=async(e,t)=>(await bd(e,yd(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Ed=async(e,t)=>{await bd(e,yd(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await Cd(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${ud(n)}`),i},Dd=e=>[yd(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),yd(`git clean -fd`,[`clean`,`-fd`],e)],Od=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Dd(r)),a.push(yd(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),yd(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await bd(e,t)},kd=async(e,t)=>{await gd(e,t.dir);let n=await wd(e,t.dir),r=await Ed(e,t),i=await Td(e,t.dir);await Od(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await wd(e,t.dir);return pd(md(r,i,{newSha:a,oldSha:n}))},Ad=async(e,t,n=20)=>(await bd(e,yd(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
326
- `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),jd=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,Md=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
327
- `),Nd=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await Zl(r,Md),await t(r,493)}))},Pd=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Fd=/\d+\.\d+\.\d+/gu,Id=e=>cl.safeParse(e).success,Ld=e=>{let t=e.match(Fd);return t!==null&&t.length>1},Rd=e=>{let t=Pd.exec(e);if(!t||Ld(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Id(r))return r},zd=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},Bd=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Rd(r);e&&zd(t,e,n)}return t},Vd=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Hd=e=>{let t=[...e.entries()],[n]=t;if(n===void 0)return null;let[r,i]=n;return t.slice(1).reduce(({format:e,data:t},[n,r])=>Vd(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Ud=e=>{let t=Bd(e);return Hd(t)},Wd=(e,t)=>e.replaceAll(`{version}`,()=>t),Gd=async(e,t,n,r)=>{let i=Wd(n,r);if(!await jd(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Kd=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,W=e=>{let t=e.replace(Kd,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},qd=/\.git$/u,Jd=e=>e.replace(qd,``),Yd=e=>{let t=0,n=e.length;for(;t<n&&e.charAt(t)===`/`;)t+=1;for(;n>t&&e.charAt(n-1)===`/`;)--n;return e.slice(t,n)},Xd=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,Zd=/^git\+/u,Qd={"https:":`443`,"ssh:":`22`},$d=e=>e.split(`/`).some(e=>e===`.`||e===`..`),ef=e=>e.includes(`\\`),tf=e=>e.includes(`%`),nf=e=>{let t=rl.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${W(e)}' is invalid`);return t.data},rf=({host:e,port:t,protocol:n})=>{let r=Qd[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},af=e=>{let t=Jd(Yd(e.path));return nf(`${rf(e)}/${t}`)},of=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 nf(`local/${n}/${r}`)},sf=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${W(t)}`)}},cf=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`)},lf=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return of(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return cf(e),af({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},uf=(e,t)=>{if(tf(e))throw b(`not a supported git url: percent-encoding not supported in ${W(t)}`);if(e.includes(`:`))throw b(`not a supported git url: ambiguous ':' in scp-style path ${W(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 ${W(t)}; use the ssh:// url form instead`)},df=(e,t)=>{let n=e.groups?.path??``;return uf(n,t),af({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},ff=(e,t)=>{if(ef(e))throw b(`not a supported git url: backslash not allowed in ${W(t)}`)},pf=(e,t)=>{if($d(e))throw b(`not a supported git url: path traversal segment in ${W(t)}`)},mf=(e,t,n)=>{if(e.protocol!==`file:`&&tf(t))throw b(`not a supported git url: percent-encoding not supported in ${W(n)}`)},hf=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(Zd,``);ff(r,e),pf(r,e);let i=Xd.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:df(i,e)};let a=sf(r,e);return mf(a,r,e),{cloneUrl:r,key:lf(a,n)}},gf=`.git`,_f=e=>e.endsWith(gf)?e:`${e}${gf}`,vf=(e,t)=>`https://${e.toLowerCase()}/${Yd(t)}`,yf=(e,t)=>`git@${e.toLowerCase()}:${_f(Yd(t))}`,bf=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},xf=(e,t,n)=>{let r=Qd[e.protocol];if(e.port!==``&&e.port!==r)throw b(`cannot apply git_transport=${t} to ${W(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},Sf=(e,t)=>t===`https`?vf(e.hostname,e.pathname):yf(e.hostname,e.pathname),Cf=(e,t,n)=>{let r=hf(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${W(e)}' → '${t}' (key '${n}' → '${r}')`);return t},wf=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Cf(t.cloneUrl,vf(n,r),t.originalKey)},Tf=e=>{let t=sf(e.cloneUrl,e.cloneUrl);return bf(t.protocol)===e.transport?e.cloneUrl:(xf(t,e.transport,e.cloneUrl),Cf(e.cloneUrl,Sf(t,e.transport),e.originalKey))},Ef=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:hf(e).key,transport:t},r=Xd.exec(e);return r?.groups===void 0?Tf(n):wf(r,n)},Df=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,Of=(e,t)=>{if(Df.test(t))return m(e,`lease-${t}`)},kf=async(e,t)=>{let n=Of(e,t);n!==void 0&&await(await o(n,`w`)).close()},Af=async(e,t)=>{let n=Of(e,t);if(n===void 0)return`gone`;let r=new Date;try{await ee(n,r,r)}catch(e){if(z(e))return`gone`;throw e}return`renewed`},jf=async(e,t)=>{let n=Of(e,t);if(n===void 0)return{state:`absent`};try{return{mtimeMs:(await p(n)).mtimeMs,state:`ok`}}catch(e){return{state:z(e)?`absent`:`unreadable`}}},Mf=`meta.json`,Nf=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},Pf=e=>{try{return process.kill(e,0),!0}catch(e){return Nf(e)!==`ESRCH`}},Ff=e=>{try{return JSON.parse(e)}catch{return}},If=async e=>{try{return await s(e,`utf8`)}catch{return}},Lf=new Set([`ENOENT`,`ENOTDIR`]),Rf=async e=>{try{return{state:`read`,text:await s(e,`utf8`)}}catch(e){let t=Nf(e);return{state:t!==void 0&&Lf.has(t)?`missing`:`unreadable`}}},zf=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Bf=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Vf=e=>{if(!(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>2147483647))return e},Hf=e=>{if(typeof e!=`object`||!e)return;let t=e,n=Vf(t.pid),r=zf(t.acquired_at);if(n===void 0||r===void 0)return;let i=Bf(e);return{acquiredAtMs:r,pid:n,...i===void 0?{}:{token:i}}},Uf=async e=>{let t=await If(m(e,Mf));if(t!==void 0)return Bf(Ff(t))},Wf=async e=>{let t=await Rf(m(e,Mf));if(t.state!==`read`)return{state:t.state};let n=Hf(Ff(t.text));return n===void 0?{state:`malformed`}:{meta:n,state:`valid`}},Gf=async e=>{try{return{mtimeMs:(await p(e)).mtimeMs,state:`ok`}}catch(e){return{state:Nf(e)===`ENOENT`?`gone`:`unreadable`}}},Kf=async(e,t)=>{let n=m(e,Mf),r=`${n}.tmp-${de()}`;await te(r,t,`utf8`),await u(r,n)},qf=()=>de(),Jf=async(e,t)=>{await kf(e,t),await Kf(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Yf=5e3,Xf=async(e,t,n)=>{if(t===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let r=await Gf(e);if(r.state===`gone`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`none`,stale:!1};if(r.state===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let i=n-r.mtimeMs;return{ageMs:i,budgetMs:Yf,meta:t,observedAtMs:n,pidState:`unknown`,policy:`grace`,stale:i>Yf}},Zf=async(e,t,n)=>{let r=t.token===void 0?{state:`absent`}:await jf(e,t.token);return r.state===`unreadable`?{policy:`unknown`}:r.state===`absent`?{ageMs:n-t.acquiredAtMs,budgetMs:6e5,policy:`legacy`}:{ageMs:n-r.mtimeMs,budgetMs:12e4,policy:`lease`}},Qf=async(e,t)=>{let n=await Wf(e);if(n.state!==`valid`)return Xf(e,n.state,t);let{meta:r}=n,i=await Zf(e,r,t),a=!Pf(r.pid),o=i.ageMs!==void 0&&i.budgetMs!==void 0&&i.ageMs>i.budgetMs;return{...i,meta:`valid`,observedAtMs:t,pid:r.pid,pidState:a?`definitely-dead`:`present-or-unknown`,stale:a||o,...r.token===void 0?{}:{token:r.token}}},$f=e=>e.meta===`valid`&&e.pidState===`definitely-dead`&&e.token!==void 0,ep=async(e,t)=>await Uf(e)===t?await Af(e,t)===`gone`?`lost`:`renewed`:`lost`,tp=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),np=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),rp=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Nf(e);if(t!==void 0&&tp.has(t))return!1;throw e}},ip=async(e,t)=>{try{return await u(e,t),!0}catch(e){let t=Nf(e);if(t!==void 0&&np.has(t))return!1;throw e}},ap=`.claims`,op=`.tombstones`,sp=(e,t)=>({lockPath:m(e,t),locksDir:e,name:t}),cp=e=>m(e.locksDir,ap,e.name),lp=e=>m(e.locksDir,op,de()),up=async e=>{await a(m(e,ap),{recursive:!0}),await a(m(e,op),{recursive:!0})},dp=e=>rp(e),fp=async e=>{try{await f(e)}catch{}},pp=async e=>{let t=lp(e);return await ip(e.lockPath,t)?t:void 0},mp=async e=>{let t=await Qf(e.lockPath,Date.now());if(!$f(t)||await Uf(e.lockPath)!==t.token)return!1;let n=await pp(e);return n!==void 0&&(await d(n,{force:!0,recursive:!0}),!0)},hp=async e=>{await up(e.locksDir);let t=cp(e);if(!await dp(t))return!1;let n=await mp(e).then(e=>({ok:!0,stolen:e}),e=>({error:e,ok:!1}));if(await fp(t),!n.ok)throw n.error;return n.stolen},gp=async e=>{try{return(await c(e,{withFileTypes:!0})).map(e=>({isDir:e.isDirectory(),name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}catch(e){if(z(e))return[];throw e}},_p=async e=>(await gp(e)).filter(e=>!e.name.startsWith(`.`)),vp=async(e,t,n)=>{let r=await Qf(m(e,t.name),n);if(r.policy!==`none`)return{diagnosis:r,isDirectory:t.isDir,kind:`lock`,name:t.name}},yp=async(e,t)=>{let n=m(e,ap),r=await gp(n);return(await Promise.all(r.map(async e=>({diagnosis:await Qf(m(n,e.name),t),isDirectory:e.isDir,kind:`claim`,name:e.name})))).filter(e=>e.diagnosis.policy!==`none`)},bp=async e=>{let t=Date.now(),n=await _p(e.locksDir),[r,i]=await Promise.all([Promise.all(n.map(n=>vp(e.locksDir,n,t))),yp(e.locksDir,t)]);return[...r.filter(e=>e!==void 0),...i]},xp=e=>{let t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),i=r%60,a=Math.floor(r/60);return a>0?i===0?`${a}h`:`${a}h ${i}m`:r>0?n===0?`${r}m`:`${r}m ${n}s`:`${n}s`},Sp=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} is present (identity not verified)`,Cp={grace:`created`,lease:`lease renewed`,legacy:`acquired`,none:`observed`,unknown:`observed`},wp={grace:`from creation, while its metadata has not been published`,lease:`from the last renewal`,legacy:`from acquisition (no renewable lease)`,none:``,unknown:``},Tp=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return t===void 0||n===void 0?``:t<0?`, but its recorded time is in the future — check the system clock`:`, ${Cp[r]} ${xp(t)} ago; its window is ${xp(n)} ${wp[r]}`},Ep=(e,t)=>{if(t.policy===`none`)return`lock ${e} could not be acquired before the timeout, but it was released while the failure was being diagnosed. Retry the operation.`;let n=`lock ${e} is held: ${Sp(t)}`;return $f(t)?`${n}, and refs is entitled to reclaim it — it could not do so before the timeout. Retry; if it persists, run refs doctor.`:t.stale?`${n}${Tp(t)}. refs does not reclaim this automatically: only a recorded process the operating system reports as gone is reclaimed, and this one is not. Run refs doctor for what to do about it.`:`${n}${Tp(t)}. Retry once the other refs command finishes.`},Dp=(e,t)=>{if(t.stopped)return;let n=setTimeout(()=>{t.stopped||(t.inFlight=Op(e,t))},e.intervalMs);n.unref(),t.timer=n},Op=async(e,t)=>{try{if(await e.renew()===`lost`){t.lost=!0,t.stopped=!0;return}}catch{}Dp(e,t)},kp=e=>{let t={inFlight:Promise.resolve(),lost:!1,stopped:!1};return Dp(e,t),{ownershipLost:()=>t.lost,stop:async()=>{t.stopped=!0,t.timer!==void 0&&clearTimeout(t.timer),await t.inFlight}}},Ap=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,jp=async(e,t)=>{try{await Jf(e,t)}catch(e){if(Nf(e)===`ENOENT`)return`retry`;throw e}return t},Mp=async(e,t)=>{if(!await rp(e))return;let n=await jp(e,qf());return n===`retry`?Date.now()>=t?void 0:Mp(e,t):n},Np=async(e,t)=>{if(!await hp(e)){if(Date.now()>=t){let t=await Qf(e.lockPath,Date.now());throw Se(Ep(e.name,t))}await ge(100)}},Pp=async(e,t)=>{let n=await Mp(e.lockPath,t);return n===void 0?(await Np(e,t),Pp(e,t)):n},Fp=async(e,t)=>await Uf(e)===t&&(await d(e,{force:!0,recursive:!0}),!0),Ip=async e=>{try{return{ok:!0,value:await e()}}catch(e){return{error:e,ok:!1}}},Lp=async(e,t,n,r)=>{await n.stop();let i=await Ip(()=>Fp(e.lockPath,t));if(!r.ok)throw r.error;if(!i.ok)throw i.error;if(n.ownershipLost()||!i.value)throw Se(`lock ${e.name} was lost while the operation was running`);return r.value},Rp=e=>e!==`.`&&e!==`..`&&Ap.test(e),zp=e=>{if(!Rp(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}`)},G=async(e,t,n,r)=>{zp(t);let i=sp(e.locksDir,t);await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await Pp(i,o),c=kp({intervalMs:3e4,renew:()=>ep(i.lockPath,s)});return Lp(i,s,c,await Ip(n))},Bp=oc({directory:F().optional(),url:F().optional()}),Vp=oc({repository:cc([F(),Bp]).optional()}),Hp=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,Up=new Set([`node_modules`,`favicon.ico`]),Wp=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),Gp=e=>{let[t,n]=e.split(`/`);return n??t??e},Kp=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!Hp.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=Gp(e);if(Up.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},qp=e=>e.replaceAll(`/`,`%2F`),Jp=e=>typeof e==`string`?e:e?.url,Yp=e=>{if(typeof e==`object`&&e?.directory){let t=ll.safeParse(e.directory);if(t.success)return t.data}},Xp=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},Zp=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${qp(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 Xp(n,t),i=Vp.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},Qp=(e,t)=>{try{return hf(e)}catch{throw Wp(t)}},$p=async(e,t)=>{Kp(t);let n=await Zp(e,t),r=Jp(n.repository);if(r===void 0||r===``)throw Wp(t);let{cloneUrl:i,key:a}=Qp(r,t),o=Yp(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},em=(e,t,n)=>{let r=e instanceof RegExp?tm(e,n):e,i=t instanceof RegExp?tm(t,n):t,a=r!==null&&i!=null&&nm(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},tm=(e,t)=>{let n=t.match(e);return n?n[0]:null},nm=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},rm=`\0SLASH`+Math.random()+`\0`,im=`\0OPEN`+Math.random()+`\0`,am=`\0CLOSE`+Math.random()+`\0`,om=`\0COMMA`+Math.random()+`\0`,sm=`\0PERIOD`+Math.random()+`\0`,cm=new RegExp(rm,`g`),lm=new RegExp(im,`g`),um=new RegExp(am,`g`),dm=new RegExp(om,`g`),fm=new RegExp(sm,`g`),pm=/\\\\/g,mm=/\\{/g,hm=/\\}/g,gm=/\\,/g,_m=/\\\./g;function vm(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function ym(e){return e.replace(pm,rm).replace(mm,im).replace(hm,am).replace(gm,om).replace(_m,sm)}function bm(e){return e.replace(cm,`\\`).replace(lm,`{`).replace(um,`}`).replace(dm,`,`).replace(fm,`.`)}function xm(e){if(!e)return[``];let t=[],n=em(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=xm(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Sm(e,t={}){if(!e)return[];let{max:n=1e5,maxLength:r=4e6}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),km(ym(e),n,r,!0).map(bm)}function Cm(e){return`{`+e+`}`}function wm(e){return/^-?0\d/.test(e)}function Tm(e,t){return e<=t}function Em(e,t){return e>=t}function Dm(e,t,n,r,i,a){let o=[],s=0;for(let c=0;c<e.length;c++)for(let l=0;l<n.length;l++){if(o.length>=r)return o;let u=e[c]+t+n[l];if(!a||u){if(s+u.length>i)return o;o.push(u),s+=u.length}}return o}function Om(e,t,n,r){let i=e.split(/\.\./),a=[];if(i[0]===void 0||i[1]===void 0)return a;let o=vm(i[0]),s=vm(i[1]),c=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(vm(i[2])),1):1,u=Tm;s<o&&(l*=-1,u=Em);let d=i.some(wm),f=0;for(let e=o;u(e,s)&&a.length<n;e+=l){let n;if(t)n=String.fromCharCode(e),n===`\\`&&(n=``);else if(n=String(e),d){let t=c-n.length;if(t>0){let r=Array(t+1).join(`0`);n=e<0?`-`+r+n.slice(1):r+n}}if(f+n.length>r)break;a.push(n),f+=n.length}return a}function km(e,t,n,r){let i=[``],a=!1,o=!0;for(;;){let s=em(`{`,`}`,e);if(!s)return Dm(i,e,[``],t,n,a);let c=s.pre;if(/\$$/.test(c)){if(i=Dm(i,c+`{`+s.body+`}`,[``],t,n,a&&!s.post.length),o=!1,!s.post.length)break;e=s.post;continue}let l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),d=l||u,f=s.body.indexOf(`,`)>=0;if(!d&&!f){if(s.post.match(/,(?!,).*\}/)){e=s.pre+`{`+s.body+am+s.post,r=!0;continue}return Dm(i,c+`{`+s.body+`}`+s.post,[``],t,n,a)}o&&=(a=r&&!d,!1);let p;if(d)p=Om(s.body,u,t,n);else{let r=xm(s.body);if(r.length===1&&r[0]!==void 0&&(r=km(r[0],t,n,!1).map(Cm),r.length===1)){if(i=Dm(i,c+r[0],[``],t,n,a&&!s.post.length),!s.post.length)break;e=s.post;continue}let o=a&&!s.post.length&&!c;for(let e=0;o&&e<i.length;e++)i[e]&&(o=!1);p=[];let l=0;outer:for(let e=0;e<r.length;e++){let i=km(r[e],t,n,!1);for(let e=0;e<i.length;e++){let r=i[e];if(!o||r){if(p.length>=t||l+r.length>n)break outer;p.push(r),l+=r.length}}}}if(i=Dm(i,c,p,t,n,a&&!s.post.length),!s.post.length)break;e=s.post}return i}const Am=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},jm={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},Mm=e=>e.replace(/[[\]\\-]/g,`\\$&`),Nm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Pm=e=>e.join(``),Fm=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(jm))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(Mm(d)+`-`+Mm(t)):t===d&&r.push(Mm(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(Mm(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(Mm(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let e=r[0].length===2?r[0].slice(-1):r[0];return[Nm(e),!1,u-n,!1]}let f=`[`+(l?`^`:``)+Pm(r)+`]`,p=`[`+(l?``:`^`)+Pm(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},Im=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var K;const Lm=new Set([`!`,`?`,`+`,`*`,`@`]),Rm=e=>Lm.has(e),zm=e=>Rm(e.type),Bm=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Vm=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Hm=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),Um=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Wm=`(?!\\.)`,Gm=new Set([`[`,`.`]),Km=new Set([`..`,`.`]),qm=new Set(`().*{}+?[]^$\\!`),Jm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Ym=`[^/]+?`;let Xm=0;var Zm=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++Xm;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.#l=this.type?this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof K&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof K&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new K(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&Rm(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new K(n,t);u=K.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new K(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&Rm(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new K(n,d);d.push(o),u=K.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new K(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,Vm)}#m(e,t=Bm){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=Hm){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new K(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!Um.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=Um.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new K(null,void 0,t);return K.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!zm(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?K.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Km.has(this.#r[0]))){let n=Gm,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Wm:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,Im(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,Im(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Wm:``)+Ym;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Wm:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,Im(i),this.#t=!!this.#t,this.#n]}#x(){if(zm(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(qm.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?Ym:`[^/]*?`,t=!0;continue}if(o=!1,c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=Fm(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=`[^/]`,t=!0;continue}i+=Jm(c)}return[i,Im(e),!!t,a]}};K=Zm;const Qm=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),q=(e,t,n={})=>(Am(t),!n.nocomment&&t.charAt(0)===`#`?!1:new wh(t,n).match(e)),$m=/^\*+([^+@!?*[(]*)$/,eh=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),th=e=>t=>t.endsWith(e),nh=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),rh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ih=/^\*+\.\*+$/,ah=e=>!e.startsWith(`.`)&&e.includes(`.`),oh=e=>e!==`.`&&e!==`..`&&e.includes(`.`),sh=/^\.\*+$/,ch=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),lh=/^\*+$/,uh=e=>e.length!==0&&!e.startsWith(`.`),dh=e=>e.length!==0&&e!==`.`&&e!==`..`,fh=/^\?+([^+@!?*[(]*)?$/,ph=([e,t=``])=>{let n=_h([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},mh=([e,t=``])=>{let n=vh([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},hh=([e,t=``])=>{let n=vh([e]);return t?e=>n(e)&&e.endsWith(t):n},gh=([e,t=``])=>{let n=_h([e]);return t?e=>n(e)&&e.endsWith(t):n},_h=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},vh=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},yh=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,bh={win32:{sep:`\\`},posix:{sep:`/`}};q.sep=yh===`win32`?bh.win32.sep:bh.posix.sep;const J=Symbol(`globstar **`);q.GLOBSTAR=J,q.filter=(e,t={})=>n=>q(n,e,t);const Y=(e,t={})=>Object.assign({},e,t);q.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return q;let t=q;return Object.assign((n,r,i={})=>t(n,r,Y(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,Y(e,n))}static defaults(n){return t.defaults(Y(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,Y(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,Y(e,r))}},unescape:(n,r={})=>t.unescape(n,Y(e,r)),escape:(n,r={})=>t.escape(n,Y(e,r)),filter:(n,r={})=>t.filter(n,Y(e,r)),defaults:n=>t.defaults(Y(e,n)),makeRe:(n,r={})=>t.makeRe(n,Y(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,Y(e,r)),match:(n,r,i={})=>t.match(n,r,Y(e,i)),sep:t.sep,GLOBSTAR:J})};const xh=(e,t={})=>(Am(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Sm(e,{max:t.braceExpandMax}));q.braceExpand=xh,q.makeRe=(e,t={})=>new wh(e,t).makeRe(),q.match=(e,t,n={})=>{let r=new wh(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const Sh=/[?*]|[+@!]\(.*?\)|\[|\]/,Ch=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var wh=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){Am(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||yh,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!Sh.test(e[2]))&&!Sh.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t of e)for(let e=0;e<t.length;e++)t[e]===`**`&&(t[e]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];(n!==1||r!==``||e[0]!==``)&&(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&!(this.isWindows&&/^[a-z]:$/i.test(r))&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];(e!==1||r!==``||n[0]!==``)&&(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(J)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(J,i),o=t.lastIndexOf(J),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,ee=[0];for(let e of c)e===J?(ee.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let te=d.length-1,ne=e.length-u;for(let e of d)e[1]=ne-(ee[te--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===J)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return xh(this.pattern,this.options)}parse(e){Am(e);let t=this.options;if(e===`**`)return J;if(e===``)return``;let n,r=null;(n=e.match(lh))?r=t.dot?dh:uh:(n=e.match($m))?r=(t.nocase?t.dot?rh:nh:t.dot?th:eh)(n[1]):(n=e.match(fh))?r=(t.nocase?t.dot?mh:ph:t.dot?hh:gh)(n):(n=e.match(ih))?r=t.dot?oh:ah:(n=e.match(sh))&&(r=ch);let i=Zm.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?Ch(e):e===J?J:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e===J&&a!==J&&(a===void 0?i!==void 0&&i!==J?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==J&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=J))});let i=t.filter(e=>e!==J);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return q.defaults(e).Minimatch}};q.AST=Zm,q.Minimatch=wh,q.escape=Qm,q.unescape=Im;const Th=/[/\\]/u,Eh={kind:`ignore`},Dh=e=>!ae(e)&&e.split(Th).every(e=>e!==`.`&&e!==`..`),Oh=/^!+/u,kh=/^\.?\/+/u,Ah=e=>{let t=Oh.exec(e)?.[0]??``;return{body:e.slice(t.length).replace(kh,``),negated:t.length%2==1}},jh=e=>Ah(e).negated,Mh=e=>Ah(e).body,Nh=/[?[\]{}()]/u,Ph=e=>Dh(e)&&!jh(e)&&!e.includes(`**`)&&!Nh.test(e)&&(e.match(/\*/gu)??[]).length<=1,Fh=(e,t)=>q(e,t),Ih=e=>{let t=e.lastIndexOf(`/`);return(t===-1?e:e.slice(t+1)).includes(`*`)?{baseDir:t===-1?`.`:e.slice(0,t),kind:`expand-children`,pattern:e}:Eh},Lh=e=>Ph(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`,pattern:e}:e===`*`?{baseDir:`.`,kind:`expand-children`,pattern:e}:e.includes(`*`)?Ih(e):{dir:e,kind:`probe-dir`,pattern:e}:Eh,Rh=e=>e.replaceAll(/\/+/gu,`/`).replace(/\/$/u,``),zh=new Set([`candidate_not_inspected`,`manifest_unreadable`,`unsupported_pattern`,`workspace_declaration_unparsed`,`workspace_dir_unreadable`,`workspace_file_unreadable`]),Bh=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>oe.join(e,t)),Vh=(e,t)=>t?.name?{name:t.name,path:e}:void 0,Hh=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},Uh=e=>!e.diagnostics.some(e=>zh.has(e.kind)),Wh=e=>!e.diagnostics.some(e=>e.kind===`no_workspace_declaration`),Gh=(e,t)=>e<t?-1:+(e>t),Kh=e=>`path`in e?`${e.kind} ${e.path}`:`file`in e?`${e.kind} ${e.file}`:`pattern`in e?`${e.kind} ${e.pattern}`:e.kind,qh=e=>e.toSorted((e,t)=>Gh(Kh(e),Kh(t))),Jh=e=>!ae(e)&&!e.split(/[/\\]/u).includes(`..`),Yh=(e,t)=>e.kind===`missing`?{kind:`absent`}:e.kind===`outside`?{kind:`unreadable`,reason:`${t} escapes the checkout`}:{kind:`unreadable`,reason:e.code},Xh=async(e,t,n)=>{if(!Jh(t))return{kind:`unreadable`,reason:`path escapes the checkout`};let r=await Zh(e,t);if(`probe`in r)return r.probe;let i=await Qh(r.real);return`reason`in i?{kind:`unreadable`,reason:i.reason}:i.found===n?{kind:`match`}:{found:i.found,kind:`mismatch`}},Zh=async(e,t)=>{let n=await Eu(e,m(e,t));if(n.kind!==`inside`)return{probe:Yh(n,`path`)};let r=await Eu(e,m(n.real,`package.json`));return r.kind===`inside`?{real:r.real}:{probe:Yh(r,`manifest`)}},Qh=async e=>{try{let t=JSON.parse(await s(e,`utf8`));return{found:Fu(t)}}catch(e){return{reason:e.code??String(e)}}},$h=(e,t)=>{let n=e.filter(e=>e.name===t).map(e=>e.path);return n.length===0?{kind:`absent`}:n.length===1?{kind:`found`,path:n[0]}:{kind:`ambiguous`,paths:n.toSorted(Gh)}},eg=new Set;let tg=!1;const ng=()=>{for(let e of eg)try{e.kill(`SIGKILL`)}catch{}},rg=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],ig=e=>{let t=()=>{ng(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},ag=()=>{tg||(tg=!0,rg.forEach(e=>{ig(e)}),process.on(`exit`,ng))},og=()=>{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}}},sg=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
328
- `),cg=(e,t,n)=>{let r=e;return t.truncated&&(r=sg(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=sg(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},lg={clear:()=>{},markedTimedOut:()=>!1},ug=(e,t)=>{if(t===void 0)return lg;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}},dg=e=>e===void 0?{}:{cwd:e},fg=(e,t)=>sg(e,`refs: command timed out after ${String(t)}ms`),pg=(e,t)=>({exitCode:124,stderr:fg(e,t),stdout:``,timedOut:!0}),mg=(e,t,n)=>{let r=be(e,t,{...dg(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});eg.add(r);let i=og(),a=og();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:ug(r,n?.timeoutMs)}},hg=(e,t,n)=>{try{return mg(e,t,n)}catch(e){return{exitCode:127,stderr:_g(e),stdout:``}}},gg=e=>!(`child`in e),_g=e=>e instanceof Error?e.message:String(e),vg=async e=>{try{let[t]=await ve(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:_g(e)}}},yg=e=>e===null?1:e,bg=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,xg=e=>e.timedOut?pg(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?bg({exitCode:yg(e.code),stderr:cg(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):bg({exitCode:127,stderr:sg(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Sg=class{async run(e,t,n){ag();let r=hg(e,t,n);if(gg(r))return r;let i=await vg(r.child);return eg.delete(r.child),r.timeout.clear(),xg({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Cg=pl.partial({description:!0}),wg=L({default_branch:F().min(1),key:rl,tag_format_candidate:cl.nullable(),url:F().min(1)});wg.extend({description:F().default(``),packages:Wc(Cg)});const Tg=wg.extend({description:F().min(1),packages:Wc(pl)}),Eg=L({effective_clone_mode:ol.optional(),head_sha:F().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:F().optional(),last_fetched_at:Bc().optional(),pending_proposal_at:Bc().optional()}),Dg=L({refs:Hc(e=>e.length>0&&!Vc.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,fc(F(),Eg)).default({})}),Og=(e,t,n)=>t?.[e]??n[e],kg=async e=>{try{return await s(e.statePath,`utf8`)}catch(e){if(z(e))return;throw e}},Ag=e=>{try{return JSON.parse(e)}catch{return}},jg=async e=>{let t=await kg(e);if(t===void 0)return Dg.parse({});let n=Ag(t);if(n===void 0)return Dg.parse({});let r=Dg.safeParse(n);return r.success?r.data:Dg.parse({})},Mg=async(e,t)=>{let n=Dg.safeParse(t);if(!n.success)throw b(E(n.error));await Zl(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Ng=/^\d+\.\d+\.\d+$/u,Pg=/^0+(?=\d)/u,Fg=(e,t)=>{let n=e.replace(Pg,``),r=t.replace(Pg,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},Ig=(e,t)=>{if(!Ng.test(e)||!Ng.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>Fg(e,r[t]??``)).find(e=>e!==0)??0},Lg=oc({version:F().regex(Ng)}),Rg=L({checked_at:Bc(),latest_version:F().regex(Ng)}),zg=async e=>{try{let t=Rg.safeParse(JSON.parse(await s(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},Bg=async(e,t)=>{try{await p(e.root),await Zl(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},Vg=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},Hg=async e=>{try{let t=await e(`https://registry.npmjs.org/@kaisers-io%2Frefs/latest`,{signal:AbortSignal.timeout(2e3)});if(t.status!==200)return;let n=Lg.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},Ug=async e=>{let t=await zg(e.home);if(t!==void 0&&Vg(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await Hg(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await Bg(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},Wg=(e,t)=>{let n=Ig(e,t);return n!==void 0&&n<0},Gg=(e,t)=>`refs ${t} is available (this is ${e}) — update: npm i -g @kaisers-io/refs@latest`,Kg=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},qg=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},Jg={check:!0,notify:!0},Yg=e=>{let t=Kg(e.env);return t===void 0?(e.updates??Jg).check?qg(e.env)?`ci`:`on`:`config`:t?`on`:`env`},Xg=e=>Yg(e)===`on`,Zg=e=>Xg(e)&&(e.updates??Jg).notify,Qg=async(e,t)=>{let n=await Eu(e,m(t,`package.json`));if(n.kind===`inside`)try{let e=JSON.parse(await s(n.real,`utf8`));return{name:Fu(e)}}catch{return}},$g=async(e,t)=>{let n=await Qg(e,m(e,t));if(n===void 0)return{diagnostic:{kind:`manifest_unreadable`,path:t}};let r=Vh(t,n);return r===void 0?{diagnostic:{kind:`manifest_missing_name`,path:t}}:{pkg:r}},e_=e=>{let t=[],n=[];for(let r of e)r.diagnostic!==void 0&&t.push(r.diagnostic),r.pkg!==void 0&&n.push(r.pkg);return{diagnostics:t,packages:n}},t_=new Set([`ENOENT`,`ENOTDIR`]),n_=async(e,t)=>{let n=await Eu(e,m(t,`package.json`));if(n.kind===`missing`)return`none`;if(n.kind!==`inside`)return`rejected`;try{return await s(n.real,`utf8`),`manifest`}catch{return`rejected`}},r_=async e=>{try{return{entries:await c(e,{withFileTypes:!0})}}catch(e){return{code:e.code??``}}},i_=(e,t,n)=>Promise.all(n.map(n=>n_(e,m(t,n.name)))),a_=(e,t,n)=>e.filter((e,r)=>n(t[r])).map(e=>e.name),o_=async e=>{let{baseDir:t,dirs:n,fullPath:r,repoDir:i,symlinks:a}=e,o=e=>oe.join(t===`.`?``:t,e),[s,c]=await Promise.all([i_(i,r,n),i_(i,r,a)]);return{diagnostics:[...a_(n,s,e=>e===`rejected`).map(e=>({kind:`manifest_unreadable`,path:o(e)})),...a_(a,c,e=>e!==`none`).map(e=>({kind:`candidate_not_inspected`,path:o(e)}))],dirs:Bh(t,n.map(e=>e.name),s.map(e=>e===`manifest`))}},s_=async e=>{let t=await $g(e,`.`);return`pkg`in t?[t]:[]},c_=e=>{let t=e.find(e=>e.path===`.`);return t===void 0?[...e]:e.some(e=>e.path!==`.`&&e.name===t.name)?e.filter(e=>e!==t):[...e]},l_=async e=>{let[t]=await s_(e);return t!==void 0&&`pkg`in t?t.pkg:void 0},u_=(e,t)=>Fh(oe.join(t.baseDir===`.`?``:t.baseDir,e.name),t.pattern),d_=async(e,t)=>{let n=m(e,t),r=await Eu(e,n);if(r.kind===`missing`)return{result:{diagnostics:[],dirs:[]}};if(r.kind!==`inside`)return{result:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}};let i=await r_(n);return`code`in i?{result:t_.has(i.code)?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}}:{entries:i.entries}},f_=async(e,t,n)=>{let{baseDir:r}=t,i=await d_(e,r);if(`result`in i)return i.result;let a=r===`.`?``:r,o=e=>u_(e,t)&&!n.has(oe.join(a,e.name)),s={entries:i.entries};return o_({baseDir:r,dirs:s.entries.filter(e=>e.isDirectory()&&o(e)),fullPath:m(e,r),repoDir:e,symlinks:s.entries.filter(e=>e.isSymbolicLink()&&o(e))})},p_=async(e,t)=>{let n=await n_(e,m(e,t));return n===`manifest`?{diagnostics:[],dirs:[Rh(t)]}:n===`rejected`?{diagnostics:[{kind:`manifest_unreadable`,path:t}],dirs:[]}:{diagnostics:[],dirs:[]}},m_=(e,t,n)=>{let r=Lh(t.body);return r.kind===`expand-children`?f_(e,r,n):r.kind===`probe-dir`?n.has(Rh(r.dir))?Promise.resolve({diagnostics:[],dirs:[]}):p_(e,r.dir):Promise.resolve({diagnostics:[{kind:`unsupported_pattern`,pattern:t.declared}],dirs:[]})},h_=(e,t)=>Fh(Mh(e),Mh(t)),g_=e=>({negations:e.filter(e=>jh(e)),patterns:e.filter(e=>!jh(e))}),__=e=>{let t=e.reduce((e,t)=>jh(t)?{negations:[...e.negations,t],patterns:e.patterns}:{negations:e.negations.filter(e=>!h_(t,e)),patterns:[...e.patterns,t]},{negations:[],patterns:[]});return{negations:t.negations,patterns:t.patterns.filter(e=>!t.negations.some(t=>h_(e,t)))}},v_=e=>e.endsWith(`/`)?e:`${e}/`,y_=(e,t)=>e.some(e=>Fh(v_(t),v_(Mh(e)))),b_=e=>{let t=new Set,n=[];for(let r of e)r.dirs.forEach(e=>t.add(e)),n.push(...r.diagnostics);return{diagnostics:n,dirs:[...t]}},x_=async(e,t)=>{let{negations:n,patterns:r}=t,i={has:e=>y_(n,e)},a=b_(await Promise.all(r.map(t=>m_(e,{body:Mh(t),declared:t},i))));return{diagnostics:a.diagnostics,dirs:a.dirs}},S_=async(e,t)=>{let n=__(t.npm),r=g_(t.pnpm),i=await Promise.all([x_(e,n),x_(e,r)]);return b_(i)},C_=async e=>{let t=await Hu(e);if(t.npm.length===0&&t.pnpm.length===0)return{diagnostics:qh([...t.diagnostics,{kind:`no_workspace_declaration`}]),packages:[]};let n=await S_(e,t),[r,i]=await Promise.all([s_(e),Promise.all(n.dirs.map(t=>$g(e,t)))]),a=e_([...r,...i]);return{diagnostics:qh([...t.diagnostics,...n.diagnostics,...a.diagnostics]),packages:c_(Hh(a.packages))}};var w_=`0.13.0`;const T_=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},E_=()=>{try{return he()}catch{return``}},D_=()=>({cliVersion:w_,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:E_(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:T_,runner:new Sg});var O_=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}},k_=class extends O_{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},A_=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}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 k_(`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 j_(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var M_=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=>j_(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(`
325
+ `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},dd=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,fd=(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(` | `)},pd=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:dd(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=fd(n,r);return o!==void 0&&(a.warning=o),a},md=(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},U=e=>pe(m(e,`.git`)),hd=e=>`refusing to sync ${e}: not a refs-managed checkout`,gd=async(e,t)=>{if(!U(t))throw b(hd(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw b(hd(t))},_d=/filtering not recognized/iu,vd=e=>e===void 0?{}:{cwd:e},yd=(e,t,n)=>({action:e,args:t,cmd:`git`,...vd(n)}),bd=async(e,t)=>{let n=await e.run(t.cmd,t.args,vd(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}`)},xd=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await bd(e,yd(`git clone`,n));return await bd(e,yd(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&_d.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}},Sd=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},Cd=async(e,t)=>{let n=await Sd(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await Sd(e,t);if(r!==void 0)return r;throw b(`could not detect the default branch for checkout: ${t}`)},wd=async(e,t)=>(await bd(e,yd(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),Td=async(e,t)=>(await bd(e,yd(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Ed=async(e,t)=>{await bd(e,yd(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await Cd(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${ud(n)}`),i},Dd=e=>[yd(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),yd(`git clean -fd`,[`clean`,`-fd`],e)],Od=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Dd(r)),a.push(yd(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),yd(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await bd(e,t)},kd=async(e,t)=>{await gd(e,t.dir);let n=await wd(e,t.dir),r=await Ed(e,t),i=await Td(e,t.dir);await Od(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await wd(e,t.dir);return pd(md(r,i,{newSha:a,oldSha:n}))},Ad=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,jd=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
326
+ `),Md=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await Zl(r,jd),await t(r,493)}))},Nd=async(e,t,n)=>{let r=await bd(e,yd(`git tag`,[`tag`,`--sort=-version:refname`],t)),i=r.stdout.split(`
327
+ `).map(e=>e.trim()).filter(e=>e!==``),a=!r.stderr.includes(`refs: stdout exceeded`);return n===void 0?{complete:a,tags:i}:{complete:a&&i.length<=n,tags:i.slice(0,n)}},Pd=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Fd=/\d+\.\d+\.\d+/gu,Id=e=>cl.safeParse(e).success,Ld=e=>{let t=e.match(Fd);return t!==null&&t.length>1},Rd=e=>{let t=Pd.exec(e);if(!t||Ld(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Id(r))return r},zd=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},Bd=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Rd(r);e&&zd(t,e,n)}return t},Vd=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Hd=e=>{let t=[...e.entries()],[n]=t;if(n===void 0)return null;let[r,i]=n;return t.slice(1).reduce(({format:e,data:t},[n,r])=>Vd(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Ud=e=>{let t=Bd(e);return Hd(t)},Wd=(e,t)=>e.replaceAll(`{version}`,()=>t),Gd=async(e,t,n,r)=>{let i=Wd(n,r);if(!await Ad(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Kd=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,W=e=>{let t=e.replace(Kd,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},qd=/\.git$/u,Jd=e=>e.replace(qd,``),Yd=e=>{let t=0,n=e.length;for(;t<n&&e.charAt(t)===`/`;)t+=1;for(;n>t&&e.charAt(n-1)===`/`;)--n;return e.slice(t,n)},Xd=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,Zd=/^git\+/u,Qd={"https:":`443`,"ssh:":`22`},$d=e=>e.split(`/`).some(e=>e===`.`||e===`..`),ef=e=>e.includes(`\\`),tf=e=>e.includes(`%`),nf=e=>{let t=rl.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${W(e)}' is invalid`);return t.data},rf=({host:e,port:t,protocol:n})=>{let r=Qd[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},af=e=>{let t=Jd(Yd(e.path));return nf(`${rf(e)}/${t}`)},of=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 nf(`local/${n}/${r}`)},sf=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${W(t)}`)}},cf=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`)},lf=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return of(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return cf(e),af({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},uf=(e,t)=>{if(tf(e))throw b(`not a supported git url: percent-encoding not supported in ${W(t)}`);if(e.includes(`:`))throw b(`not a supported git url: ambiguous ':' in scp-style path ${W(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 ${W(t)}; use the ssh:// url form instead`)},df=(e,t)=>{let n=e.groups?.path??``;return uf(n,t),af({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},ff=(e,t)=>{if(ef(e))throw b(`not a supported git url: backslash not allowed in ${W(t)}`)},pf=(e,t)=>{if($d(e))throw b(`not a supported git url: path traversal segment in ${W(t)}`)},mf=(e,t,n)=>{if(e.protocol!==`file:`&&tf(t))throw b(`not a supported git url: percent-encoding not supported in ${W(n)}`)},hf=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(Zd,``);ff(r,e),pf(r,e);let i=Xd.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:df(i,e)};let a=sf(r,e);return mf(a,r,e),{cloneUrl:r,key:lf(a,n)}},gf=`.git`,_f=e=>e.endsWith(gf)?e:`${e}${gf}`,vf=(e,t)=>`https://${e.toLowerCase()}/${Yd(t)}`,yf=(e,t)=>`git@${e.toLowerCase()}:${_f(Yd(t))}`,bf=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},xf=(e,t,n)=>{let r=Qd[e.protocol];if(e.port!==``&&e.port!==r)throw b(`cannot apply git_transport=${t} to ${W(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},Sf=(e,t)=>t===`https`?vf(e.hostname,e.pathname):yf(e.hostname,e.pathname),Cf=(e,t,n)=>{let r=hf(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${W(e)}' → '${t}' (key '${n}' → '${r}')`);return t},wf=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Cf(t.cloneUrl,vf(n,r),t.originalKey)},Tf=e=>{let t=sf(e.cloneUrl,e.cloneUrl);return bf(t.protocol)===e.transport?e.cloneUrl:(xf(t,e.transport,e.cloneUrl),Cf(e.cloneUrl,Sf(t,e.transport),e.originalKey))},Ef=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:hf(e).key,transport:t},r=Xd.exec(e);return r?.groups===void 0?Tf(n):wf(r,n)},Df=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,Of=(e,t)=>{if(Df.test(t))return m(e,`lease-${t}`)},kf=async(e,t)=>{let n=Of(e,t);n!==void 0&&await(await o(n,`w`)).close()},Af=async(e,t)=>{let n=Of(e,t);if(n===void 0)return`gone`;let r=new Date;try{await ee(n,r,r)}catch(e){if(z(e))return`gone`;throw e}return`renewed`},jf=async(e,t)=>{let n=Of(e,t);if(n===void 0)return{state:`absent`};try{return{mtimeMs:(await p(n)).mtimeMs,state:`ok`}}catch(e){return{state:z(e)?`absent`:`unreadable`}}},Mf=`meta.json`,Nf=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},Pf=e=>{try{return process.kill(e,0),!0}catch(e){return Nf(e)!==`ESRCH`}},Ff=e=>{try{return JSON.parse(e)}catch{return}},If=async e=>{try{return await s(e,`utf8`)}catch{return}},Lf=new Set([`ENOENT`,`ENOTDIR`]),Rf=async e=>{try{return{state:`read`,text:await s(e,`utf8`)}}catch(e){let t=Nf(e);return{state:t!==void 0&&Lf.has(t)?`missing`:`unreadable`}}},zf=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Bf=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Vf=e=>{if(!(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>2147483647))return e},Hf=e=>{if(typeof e!=`object`||!e)return;let t=e,n=Vf(t.pid),r=zf(t.acquired_at);if(n===void 0||r===void 0)return;let i=Bf(e);return{acquiredAtMs:r,pid:n,...i===void 0?{}:{token:i}}},Uf=async e=>{let t=await If(m(e,Mf));if(t!==void 0)return Bf(Ff(t))},Wf=async e=>{let t=await Rf(m(e,Mf));if(t.state!==`read`)return{state:t.state};let n=Hf(Ff(t.text));return n===void 0?{state:`malformed`}:{meta:n,state:`valid`}},Gf=async e=>{try{return{mtimeMs:(await p(e)).mtimeMs,state:`ok`}}catch(e){return{state:Nf(e)===`ENOENT`?`gone`:`unreadable`}}},Kf=async(e,t)=>{let n=m(e,Mf),r=`${n}.tmp-${de()}`;await te(r,t,`utf8`),await u(r,n)},qf=()=>de(),Jf=async(e,t)=>{await kf(e,t),await Kf(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Yf=5e3,Xf=async(e,t,n)=>{if(t===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let r=await Gf(e);if(r.state===`gone`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`none`,stale:!1};if(r.state===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let i=n-r.mtimeMs;return{ageMs:i,budgetMs:Yf,meta:t,observedAtMs:n,pidState:`unknown`,policy:`grace`,stale:i>Yf}},Zf=async(e,t,n)=>{let r=t.token===void 0?{state:`absent`}:await jf(e,t.token);return r.state===`unreadable`?{policy:`unknown`}:r.state===`absent`?{ageMs:n-t.acquiredAtMs,budgetMs:6e5,policy:`legacy`}:{ageMs:n-r.mtimeMs,budgetMs:12e4,policy:`lease`}},Qf=async(e,t)=>{let n=await Wf(e);if(n.state!==`valid`)return Xf(e,n.state,t);let{meta:r}=n,i=await Zf(e,r,t),a=!Pf(r.pid),o=i.ageMs!==void 0&&i.budgetMs!==void 0&&i.ageMs>i.budgetMs;return{...i,meta:`valid`,observedAtMs:t,pid:r.pid,pidState:a?`definitely-dead`:`present-or-unknown`,stale:a||o,...r.token===void 0?{}:{token:r.token}}},$f=e=>e.meta===`valid`&&e.pidState===`definitely-dead`&&e.token!==void 0,ep=async(e,t)=>await Uf(e)===t?await Af(e,t)===`gone`?`lost`:`renewed`:`lost`,tp=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),np=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),rp=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Nf(e);if(t!==void 0&&tp.has(t))return!1;throw e}},ip=async(e,t)=>{try{return await u(e,t),!0}catch(e){let t=Nf(e);if(t!==void 0&&np.has(t))return!1;throw e}},ap=`.claims`,op=`.tombstones`,sp=(e,t)=>({lockPath:m(e,t),locksDir:e,name:t}),cp=e=>m(e.locksDir,ap,e.name),lp=e=>m(e.locksDir,op,de()),up=async e=>{await a(m(e,ap),{recursive:!0}),await a(m(e,op),{recursive:!0})},dp=e=>rp(e),fp=async e=>{try{await f(e)}catch{}},pp=async e=>{let t=lp(e);return await ip(e.lockPath,t)?t:void 0},mp=async e=>{let t=await Qf(e.lockPath,Date.now());if(!$f(t)||await Uf(e.lockPath)!==t.token)return!1;let n=await pp(e);return n!==void 0&&(await d(n,{force:!0,recursive:!0}),!0)},hp=async e=>{await up(e.locksDir);let t=cp(e);if(!await dp(t))return!1;let n=await mp(e).then(e=>({ok:!0,stolen:e}),e=>({error:e,ok:!1}));if(await fp(t),!n.ok)throw n.error;return n.stolen},gp=async e=>{try{return(await c(e,{withFileTypes:!0})).map(e=>({isDir:e.isDirectory(),name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}catch(e){if(z(e))return[];throw e}},_p=async e=>(await gp(e)).filter(e=>!e.name.startsWith(`.`)),vp=async(e,t,n)=>{let r=await Qf(m(e,t.name),n);if(r.policy!==`none`)return{diagnosis:r,isDirectory:t.isDir,kind:`lock`,name:t.name}},yp=async(e,t)=>{let n=m(e,ap),r=await gp(n);return(await Promise.all(r.map(async e=>({diagnosis:await Qf(m(n,e.name),t),isDirectory:e.isDir,kind:`claim`,name:e.name})))).filter(e=>e.diagnosis.policy!==`none`)},bp=async e=>{let t=Date.now(),n=await _p(e.locksDir),[r,i]=await Promise.all([Promise.all(n.map(n=>vp(e.locksDir,n,t))),yp(e.locksDir,t)]);return[...r.filter(e=>e!==void 0),...i]},xp=e=>{let t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),i=r%60,a=Math.floor(r/60);return a>0?i===0?`${a}h`:`${a}h ${i}m`:r>0?n===0?`${r}m`:`${r}m ${n}s`:`${n}s`},Sp=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} is present (identity not verified)`,Cp={grace:`created`,lease:`lease renewed`,legacy:`acquired`,none:`observed`,unknown:`observed`},wp={grace:`from creation, while its metadata has not been published`,lease:`from the last renewal`,legacy:`from acquisition (no renewable lease)`,none:``,unknown:``},Tp=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return t===void 0||n===void 0?``:t<0?`, but its recorded time is in the future — check the system clock`:`, ${Cp[r]} ${xp(t)} ago; its window is ${xp(n)} ${wp[r]}`},Ep=(e,t)=>{if(t.policy===`none`)return`lock ${e} could not be acquired before the timeout, but it was released while the failure was being diagnosed. Retry the operation.`;let n=`lock ${e} is held: ${Sp(t)}`;return $f(t)?`${n}, and refs is entitled to reclaim it — it could not do so before the timeout. Retry; if it persists, run refs doctor.`:t.stale?`${n}${Tp(t)}. refs does not reclaim this automatically: only a recorded process the operating system reports as gone is reclaimed, and this one is not. Run refs doctor for what to do about it.`:`${n}${Tp(t)}. Retry once the other refs command finishes.`},Dp=(e,t)=>{if(t.stopped)return;let n=setTimeout(()=>{t.stopped||(t.inFlight=Op(e,t))},e.intervalMs);n.unref(),t.timer=n},Op=async(e,t)=>{try{if(await e.renew()===`lost`){t.lost=!0,t.stopped=!0;return}}catch{}Dp(e,t)},kp=e=>{let t={inFlight:Promise.resolve(),lost:!1,stopped:!1};return Dp(e,t),{ownershipLost:()=>t.lost,stop:async()=>{t.stopped=!0,t.timer!==void 0&&clearTimeout(t.timer),await t.inFlight}}},Ap=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,jp=async(e,t)=>{try{await Jf(e,t)}catch(e){if(Nf(e)===`ENOENT`)return`retry`;throw e}return t},Mp=async(e,t)=>{if(!await rp(e))return;let n=await jp(e,qf());return n===`retry`?Date.now()>=t?void 0:Mp(e,t):n},Np=async(e,t)=>{if(!await hp(e)){if(Date.now()>=t){let t=await Qf(e.lockPath,Date.now());throw Se(Ep(e.name,t))}await ge(100)}},Pp=async(e,t)=>{let n=await Mp(e.lockPath,t);return n===void 0?(await Np(e,t),Pp(e,t)):n},Fp=async(e,t)=>await Uf(e)===t&&(await d(e,{force:!0,recursive:!0}),!0),Ip=async e=>{try{return{ok:!0,value:await e()}}catch(e){return{error:e,ok:!1}}},Lp=async(e,t,n,r)=>{await n.stop();let i=await Ip(()=>Fp(e.lockPath,t));if(!r.ok)throw r.error;if(!i.ok)throw i.error;if(n.ownershipLost()||!i.value)throw Se(`lock ${e.name} was lost while the operation was running`);return r.value},Rp=e=>e!==`.`&&e!==`..`&&Ap.test(e),zp=e=>{if(!Rp(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}`)},G=async(e,t,n,r)=>{zp(t);let i=sp(e.locksDir,t);await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await Pp(i,o),c=kp({intervalMs:3e4,renew:()=>ep(i.lockPath,s)});return Lp(i,s,c,await Ip(n))},Bp=oc({directory:F().optional(),url:F().optional()}),Vp=oc({repository:cc([F(),Bp]).optional()}),Hp=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,Up=new Set([`node_modules`,`favicon.ico`]),Wp=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),Gp=e=>{let[t,n]=e.split(`/`);return n??t??e},Kp=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!Hp.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=Gp(e);if(Up.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},qp=e=>e.replaceAll(`/`,`%2F`),Jp=e=>typeof e==`string`?e:e?.url,Yp=e=>{if(typeof e==`object`&&e?.directory){let t=ll.safeParse(e.directory);if(t.success)return t.data}},Xp=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},Zp=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${qp(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 Xp(n,t),i=Vp.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},Qp=(e,t)=>{try{return hf(e)}catch{throw Wp(t)}},$p=async(e,t)=>{Kp(t);let n=await Zp(e,t),r=Jp(n.repository);if(r===void 0||r===``)throw Wp(t);let{cloneUrl:i,key:a}=Qp(r,t),o=Yp(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},em=(e,t,n)=>{let r=e instanceof RegExp?tm(e,n):e,i=t instanceof RegExp?tm(t,n):t,a=r!==null&&i!=null&&nm(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},tm=(e,t)=>{let n=t.match(e);return n?n[0]:null},nm=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},rm=`\0SLASH`+Math.random()+`\0`,im=`\0OPEN`+Math.random()+`\0`,am=`\0CLOSE`+Math.random()+`\0`,om=`\0COMMA`+Math.random()+`\0`,sm=`\0PERIOD`+Math.random()+`\0`,cm=new RegExp(rm,`g`),lm=new RegExp(im,`g`),um=new RegExp(am,`g`),dm=new RegExp(om,`g`),fm=new RegExp(sm,`g`),pm=/\\\\/g,mm=/\\{/g,hm=/\\}/g,gm=/\\,/g,_m=/\\\./g;function vm(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function ym(e){return e.replace(pm,rm).replace(mm,im).replace(hm,am).replace(gm,om).replace(_m,sm)}function bm(e){return e.replace(cm,`\\`).replace(lm,`{`).replace(um,`}`).replace(dm,`,`).replace(fm,`.`)}function xm(e){if(!e)return[``];let t=[],n=em(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=xm(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function Sm(e,t={}){if(!e)return[];let{max:n=1e5,maxLength:r=4e6}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),km(ym(e),n,r,!0).map(bm)}function Cm(e){return`{`+e+`}`}function wm(e){return/^-?0\d/.test(e)}function Tm(e,t){return e<=t}function Em(e,t){return e>=t}function Dm(e,t,n,r,i,a){let o=[],s=0;for(let c=0;c<e.length;c++)for(let l=0;l<n.length;l++){if(o.length>=r)return o;let u=e[c]+t+n[l];if(!a||u){if(s+u.length>i)return o;o.push(u),s+=u.length}}return o}function Om(e,t,n,r){let i=e.split(/\.\./),a=[];if(i[0]===void 0||i[1]===void 0)return a;let o=vm(i[0]),s=vm(i[1]),c=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(vm(i[2])),1):1,u=Tm;s<o&&(l*=-1,u=Em);let d=i.some(wm),f=0;for(let e=o;u(e,s)&&a.length<n;e+=l){let n;if(t)n=String.fromCharCode(e),n===`\\`&&(n=``);else if(n=String(e),d){let t=c-n.length;if(t>0){let r=Array(t+1).join(`0`);n=e<0?`-`+r+n.slice(1):r+n}}if(f+n.length>r)break;a.push(n),f+=n.length}return a}function km(e,t,n,r){let i=[``],a=!1,o=!0;for(;;){let s=em(`{`,`}`,e);if(!s)return Dm(i,e,[``],t,n,a);let c=s.pre;if(/\$$/.test(c)){if(i=Dm(i,c+`{`+s.body+`}`,[``],t,n,a&&!s.post.length),o=!1,!s.post.length)break;e=s.post;continue}let l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),d=l||u,f=s.body.indexOf(`,`)>=0;if(!d&&!f){if(s.post.match(/,(?!,).*\}/)){e=s.pre+`{`+s.body+am+s.post,r=!0;continue}return Dm(i,c+`{`+s.body+`}`+s.post,[``],t,n,a)}o&&=(a=r&&!d,!1);let p;if(d)p=Om(s.body,u,t,n);else{let r=xm(s.body);if(r.length===1&&r[0]!==void 0&&(r=km(r[0],t,n,!1).map(Cm),r.length===1)){if(i=Dm(i,c+r[0],[``],t,n,a&&!s.post.length),!s.post.length)break;e=s.post;continue}let o=a&&!s.post.length&&!c;for(let e=0;o&&e<i.length;e++)i[e]&&(o=!1);p=[];let l=0;outer:for(let e=0;e<r.length;e++){let i=km(r[e],t,n,!1);for(let e=0;e<i.length;e++){let r=i[e];if(!o||r){if(p.length>=t||l+r.length>n)break outer;p.push(r),l+=r.length}}}}if(i=Dm(i,c,p,t,n,a&&!s.post.length),!s.post.length)break;e=s.post}return i}const Am=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},jm={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},Mm=e=>e.replace(/[[\]\\-]/g,`\\$&`),Nm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Pm=e=>e.join(``),Fm=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(jm))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue WHILE}}if(c=!1,d){t>d?r.push(Mm(d)+`-`+Mm(t)):t===d&&r.push(Mm(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(Mm(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(Mm(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let e=r[0].length===2?r[0].slice(-1):r[0];return[Nm(e),!1,u-n,!1]}let f=`[`+(l?`^`:``)+Pm(r)+`]`,p=`[`+(l?``:`^`)+Pm(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},Im=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var K;const Lm=new Set([`!`,`?`,`+`,`*`,`@`]),Rm=e=>Lm.has(e),zm=e=>Rm(e.type),Bm=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Vm=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Hm=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),Um=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Wm=`(?!\\.)`,Gm=new Set([`[`,`.`]),Km=new Set([`..`,`.`]),qm=new Set(`().*{}+?[]^$\\!`),Jm=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Ym=`[^/]+?`;let Xm=0;var Zm=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++Xm;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.#l=this.type?this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==``){if(typeof t!=`string`&&!(t instanceof K&&t.#i===this))throw Error(`invalid part: `+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;t<this.#a;t++){let n=e.#r[t];if(!(n instanceof K&&n.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(e){let t=new K(this.type,e);for(let e of this.#r)t.copyIn(e);return t}static#f(e,t,n,r,i){let a=r.maxExtglobRecursion??2,o=!1,s=!1,c=-1,l=!1;if(t.type===null){let u=n,d=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,d+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),d+=n;continue}if(n===`[`){s=!0,c=u,l=!1,d+=n;continue}if(!r.noext&&Rm(n)&&e.charAt(u)===`(`&&i<=a){t.push(d),d=``;let a=new K(n,t);u=K.#f(e,a,u,r,i+1),t.push(a);continue}d+=n}return t.push(d),u}let u=n+1,d=new K(null,t),f=[],p=``;for(;u<e.length;){let n=e.charAt(u++);if(o||n===`\\`){o=!o,p+=n;continue}if(s){u===c+1?(n===`^`||n===`!`)&&(l=!0):n===`]`&&!(u===c+2&&l)&&(s=!1),p+=n;continue}if(n===`[`){s=!0,c=u,l=!1,p+=n;continue}if(!r.noext&&Rm(n)&&e.charAt(u)===`(`&&(i<=a||t&&t.#h(n))){let a=t&&t.#h(n)?0:1;d.push(p),p=``;let o=new K(n,d);d.push(o),u=K.#f(e,o,u,r,i+a);continue}if(n===`|`){d.push(p),p=``,f.push(d),d=new K(null,t);continue}if(n===`)`)return p===``&&t.#r.length===0&&(t.#u=!0),d.push(p),p=``,t.push(...f,d),u;p+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],u}#p(e){return this.#m(e,Vm)}#m(e,t=Bm){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null)return!1;let n=e.#r[0];return!n||typeof n!=`object`||n.type===null?!1:this.#h(n.type,t)}#h(e,t=Hm){return!!t.get(this.type)?.includes(e)}#g(e,t){let n=e.#r[0],r=new K(null,n,this.options);r.#r.push(``),n.push(r),this.#_(e,t)}#_(e,t){let n=e.#r[0];this.#r.splice(t,1,...n.#r);for(let e of n.#r)typeof e==`object`&&(e.#i=this);this.#l=void 0}#v(e){return!!Um.get(this.type)?.has(e)}#y(e){if(!e||typeof e!=`object`||e.type!==null||e.#r.length!==1||this.type===null||this.#r.length!==1)return!1;let t=e.#r[0];return!t||typeof t!=`object`||t.type===null?!1:this.#v(t.type)}#b(e){let t=Um.get(this.type),n=e.#r[0],r=t?.get(n.type);if(!r)return!1;this.#r=n.#r;for(let e of this.#r)typeof e==`object`&&(e.#i=this);this.type=r,this.#l=void 0,this.#u=!1}static fromGlob(e,t={}){let n=new K(null,void 0,t);return K.#f(e,n,0,t,0),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(e){let t=e??!!this.#c.dot;if(this.#e===this&&(this.#x(),this.#d()),!zm(this)){let n=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?K.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Km.has(this.#r[0]))){let n=Gm,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Wm:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,Im(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,Im(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Wm:``)+Ym;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Wm:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,Im(i),this.#t=!!this.#t,this.#n]}#x(){if(zm(this)){let e=0,t=!1;do{t=!0;for(let e=0;e<this.#r.length;e++){let n=this.#r[e];typeof n==`object`&&(n.#x(),this.#m(n)?(t=!1,this.#_(n,e)):this.#p(n)?(t=!1,this.#g(n,e)):this.#y(n)&&(t=!1,this.#b(n)))}}while(!t&&++e<10)}else for(let e of this.#r)typeof e==`object`&&e.#x();this.#l=void 0}#S(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(qm.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?Ym:`[^/]*?`,t=!0;continue}if(o=!1,c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=Fm(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=`[^/]`,t=!0;continue}i+=Jm(c)}return[i,Im(e),!!t,a]}};K=Zm;const Qm=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),q=(e,t,n={})=>(Am(t),!n.nocomment&&t.charAt(0)===`#`?!1:new wh(t,n).match(e)),$m=/^\*+([^+@!?*[(]*)$/,eh=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),th=e=>t=>t.endsWith(e),nh=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),rh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ih=/^\*+\.\*+$/,ah=e=>!e.startsWith(`.`)&&e.includes(`.`),oh=e=>e!==`.`&&e!==`..`&&e.includes(`.`),sh=/^\.\*+$/,ch=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),lh=/^\*+$/,uh=e=>e.length!==0&&!e.startsWith(`.`),dh=e=>e.length!==0&&e!==`.`&&e!==`..`,fh=/^\?+([^+@!?*[(]*)?$/,ph=([e,t=``])=>{let n=_h([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},mh=([e,t=``])=>{let n=vh([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},hh=([e,t=``])=>{let n=vh([e]);return t?e=>n(e)&&e.endsWith(t):n},gh=([e,t=``])=>{let n=_h([e]);return t?e=>n(e)&&e.endsWith(t):n},_h=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},vh=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},yh=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,bh={win32:{sep:`\\`},posix:{sep:`/`}};q.sep=yh===`win32`?bh.win32.sep:bh.posix.sep;const J=Symbol(`globstar **`);q.GLOBSTAR=J,q.filter=(e,t={})=>n=>q(n,e,t);const Y=(e,t={})=>Object.assign({},e,t);q.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return q;let t=q;return Object.assign((n,r,i={})=>t(n,r,Y(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,Y(e,n))}static defaults(n){return t.defaults(Y(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,Y(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,Y(e,r))}},unescape:(n,r={})=>t.unescape(n,Y(e,r)),escape:(n,r={})=>t.escape(n,Y(e,r)),filter:(n,r={})=>t.filter(n,Y(e,r)),defaults:n=>t.defaults(Y(e,n)),makeRe:(n,r={})=>t.makeRe(n,Y(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,Y(e,r)),match:(n,r,i={})=>t.match(n,r,Y(e,i)),sep:t.sep,GLOBSTAR:J})};const xh=(e,t={})=>(Am(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Sm(e,{max:t.braceExpandMax}));q.braceExpand=xh,q.makeRe=(e,t={})=>new wh(e,t).makeRe(),q.match=(e,t,n={})=>{let r=new wh(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const Sh=/[?*]|[+@!]\(.*?\)|\[|\]/,Ch=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var wh=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){Am(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||yh,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!Sh.test(e[2]))&&!Sh.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t of e)for(let e=0;e<t.length;e++)t[e]===`**`&&(t[e]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];(n!==1||r!==``||e[0]!==``)&&(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&!(this.isWindows&&/^[a-z]:$/i.test(r))&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];(e!==1||r!==``||n[0]!==``)&&(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=0,i=0;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),a=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),o=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),s=!o&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),c=a?3:n?0:void 0,l=s?3:o?0:void 0;if(typeof c==`number`&&typeof l==`number`){let[n,a]=[e[c],t[l]];n.toLowerCase()===a.toLowerCase()&&(t[l]=n,i=l,r=c)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(J)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(J,i),o=t.lastIndexOf(J),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n<e.length-u;n++){let r=String(e[n]);if(t=!0,r===`.`||r===`..`||!this.options.dot&&r.startsWith(`.`))return!1}return n||t}let d=[[[],0]],f=d[0],p=0,ee=[0];for(let e of c)e===J?(ee.push(p),f=[[],0],d.push(f)):(f[0].push(e),p++);let te=d.length-1,ne=e.length-u;for(let e of d)e[1]=ne-(ee[te--]+e[0].length);return!!this.#t(e,d,r,0,n,0,!!u)}#t(e,t,n,r,i,a,o){let s=t[r];if(!s){for(let t=n;t<e.length;t++){o=!0;let n=e[t];if(n===`.`||n===`..`||!this.options.dot&&n.startsWith(`.`))return!1}return o}let[c,l]=s;for(;n<=l;){if(this.#n(e.slice(0,n+c.length),c,i,n,0)&&a<this.maxGlobstarRecursion){let s=this.#t(e,t,n+c.length,r+1,i,a+1,o);if(s!==!1)return s}let s=e[n];if(s===`.`||s===`..`||!this.options.dot&&s.startsWith(`.`))return!1;n++}return i||null}#n(e,t,n,r,i){let a,o,s,c;for(a=r,o=i,c=e.length,s=t.length;a<c&&o<s;a++,o++){this.debug(`matchOne loop`);let n=t[o],r=e[a];if(this.debug(t,n,r),n===!1||n===J)return!1;let i;if(typeof n==`string`?(i=r===n,this.debug(`string match`,n,r,i)):(i=n.test(r),this.debug(`pattern match`,n,r,i)),!i)return!1}if(a===c&&o===s)return!0;if(a===c)return n;if(o===s)return a===c-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return xh(this.pattern,this.options)}parse(e){Am(e);let t=this.options;if(e===`**`)return J;if(e===``)return``;let n,r=null;(n=e.match(lh))?r=t.dot?dh:uh:(n=e.match($m))?r=(t.nocase?t.dot?rh:nh:t.dot?th:eh)(n[1]):(n=e.match(fh))?r=(t.nocase?t.dot?mh:ph:t.dot?hh:gh)(n):(n=e.match(ih))?r=t.dot?oh:ah:(n=e.match(sh))&&(r=ch);let i=Zm.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?`[^/]*?`:t.dot?`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`:`(?:(?!(?:\\/|^)\\.).)*?`,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?Ch(e):e===J?J:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e===J&&a!==J&&(a===void 0?i!==void 0&&i!==J?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==J&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=J))});let i=t.filter(e=>e!==J);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return q.defaults(e).Minimatch}};q.AST=Zm,q.Minimatch=wh,q.escape=Qm,q.unescape=Im;const Th=/[/\\]/u,Eh={kind:`ignore`},Dh=e=>!ae(e)&&e.split(Th).every(e=>e!==`.`&&e!==`..`),Oh=/^!+/u,kh=/^\.?\/+/u,Ah=e=>{let t=Oh.exec(e)?.[0]??``;return{body:e.slice(t.length).replace(kh,``),negated:t.length%2==1}},jh=e=>Ah(e).negated,Mh=e=>Ah(e).body,Nh=/[?[\]{}()]/u,Ph=e=>Dh(e)&&!jh(e)&&!e.includes(`**`)&&!Nh.test(e)&&(e.match(/\*/gu)??[]).length<=1,Fh=(e,t)=>q(e,t),Ih=e=>e.replaceAll(/\/+/gu,`/`).replace(/\/$/u,``),Lh=e=>{let t=Ih(e).split(`/`),n=t.findIndex(e=>e.includes(`*`));return n===-1?Eh:{baseDir:n===0?`.`:t.slice(0,n).join(`/`),kind:`expand-children`,pattern:Ih(e),suffix:t.slice(n+1).join(`/`)}},Rh=e=>Ph(e)?e.includes(`*`)?Lh(e):{dir:e,kind:`probe-dir`,pattern:e}:Eh,zh=new Set([`candidate_not_inspected`,`manifest_unreadable`,`unsupported_pattern`,`workspace_declaration_unparsed`,`workspace_dir_unreadable`,`workspace_file_unreadable`]),Bh=(e,t)=>t?.name?{name:t.name,path:e}:void 0,Vh=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},Hh=e=>!e.diagnostics.some(e=>zh.has(e.kind)),Uh=e=>!e.diagnostics.some(e=>e.kind===`no_workspace_declaration`),Wh=(e,t)=>e<t?-1:+(e>t),Gh=e=>`path`in e?`${e.kind} ${e.path}`:`file`in e?`${e.kind} ${e.file}`:`pattern`in e?`${e.kind} ${e.pattern}`:e.kind,Kh=e=>e.toSorted((e,t)=>Wh(Gh(e),Gh(t))),qh=e=>!ae(e)&&!e.split(/[/\\]/u).includes(`..`),Jh=(e,t)=>e.kind===`missing`?{kind:`absent`}:e.kind===`outside`?{kind:`unreadable`,reason:`${t} escapes the checkout`}:{kind:`unreadable`,reason:e.code},Yh=async(e,t,n)=>{if(!qh(t))return{kind:`unreadable`,reason:`path escapes the checkout`};let r=await Xh(e,t);if(`probe`in r)return r.probe;let i=await Zh(r.real);return`reason`in i?{kind:`unreadable`,reason:i.reason}:i.found===n?{kind:`match`}:{found:i.found,kind:`mismatch`}},Xh=async(e,t)=>{let n=await Eu(e,m(e,t));if(n.kind!==`inside`)return{probe:Jh(n,`path`)};let r=await Eu(e,m(n.real,`package.json`));return r.kind===`inside`?{real:r.real}:{probe:Jh(r,`manifest`)}},Zh=async e=>{try{let t=JSON.parse(await s(e,`utf8`));return{found:Fu(t)}}catch(e){return{reason:e.code??String(e)}}},Qh=(e,t)=>{let n=e.filter(e=>e.name===t).map(e=>e.path);return n.length===0?{kind:`absent`}:n.length===1?{kind:`found`,path:n[0]}:{kind:`ambiguous`,paths:n.toSorted(Wh)}},$h=new Set;let eg=!1;const tg=()=>{for(let e of $h)try{e.kill(`SIGKILL`)}catch{}},ng=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],rg=e=>{let t=()=>{tg(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},ig=()=>{eg||(eg=!0,ng.forEach(e=>{rg(e)}),process.on(`exit`,tg))},ag=()=>{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}}},og=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
328
+ `),sg=(e,t,n)=>{let r=e;return t.truncated&&(r=og(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=og(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},cg={clear:()=>{},markedTimedOut:()=>!1},lg=(e,t)=>{if(t===void 0)return cg;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}},ug=e=>e===void 0?{}:{cwd:e},dg=(e,t)=>og(e,`refs: command timed out after ${String(t)}ms`),fg=(e,t)=>({exitCode:124,stderr:dg(e,t),stdout:``,timedOut:!0}),pg=(e,t,n)=>{let r=be(e,t,{...ug(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});$h.add(r);let i=ag(),a=ag();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:lg(r,n?.timeoutMs)}},mg=(e,t,n)=>{try{return pg(e,t,n)}catch(e){return{exitCode:127,stderr:gg(e),stdout:``}}},hg=e=>!(`child`in e),gg=e=>e instanceof Error?e.message:String(e),_g=async e=>{try{let[t]=await ve(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:gg(e)}}},vg=e=>e===null?1:e,yg=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,bg=e=>e.timedOut?fg(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?yg({exitCode:vg(e.code),stderr:sg(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):yg({exitCode:127,stderr:og(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var xg=class{async run(e,t,n){ig();let r=mg(e,t,n);if(hg(r))return r;let i=await _g(r.child);return $h.delete(r.child),r.timeout.clear(),bg({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Sg=pl.partial({description:!0}),Cg=L({default_branch:F().min(1),key:rl,tag_format_candidate:cl.nullable(),url:F().min(1)});Cg.extend({description:F().default(``),packages:Wc(Sg)});const wg=Cg.extend({description:F().min(1),packages:Wc(pl)}),Tg=L({effective_clone_mode:ol.optional(),head_sha:F().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:F().optional(),last_fetched_at:Bc().optional(),pending_proposal_at:Bc().optional()}),Eg=L({refs:Hc(e=>e.length>0&&!Vc.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,fc(F(),Tg)).default({})}),Dg=(e,t,n)=>t?.[e]??n[e],Og=async e=>{try{return await s(e.statePath,`utf8`)}catch(e){if(z(e))return;throw e}},kg=e=>{try{return JSON.parse(e)}catch{return}},Ag=async e=>{let t=await Og(e);if(t===void 0)return Eg.parse({});let n=kg(t);if(n===void 0)return Eg.parse({});let r=Eg.safeParse(n);return r.success?r.data:Eg.parse({})},jg=async(e,t)=>{let n=Eg.safeParse(t);if(!n.success)throw b(E(n.error));await Zl(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Mg=/^\d+\.\d+\.\d+$/u,Ng=/^0+(?=\d)/u,Pg=(e,t)=>{let n=e.replace(Ng,``),r=t.replace(Ng,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},Fg=(e,t)=>{if(!Mg.test(e)||!Mg.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>Pg(e,r[t]??``)).find(e=>e!==0)??0},Ig=oc({version:F().regex(Mg)}),Lg=L({checked_at:Bc(),latest_version:F().regex(Mg)}),Rg=async e=>{try{let t=Lg.safeParse(JSON.parse(await s(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},zg=async(e,t)=>{try{await p(e.root),await Zl(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},Bg=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},Vg=async e=>{try{let t=await e(`https://registry.npmjs.org/@kaisers-io%2Frefs/latest`,{signal:AbortSignal.timeout(2e3)});if(t.status!==200)return;let n=Ig.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},Hg=async e=>{let t=await Rg(e.home);if(t!==void 0&&Bg(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await Vg(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await zg(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},Ug=(e,t)=>{let n=Fg(e,t);return n!==void 0&&n<0},Wg=(e,t)=>`refs ${t} is available (this is ${e}) — update: npm i -g @kaisers-io/refs@latest`,Gg=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},Kg=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},qg={check:!0,notify:!0},Jg=e=>{let t=Gg(e.env);return t===void 0?(e.updates??qg).check?Kg(e.env)?`ci`:`on`:`config`:t?`on`:`env`},Yg=e=>Jg(e)===`on`,Xg=e=>Yg(e)&&(e.updates??qg).notify,Zg=async(e,t)=>{let n=await Eu(e,m(t,`package.json`));if(n.kind===`inside`)try{let e=JSON.parse(await s(n.real,`utf8`));return{name:Fu(e)}}catch{return}},Qg=async(e,t)=>{let n=await Zg(e,m(e,t));if(n===void 0)return{diagnostic:{kind:`manifest_unreadable`,path:t}};let r=Bh(t,n);return r===void 0?{diagnostic:{kind:`manifest_missing_name`,path:t}}:{pkg:r}},$g=e=>{let t=[],n=[];for(let r of e)r.diagnostic!==void 0&&t.push(r.diagnostic),r.pkg!==void 0&&n.push(r.pkg);return{diagnostics:t,packages:n}},e_=new Set([`ENOENT`,`ENOTDIR`]),t_=async(e,t)=>{let n=await Eu(e,m(t,`package.json`));if(n.kind===`missing`)return`none`;if(n.kind!==`inside`)return`rejected`;try{return await s(n.real,`utf8`),`manifest`}catch{return`rejected`}},n_=async e=>{try{return{entries:await c(e,{withFileTypes:!0})}}catch(e){return{code:e.code??``}}},r_=e=>Promise.all(e.entries.map(t=>t_(e.repoDir,m(e.fullPath,t.name,e.suffix)))),i_=(e,t,n)=>e.filter((e,r)=>n(t[r])).map(e=>e.name),a_=async e=>{let{baseDir:t,dirs:n,fullPath:r,repoDir:i,suffix:a,symlinks:o}=e,s=e=>oe.join(t===`.`?``:t,e,a),[c,l]=await Promise.all([r_({entries:n,fullPath:r,repoDir:i,suffix:a}),r_({entries:o,fullPath:r,repoDir:i,suffix:a})]);return{diagnostics:[...i_(n,c,e=>e===`rejected`).map(e=>({kind:`manifest_unreadable`,path:s(e)})),...i_(o,l,e=>e!==`none`).map(e=>({kind:`candidate_not_inspected`,path:s(e)}))],dirs:i_(n,c,e=>e===`manifest`).map(e=>s(e))}},o_=async e=>{let t=await Qg(e,`.`);return`pkg`in t?[t]:[]},s_=e=>{let t=e.find(e=>e.path===`.`);return t===void 0?[...e]:e.some(e=>e.path!==`.`&&e.name===t.name)?e.filter(e=>e!==t):[...e]},c_=async e=>{let[t]=await o_(e);return t!==void 0&&`pkg`in t?t.pkg:void 0},l_=(e,t)=>oe.join(e.baseDir===`.`?``:e.baseDir,t,e.suffix),u_=(e,t)=>Fh(l_(t,e.name),t.pattern),d_=async(e,t)=>{let n=m(e,t),r=await Eu(e,n);if(r.kind===`missing`)return{result:{diagnostics:[],dirs:[]}};if(r.kind!==`inside`)return{result:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}};let i=await n_(n);return`code`in i?{result:e_.has(i.code)?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}}:{entries:i.entries}},f_=async(e,t,n)=>{let{baseDir:r}=t,i=await d_(e,r);if(`result`in i)return i.result;let a=e=>u_(e,t)&&!n.has(l_(t,e.name)),o={entries:i.entries};return a_({baseDir:r,dirs:o.entries.filter(e=>e.isDirectory()&&a(e)),fullPath:m(e,r),repoDir:e,suffix:t.suffix,symlinks:o.entries.filter(e=>e.isSymbolicLink()&&a(e))})},p_=async(e,t)=>{let n=await t_(e,m(e,t));return n===`manifest`?{diagnostics:[],dirs:[Ih(t)]}:n===`rejected`?{diagnostics:[{kind:`manifest_unreadable`,path:t}],dirs:[]}:{diagnostics:[],dirs:[]}},m_=(e,t,n)=>{let r=Rh(t.body);return r.kind===`expand-children`?f_(e,r,n):r.kind===`probe-dir`?n.has(Ih(r.dir))?Promise.resolve({diagnostics:[],dirs:[]}):p_(e,r.dir):Promise.resolve({diagnostics:[{kind:`unsupported_pattern`,pattern:t.declared}],dirs:[]})},h_=(e,t)=>Fh(Mh(e),Mh(t)),g_=e=>({negations:e.filter(e=>jh(e)),patterns:e.filter(e=>!jh(e))}),__=e=>{let t=e.reduce((e,t)=>jh(t)?{negations:[...e.negations,t],patterns:e.patterns}:{negations:e.negations.filter(e=>!h_(t,e)),patterns:[...e.patterns,t]},{negations:[],patterns:[]});return{negations:t.negations,patterns:t.patterns.filter(e=>!t.negations.some(t=>h_(e,t)))}},v_=e=>e.endsWith(`/`)?e:`${e}/`,y_=(e,t)=>e.some(e=>Fh(v_(t),v_(Mh(e)))),b_=e=>{let t=new Set,n=[];for(let r of e)r.dirs.forEach(e=>t.add(e)),n.push(...r.diagnostics);return{diagnostics:n,dirs:[...t]}},x_=async(e,t)=>{let{negations:n,patterns:r}=t,i={has:e=>y_(n,e)},a=b_(await Promise.all(r.map(t=>m_(e,{body:Mh(t),declared:t},i))));return{diagnostics:a.diagnostics,dirs:a.dirs}},S_=async(e,t)=>{let n=__(t.npm),r=g_(t.pnpm),i=await Promise.all([x_(e,n),x_(e,r)]);return b_(i)},C_=async e=>{let t=await Hu(e);if(t.npm.length===0&&t.pnpm.length===0)return{diagnostics:Kh([...t.diagnostics,{kind:`no_workspace_declaration`}]),packages:[]};let n=await S_(e,t),[r,i]=await Promise.all([o_(e),Promise.all(n.dirs.map(t=>Qg(e,t)))]),a=$g([...r,...i]);return{diagnostics:Kh([...t.diagnostics,...n.diagnostics,...a.diagnostics]),packages:s_(Vh(a.packages))}};var w_=`0.13.1`;const T_=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},E_=()=>{try{return he()}catch{return``}},D_=()=>({cliVersion:w_,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:E_(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:T_,runner:new xg});var O_=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}},k_=class extends O_{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},A_=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}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 k_(`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 j_(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var M_=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=>j_(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(`
329
329
  `)}displayWidth(e){return xe(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,`
330
330
  `+` `.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(`
331
331
  `)}},N_=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=I_(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 k_(`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?F_(this.name().replace(/^no-/,``)):F_(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}},P_=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&&r;return t.negate===(i===e)}};function F_(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function I_(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}
@@ -343,14 +343,14 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
343
343
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
344
344
  - ${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=ne.resolve(e,t);if(fe.existsSync(r))return r;if(n.includes(ne.extname(t)))return;let i=n.find(e=>fe.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=fe.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=ne.resolve(ne.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=ne.basename(this._scriptPath,ne.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(ne.extname(i)),s;h.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=B_(h.execArgv).concat(t),s=ye.spawn(h.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=B_(h.execArgv).concat(t),s=ye.spawn(h.argv[0],t,{stdio:`inherit`})):s=ye.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 O_(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 O_(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&&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}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}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(`
345
345
  `),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 P_(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=R_(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=R_(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=>j_(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=ne.basename(e,ne.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.
346
- 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 B_(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 V_(){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 z_;const H_=[],U_=e=>Array.isArray(e)?e:[e],W_=e=>e===void 0?H_:[e],G_=e=>e instanceof Error?e.message:String(e),X=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},Z=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??H_};e.out(JSON.stringify(t));return}for(let t of U_(n))e.out(t);for(let t of i??H_)e.errLine(`refs: warning: ${t}`)},K_=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message,...n.reason===void 0?{}:{reason:n.reason}},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},q_=(e,t)=>{e.errLine(`refs: ${t}`)},Q=(e,t,n)=>async()=>{try{await n()}catch(n){let r=we(n,{verbose:t.verbose});K_(e,t,r),process.exitCode=r.exitCode}},J_=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,Y_=e=>`rm -rf -- ${J_(e)}`,X_=e=>`rmdir -- ${J_(e)}`,Z_=e=>({path:e.path}),Q_=e=>e.filter(e=>e.path!==`.`),$_=e=>e.find(e=>e.path===`.`),ev=e=>{let t=$_(e);return t===void 0?{}:{[t.name]:Z_(t)}},tv=(e,t,n)=>{let r=Q_(e),i=ev(e);return r.length>0?{...i,...Object.fromEntries(r.map(e=>[e.name,Z_(e)]))}:n===void 0?i:{...i,[n]:{path:t??`.`}}},nv=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}},rv=(e,t)=>{let n=Object.entries(e);if(n.length!==0)return Object.fromEntries(n.map(([e,n])=>[e,nv(e===t.rootPackageName?av(n,t.refDescription):n)]))},iv=(e,t)=>{let[n]=Object.keys(ev(e));if(n!==void 0)return t[n]?.path===`.`?n:void 0},av=(e,t)=>({...e,description:t}),ov=(e,t)=>Object.keys(e).filter(e=>e!==t).toSorted(),sv=(e,t,n)=>{if(ov(e,n).length!==0)throw b(`refs add --description cannot describe a package: it has one description, about the repository. Run the two-phase flow instead:
346
+ 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 B_(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 V_(){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 z_;const H_=[],U_=e=>Array.isArray(e)?e:[e],W_=e=>e===void 0?H_:[e],G_=e=>e instanceof Error?e.message:String(e),X=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},Z=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??H_};e.out(JSON.stringify(t));return}for(let t of U_(n))e.out(t);for(let t of i??H_)e.errLine(`refs: warning: ${t}`)},K_=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message,...n.reason===void 0?{}:{reason:n.reason}},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},q_=(e,t)=>{e.errLine(`refs: ${t}`)},Q=(e,t,n)=>async()=>{try{await n()}catch(n){let r=we(n,{verbose:t.verbose});K_(e,t,r),process.exitCode=r.exitCode}},J_=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,Y_=(e,t)=>{let n=t.some(e=>e.startsWith(`-`))?[`--`]:[];return[`refs edit`,...e,...n,...t.map(e=>J_(e))].join(` `)},X_=e=>`rm -rf -- ${J_(e)}`,Z_=e=>`rmdir -- ${J_(e)}`,Q_=e=>({path:e.path}),$_=e=>e.filter(e=>e.path!==`.`),ev=e=>e.find(e=>e.path===`.`),tv=e=>{let t=ev(e);return t===void 0?{}:{[t.name]:Q_(t)}},nv=(e,t,n)=>{let r=$_(e),i=tv(e);return r.length>0?{...i,...Object.fromEntries(r.map(e=>[e.name,Q_(e)]))}:n===void 0?i:{...i,[n]:{path:t??`.`}}},rv=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}},iv=(e,t)=>{let n=Object.entries(e);if(n.length!==0)return Object.fromEntries(n.map(([e,n])=>[e,rv(e===t.rootPackageName?ov(n,t.refDescription):n)]))},av=(e,t)=>{let[n]=Object.keys(tv(e));if(n!==void 0)return t[n]?.path===`.`?n:void 0},ov=(e,t)=>({...e,description:t}),sv=(e,t)=>Object.keys(e).filter(e=>e!==t).toSorted(),cv=(e,t,n)=>{if(sv(e,n).length!==0)throw b(`refs add --description cannot describe a package: it has one description, about the repository. Run the two-phase flow instead:
347
347
  refs add ${J_(t)} --dry-run --json > proposal.json\nFill in the ref's own description, and one written from its own source for each package below, then:
348
348
  refs add --proposal proposal.json
349
- packages to describe: ${Object.keys(e).toSorted().join(`, `)}`)},cv=e=>{if(Object.keys(e).length!==0)return e},lv=e=>{let t={default_branch:e.default_branch,description:e.description,url:e.url};return e.packages!==void 0&&(t.packages=e.packages),e.tag_format!==void 0&&(t.tag_format=e.tag_format),t},uv=`ref.`,dv=`${uv}_`,fv=`${dv}_`,pv=e=>`${fv}${ue(`sha256`).update(e,`utf8`).digest(`hex`)}`,mv=e=>{let t=e.includes(`_`)?`${dv}${e.replaceAll(`_`,`_u`).replaceAll(`/`,`_s`)}`:`${uv}${e.replaceAll(`/`,`_`)}`;return Buffer.byteLength(t,`utf8`)<=212&&Rp(t)?t:pv(e)},hv=e=>e.REFS_ALLOW_FILE_URLS===`1`,gv=(e,t)=>{let n=hf(t,{allowFileUrls:hv(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},_v=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);q_(e,`resolving npm package '${t}'…`);let n=await $p(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},vv=(e,t)=>t.startsWith(`npm:`)?_v(e,t.slice(4)):Promise.resolve(gv(e,t)),yv=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Og(`git_transport`,void 0,t);return{...e,cloneUrl:Ef(e.cloneUrl,n)}},bv=e=>`ref '${e}' already exists — use refs edit or refs remove`,xv=(e,t)=>{if(e.refs[t]!==void 0)throw Se(bv(t))},Sv=async e=>{try{return await c(e,{withFileTypes:!0})}catch(e){if(z(e))return;throw e}},Cv=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),wv=async(e,t)=>{let n=await Sv(e);if(n===void 0)return{kind:`stop`};let r=Cv(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}},Tv=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await wv(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):Tv(a.nextDir,i,[...n,r])},Ev=[],Dv=async(e,t)=>{let n=await Tv(e.sourcesDir,t.split(`/`),Ev);if(n!==void 0)throw Se(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},Ov=e=>{switch(e.kind){case`candidate_not_inspected`:case`manifest_missing_name`:case`manifest_unreadable`:case`workspace_dir_unreadable`:return e.path;case`workspace_declaration_unparsed`:case`workspace_file_unreadable`:return e.file;case`unsupported_pattern`:return e.pattern;case`no_workspace_declaration`:return}},kv=e=>e.diagnostics.filter(e=>!Uh({diagnostics:[e],packages:[]})).map(e=>{let t=Ov(e);return t===void 0?e.kind:`${t}: ${e.kind}`}).toSorted().join(`, `),Av=(e,t,n)=>`checkout at ${e} points at '${W(t)}' — expected '${W(n)}'; remove the checkout directory or run refs remove before retrying`,jv=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,Mv=(e,t)=>{try{return hf(e,{allowFileUrls:t}).key}catch{return}},Nv=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=jv(n),i=Mv(t.expectedUrl,t.allowFileUrls),a=Mv(r,t.allowFileUrls);if(i===void 0||a!==i)throw Se(Av(t.dest,r,t.expectedUrl))},Pv=e=>`checkout at ${e} exists but is not refs-managed — remove it (${Y_(e)}) and retry`,Fv=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 Se(Pv(t.dest))},Iv=async(e,t)=>{await a(ie(t.dest),{recursive:!0}),q_(e,`cloning ${W(t.cloneUrl)} into ${t.dest}…`);let n=await xd(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},Lv=async(e,t)=>(nu(t.home,t.dest),U(t.dest)?(await Nv(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await Fv(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Iv(e,t)),Rv=(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`,zv=(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`,Bv=async(e,t)=>{await Nv(e,t),await Fv(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(Rv(t.key,t.dest));let r=n.stdout.trim();if(!Eg.shape.head_sha.safeParse(r).success)throw b(zv(t.key,t.dest,r));return r},Vv=e=>Uh(e)?void 0:`workspace detection could not fully inspect the declared workspaces (${kv(e)}) — members may be missing from the detected packages; the repository's own workspace declaration is what settles it`,Hv=(e,t)=>{let n=tv(e.packages,t.resolved.npmDirectory,t.resolved.npmPkgName),r=iv(e.packages,n),i=Vv(e);return{defaultBranch:t.defaultBranch,...i===void 0?{}:{detectionWarning:i},packages:n,...r===void 0?{}:{rootPackageName:r},tagFormatCandidate:t.tagFormatCandidate}},Uv=async(e,t,n)=>{let r=await Cd(e.runner,t),i=await Ad(e.runner,t),a=Ud(i);q_(e,`detecting workspace packages…`);let o=await C_(t);return Hv(o,{defaultBranch:r,resolved:n,tagFormatCandidate:a})},Wv=(e,t)=>G(t.home,mv(t.resolved.key),async()=>{let n=await Lv(e,{allowFileUrls:hv(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await Uv(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),Gv=(e,t)=>({default_branch:e.defaultBranch,description:``,key:t.key,packages:e.packages,tag_format_candidate:e.tagFormatCandidate,url:t.cloneUrl}),Kv=e=>{let{effectiveMode:t,fields:n,warning:r}=e.cloneResult;return{dest:e.dest,proposal:Gv(n,e.resolved),...n.detectionWarning===void 0?{}:{detectionWarning:n.detectionWarning},...n.rootPackageName===void 0?{}:{rootPackageName:n.rootPackageName},...t===void 0?{}:{effectiveCloneMode:t},...r===void 0?{}:{warning:r}}},qv=async(e,t)=>{let n=B(e.env),r=await H(n),i=yv(await vv(e,t),r.settings);xv(r,i.key),await Dv(n,i.key);let a=V(n,i.key),o=Og(`clone_mode`,void 0,r.settings),s=await Wv(e,{cloneMode:o,dest:a,home:n,resolved:i});return Kv({cloneResult:s,dest:a,resolved:i})},Jv=(e,t,n)=>G(e,`home`,async()=>{let r=await H(e);xv(r,t);let i=await jg(e),a=i.refs[t],o=n??a?.effective_clone_mode,s={...a,pending_proposal_at:new Date().toISOString()};o!==void 0&&(s.effective_clone_mode=o),i.refs[t]=s,await Mg(e,i)}),Yv=(e,t)=>{let n=vl.safeParse(e);if(!n.success)throw b(E(n.error));let r=Dg.safeParse(t);if(!r.success)throw b(E(r.error));return{config:n.data,state:r.data}},Xv=async(e,t)=>{let n=await H(e.home);xv(n,e.ref.key);let r=lv(e.ref);n.refs[e.ref.key]=r;let i=await jg(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Og(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...Yv(n,i),entry:r}},Zv=async(e,t)=>{let n=hv(e.env),r=await G(t.home,mv(t.ref.key),()=>(nu(t.home,t.dest),Bv(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return G(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await Xv(t,r);return await Mg(t.home,i),await uu(t.home,e),{entry:n,key:t.ref.key}})},Qv=(e,t)=>t===`-`?e.readStdin():s(t,`utf8`),$v=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${G_(e)}`)}},ey=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ty=e=>ey(e)&&`ok`in e&&!(`key`in e),ny=e=>{if(!ty(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(ey(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},ry=e=>e.code===`unrecognized_keys`,iy=e=>e.path.length===0,ay=(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}`},oy=e=>{let t=new Map;for(let n of e){let e=Jt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>ay(e,t))},sy=e=>`✖ invalid proposal: ${e.message}`,cy=e=>{let t=e.issues.filter(e=>ry(e)),n=e.issues.filter(e=>!ry(e)),r=n.filter(e=>iy(e));if(t.length===0&&r.length===0)return E(e);let i=n.filter(e=>!iy(e)),a=[...oy(t),...r.map(e=>sy(e))];return i.length>0&&a.push(E({issues:i})),a.join(`
350
- `)},ly=e=>{let t=Tg.safeParse(e);if(!t.success)throw b(cy(t.error));return t.data},uy=async(e,t)=>{let n=await Qv(e,t);return ly(ny($v(n)))},dy=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],fy=e=>[...W_(e.warning),...W_(e.detectionWarning)],py=async(e,t)=>{let n=await qv(e,t),r=B(e.env);await Jv(r,n.proposal.key,n.effectiveCloneMode);let i=fy(n);return{data:n.proposal,human:dy(n.proposal.key,n.dest),warnings:i}},my=e=>[`refs add: '${e}' added to config`],hy=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,url:e.url};e.tag_format_candidate!==null&&(t.tag_format=e.tag_format_candidate);let n=cv(e.packages);return n!==void 0&&(t.packages=n),t},gy=async(e,t)=>{let n=await uy(e,t),r=B(e.env),i=V(r,n.key);if(!U(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=hy(n),{entry:o,key:s}=await Zv(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:my(s),warnings:[]}},_y=(e,t,n)=>{sv(e.proposal.packages,n,e.rootPackageName);let r={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(r.tag_format=e.proposal.tag_format_candidate);let i=rv(e.proposal.packages,{refDescription:t,...e.rootPackageName===void 0?{}:{rootPackageName:e.rootPackageName}});return i!==void 0&&(r.packages=i),r},vy=async(e,t,n)=>{let r=await qv(e,t),i=B(e.env);await Jv(i,r.proposal.key,r.effectiveCloneMode);let a=_y(r,n,t),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await Zv(e,o);return{data:{entry:s,key:c},human:my(c),warnings:fy(r)}},yy=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`)},by=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},xy=(e,t)=>(yy(t),t.proposal===void 0?t.description===void 0?py(e,by(t.source)):vy(e,by(t.source),t.description):gy(e,t.proposal)),Sy=(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},Cy=(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=X(r);return Q(t,i,async()=>{let r=await xy(t,Sy(e,n));Z(t,i,r.human,r.data,r.warnings)})()})},wy=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`}},Ty=/^v(?<major>\d+)\.(?<minor>\d+)/u,Ey=e=>{let t=Ty.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},Dy=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,Oy=e=>{let{nodeVersion:t}=e;return Dy(Ey(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},ky=()=>vl.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),Ay=async e=>{try{return{config:await H(e)}}catch(e){return{config:ky(),errorMessage:G_(e)}}},jy=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},My={ci:`update check is off in CI — set REFS_UPDATE_CHECK=1 to run it here anyway`,config:`update check is off ([updates].check = false in config.toml)`,env:`update check is off (REFS_UPDATE_CHECK=0)`},Ny=(e,t,n)=>{if(Wg(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${Gg(e,t)}${r}`,name:`cli-update`,status:`warn`}}return n?{detail:`could not reach npm to check; its last answer was ${t}, which this CLI (${e}) already has`,name:`cli-update`,status:`warn`}:{detail:`this CLI (${e}) is npm's latest published release`,name:`cli-update`,status:`ok`}},Py=async(e,t)=>{let n=Yg({env:e.env,updates:t.updates});if(n!==`on`)return{detail:My[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await Ug({fetch:e.fetcher,home:B(e.env),nowMs:Date.now()});return r===void 0?{detail:`could not reach npm to learn the latest published version — not a fault of your setup, and nothing else depends on it`,name:`cli-update`,status:`warn`}:Ny(e.cliVersion,r,i)},Fy=(e,t)=>Object.keys(t.refs).map(e=>rl.parse(e)).map(t=>({dest:V(e,t),key:t})).filter(e=>U(e.dest)),Iy=[`pre-commit`,`pre-push`],Ly=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},Ry=async e=>{let t=await Promise.all(Iy.map(t=>Ly(e,t)));return Iy.filter((e,n)=>!t[n])},zy=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},By=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:`${Iy.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},Vy=async(e,t,n)=>{let r=Fy(t,n),[i,a]=await Promise.all([Ry(t),Promise.all(r.map(n=>zy(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return By({badKeys:o,checkoutCount:r.length,missingHooks:i})},Hy=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}},Uy=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`}},Wy=async(e,t,n)=>{let r=Fy(t,n),i=await Promise.all(r.map(t=>Hy(e,t)));return Uy(i)},Gy=async e=>{try{return await jg(e)}catch{return Dg.parse({})}},Ky=async e=>{try{return(await c(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(z(e))return[];throw e}},qy=async(e,t)=>{if(U(e))return[[...t]];let n=await Ky(e);return(await Promise.all(n.map(n=>qy(m(e,n),[...t,n])))).flat()},Jy=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},Yy=(e,t,n)=>Jy(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: ${Y_(e.dest)}`,Xy=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),Zy=async(e,t,n)=>{let r=(await qy(e.sourcesDir,[])).map(t=>Xy(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=>Yy(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},Qy=e=>e!==`unmaterialized`&&e!==`verified`,$y=new Set([`ambiguous`,`missing`,`relocated`,`unregistered`]),eb=(e,t)=>{let[n]=e;if(n===void 0)return t===void 0?{status:`ok`}:{discovery_incomplete:t,status:`unknown`};let r={packages:[...e],status:e.some(e=>$y.has(e.status))?`drift`:`unknown`};return t!==void 0&&(r.discovery_incomplete=t),r},tb=`(unknown)`,nb=e=>Gc(e.name)&&ll.safeParse(e.path).success,rb=(e,t)=>{let n=`${e.name}: declared in this checkout but not registered — it cannot be resolved by name until it is`;return e.path===void 0?`${n}. Declared at several paths (${(e.candidates??[]).join(`, `)}) — pick one`:nb(e)?`${n}. To register it: refs edit ${J_(t)} --package ${J_(e.name)} --create --path ${J_(e.path)} --description "<what it is>"`:`${n}. Its name or path is one the configuration cannot hold, so there is no command for it — report it and leave it unregistered`},ib=e=>{let t=`configured: ${e.configured_path??tb}`;if(e.status===`relocated`)return`${e.name}: moved to ${e.path??tb} — update the entry's path (${t})`;if(e.status===`missing`)return`${e.name}: gone from this repo's workspaces — remove the entry, or repoint it if it moved out of them (${t})`;if(e.status===`ambiguous`){let n=(e.candidates??[]).join(`, `);return`${e.name}: declared at several paths (${n}) — point the entry at one (${t})`}return`${e.name}: could not be checked — ${e.reason??`(no reason given)`} (${t})`},ab=(e,t)=>e.status===`unregistered`?rb(e,t):ib(e),ob=e=>`could not check for unregistered packages — ${e}`,sb=(e,t)=>{if(e.reason!==void 0)return[`could not be checked — ${e.reason}`];let n=(e.packages??[]).map(e=>ab(e,t));return e.discovery_incomplete===void 0?n:[...n,ob(e.discovery_incomplete)]},cb=e=>{let t;return()=>(t??=C_(e),t)},lb=async(e,t,n)=>{let r=await l_(e);if(r===void 0||t.some(e=>e.packageName===r.name))return{issues:[]};let i=await n();if(!Uh(i))return{incomplete:kv(i),issues:[]};let a=$h(i.packages,r.name);return a.kind===`ambiguous`?{issues:[{candidates:a.paths,name:r.name,status:`unregistered`}]}:{issues:a.kind===`found`?[{name:r.name,path:a.path,status:`unregistered`}]:[]}},ub=e=>{let t=new Map;for(let n of e)t.set(n.name,[...t.get(n.name)??[],n.path]);return t},db=(e,t)=>{let n=new Set(e.changedDirs),r=t.filter(e=>!n.has(e.path)).map(e=>e.name);return new Set([...e.namesBefore,...r])},fb=(e,t)=>t.length===1&&t[0]!==void 0?{name:e,path:t[0],status:`unregistered`}:{candidates:[...t],name:e,status:`unregistered`},pb=async(e,t,n)=>{if(t.kind===`arrivals`&&t.changedDirs.length===0)return{issues:[]};let r=await n();if(!Uh(r))return{incomplete:kv(r),issues:[]};let i=new Set(e.map(e=>e.packageName)),a=r.packages.filter(e=>e.path!==`.`),o=t.kind===`all`?void 0:db(t,a);return{issues:[...ub(a)].filter(([e])=>!i.has(e)).filter(([e])=>o===void 0||!o.has(e)).map(([e,t])=>fb(e,t)).toSorted((e,t)=>e.name.localeCompare(t.name))}},mb=(e,t)=>({path:e.configuredPath,reason:t,status:`unverifiable`}),hb=(e,t)=>Wh(t)?{configuredPath:e.configuredPath,path:null,status:`missing`}:mb(e,`this repo declares no workspaces, so there was nowhere to search`),gb=(e,t)=>t===e.configuredPath,_b=e=>e.packages.filter(e=>e.path!==`.`),vb=(e,t)=>{let n=$h(_b(t),e.packageName);return n.kind===`ambiguous`?{candidates:n.paths,configuredPath:e.configuredPath,path:null,status:`ambiguous`}:Uh(t)?n.kind===`absent`?hb(e,t):gb(e,n.path)?mb(e,`the checkout changed while it was being inspected`):{configuredPath:e.configuredPath,path:n.path,status:`relocated`}:mb(e,n.kind===`found`?`workspace detection was incomplete, so the new location is not confirmed unique`:`workspace detection was incomplete`)},yb=e=>{let t=new Map(Object.entries(e??{}));return[...t.keys()].toSorted().flatMap(e=>{let n=t.get(e);return n===void 0?[]:[{configuredPath:n.path,packageName:e}]})},bb=async(e,t)=>{let n=await Xh(e,t.configuredPath,t.packageName);if(n.kind===`match`)return{path:t.configuredPath,status:`verified`};if(n.kind===`unreadable`)return{path:t.configuredPath,reason:n.reason,status:`unverifiable`}},xb=e=>e.flatMap(e=>e.settled===void 0?[]:[{outcome:e.settled,query:e.query}]),Sb=async(e,t,n)=>{let r=await Promise.all(t.map(async t=>({query:t,settled:await bb(e,t)})));if(r.every(e=>e.settled!==void 0))return xb(r);let i=await n();return r.map(e=>({outcome:e.settled??vb(e.query,i),query:e.query}))},Cb=e=>{let{outcome:t,query:n}=e;return Qy(t.status)?[{...t.candidates===void 0?{}:{candidates:t.candidates},configured_path:n.configuredPath,name:n.packageName,...t.status===`relocated`&&t.path!==null?{path:t.path}:{},...t.reason===void 0?{}:{reason:t.reason},status:t.status}]:[]},wb=(e,t)=>{let n=new Set(e.map(e=>e.name));return[...e,...t.filter(e=>!n.has(e.name))]},Tb=async(e,t,n)=>{let r=yb(t),[i]=r;if(i===void 0)return{status:`ok`};let a=cb(e);try{let[t,i,o]=await Promise.all([Sb(e,r,a),lb(e,r,a),pb(r,n,a)]);return eb([...t.flatMap(e=>Cb(e)),...wb(i.issues,o.issues)],o.incomplete??i.incomplete)}catch(e){return{reason:G_(e),status:`unknown`}}},Eb=async(e,t,n)=>{try{return await G(e,mv(n.key),()=>Tb(n.dest,t.refs[n.key]?.packages,{kind:`all`}),{timeoutMs:100})}catch(e){if(e instanceof _&&e.code===`conflict`)return{reason:`another refs process is holding this ref`,status:`unknown`};throw e}},Db=`config-drift`,Ob=(e,t)=>{let[n]=e;return n===void 0?{detail:`every configured package path resolves in ${t} checkout(s)`,name:Db,status:`ok`}:{detail:e.join(`; `),name:Db,status:`warn`}},kb=async(e,t,n)=>{let[r,...i]=n;if(r===void 0)return[];let a=await Eb(e,t,r),o=await kb(e,t,i);return[...sb(a,r.key).map(e=>`${r.key}: ${e}`),...o]},Ab=async(e,t)=>{let n=Fy(e,t);return Ob(await kb(e,t,n),n.length)},jb=e=>{let{diagnosis:t}=e;return e.kind===`claim`||!e.isDirectory||t.pidState===`definitely-dead`||t.stale||t.meta===`malformed`||t.meta===`unreadable`||t.policy===`unknown`?!1:t.ageMs===void 0||t.ageMs>=0},Mb=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return r===`unknown`?`, state could not be read`:t===void 0||n===void 0?``:t<0?`, recorded time is in the future — check the system clock`:`, ${xp(t)} into a ${xp(n)} window`},Nb=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} present`,Pb=(e,t)=>{let n=m(e.locksDir,ap,t.name),r=t.diagnosis.ageMs===void 0?``:` for ${xp(t.diagnosis.ageMs)}`;return`steal claim on ${t.name}: present${r}. Stealing this lock is blocked while it is here. A reclaim in progress clears it within a moment; if it stays, ${Fb}: ${X_(n)}`},Fb=`stop every refs process using this home — including suspended ones — and then run`,Ib=(e,t)=>{let{diagnosis:n}=t;if($f(n))return`, reclaimable now`;if(!n.stale&&t.isDirectory)return``;let r=m(e.locksDir,t.name);return`, not automatically reclaimable — if it is genuinely abandoned, ${Fb}: ${Y_(r)}`},Lb=(e,t)=>{let{diagnosis:n}=t,r=t.isDirectory?``:`not a directory, `,i=Ib(e,t);return`${t.name}: ${r}${Nb(n)}${Mb(n)}${i}`},Rb=async e=>{let t=await bp(e),[n]=t;return n===void 0?{detail:`no locks held`,name:`locks`,status:`ok`}:{detail:t.map(t=>t.kind===`claim`?Pb(e,t):Lb(e,t)).join(`; `),name:`locks`,status:t.every(e=>jb(e))?`ok`:`warn`}},zb=[`.agents`,`skills`,`refs`,`SKILL.md`],Bb=[`skills`,`refs`,`SKILL.md`],Vb=[`.claude`,`skills`,`refs`,`SKILL.md`],Hb=`npx skills add kaisers-io/refs`,Ub=`npm i -g @kaisers-io/refs@latest`,Wb=(e,t)=>e===void 0?void 0:{display:t,path:e},Gb=e=>{let{dirName:t,env:n,home:r,overrideName:i}=e,a=n[i]?.trim();return a!==void 0&&a.length>0?{display:a,path:a}:Wb(r===void 0?void 0:m(r,t),`~/${t}`)},Kb=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:Wb(t,`~/.agents`),segments:zb},{label:`Claude Code`,root:Gb({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:Bb},{label:`Codex`,root:Gb({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:Bb},{label:`project ./.agents`,root:Wb(e.cwd,`./.agents`),segments:zb},{label:`project ./.claude`,root:Wb(e.cwd,`./.claude`),segments:Vb}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:m(t.path,...n)}])},qb=async(e,t)=>{try{let n=await l(e);return{label:t,realPath:n,source:await s(n,`utf8`)}}catch{return}},Jb=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Yb=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,Xb=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,Zb=e=>{let t=Yb.exec(e)?.groups?.body;if(t!==void 0)return Xb.exec(t)?.groups?.version},Qb=(e,t)=>{if(e===t)return`match`;let n=Ig(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},$b={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${Ub}`,match:(e,t)=>`the refs skill is installed and matches this CLI (${t})`,"skill-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the skill: ${Hb}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${Ub} and ${Hb}`},ex=e=>{let{cliVersion:t,label:n,skillVersion:r}=e;if(r===void 0)return{detail:`the refs skill (${n}) predates the version gate — update it: ${Hb}`,name:`skill`,status:`warn`};let i=Qb(r,t);return{detail:`${n}: ${$b[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},tx=e=>({detail:`refs skill not found in the locations this check knows about (${e.map(e=>e.display).join(`, `)}) — an install anywhere else is invisible here and still works; if it really is missing: ${Hb}`,name:`skill`,status:`warn`}),nx=async e=>{let t=Kb(e),n=await Promise.all(t.map(e=>qb(e.path,e.label))),r=Jb(n.filter(e=>e!==void 0)).map(t=>ex({cliVersion:e.cliVersion,label:t.label,skillVersion:Zb(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??tx(t)},rx=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,ix=e=>e===``?{}:{user:e},ax=e=>e===``?{}:{port:e},ox=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...ix(t.username),...ax(t.port)}:void 0}catch{return}},sx=e=>{let t=rx.exec(e),n=t?.groups?.host;return n===void 0?ox(e):{host:n,user:t?.groups?.user??`git`}},cx=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,lx=e=>e.user===void 0?cx(e):`${e.user}@${cx(e)}`,ux=e=>{let t=Object.values(e.refs).map(e=>sx(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(lx(e),e);return[...n.values()].toSorted((e,t)=>lx(e).localeCompare(lx(t)))},dx=/Permission denied/u,fx=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],px=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,mx=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=px(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},hx=async(e,t,n)=>{let r=lx(t),i=await e.runner.run(`ssh`,mx(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:dx.test(i.stderr)?{host:r,outcome:`denied`}:fx.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},gx=(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`}},_x=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`}},vx=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`}},yx=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),bx=(e,t)=>gx(e,t)??_x(e)??vx(e)??yx(e),xx=async(e,t,n)=>{let r=ux(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>hx(e,t,i)));return bx(a,i)},Sx=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${G_(t)}`,name:e.name,status:`fail`}}},Cx=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await Sx(t),i=await Cx(n);return r===void 0?i:[r,...i]},wx=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>wy(n)},{name:`node`,run:()=>Promise.resolve(Oy(n))},{name:`config`,run:()=>Promise.resolve(jy(t.errorMessage))},{name:`hooks-guard`,run:()=>Vy(n,r,t.config)},{name:`dirty-checkouts`,run:()=>Wy(n,r,t.config)},{name:`config-drift`,run:()=>Ab(r,t.config)},{name:`orphans`,run:()=>Zy(r,t.config,i)},{name:`locks`,run:()=>Rb(r)},{name:`skill`,run:()=>nx(n)},{name:`cli-update`,run:()=>Py(n,t.config)},{name:`ssh-auth`,run:()=>xx(n,t.config)}]},Tx=async e=>{let t=B(e.env),n=await Ay(t),r=await Gy(t);return Cx(wx({configLoad:n,ctx:e,home:t,state:r}))},Ex={fail:`FAIL`,ok:`OK`,warn:`WARN`},Dx=e=>e.map(e=>`[${Ex[e.status]}] ${e.name}: ${e.detail}`),Ox=e=>e.some(e=>e.status===`fail`),kx=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, drift, locks, ssh).`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let e=await Tx(t);Z(t,r,Dx(e),{checks:e}),Ox(e)&&(process.exitCode=g.UNEXPECTED)})()})},Ax=(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},jx=(e,t)=>{if(!U(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},Mx=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},Nx=`never`,Px=(e,t,n)=>e===void 0||n-Date.parse(e)>t,Fx=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,Ix=(e,t)=>{if(e===void 0)return Nx;let n=t-Date.parse(e);if(Number.isNaN(n))return Nx;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return Fx(i,`minute`);let a=Math.floor(i/60);if(a<24)return Fx(a,`hour`);let o=Math.floor(a/24);return o<365?Fx(o,`day`):Fx(Math.floor(o/365),`year`)},Lx=e=>{let t=Ix(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==Nx&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},Rx=(e,t,n)=>{let r=e.state.refs[t],i=al(Og(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:Og(`clone_mode`,n,e.settings),description:n.description,key:t,...r?.last_fetched_at===void 0?{}:{last_fetched_at:r.last_fetched_at},missing:!U(V(e.home,rl.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:Px(r?.last_fetched_at,i,e.now)}},zx=e=>{let t={home:e.home,includePackages:e.includePackages,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>Rx(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},Bx=async(e,t,n)=>{let r=B(e.env),i=await H(r),a=await jg(r);return zx({config:i,home:r,includePackages:t,now:n,state:a})},Vx=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...Lx({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],Hx=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...Vx(n,t)),e),[]),Ux=e=>e.split(`/`),Wx=(e,t)=>{let n=Ux(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Gx=(e,t)=>{if(Object.hasOwn(e.refs,t))return rl.parse(t);let n=Ux(t),r=Object.keys(e.refs).filter(e=>Wx(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 rl.parse(i)},Kx=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).option(`--packages`,`include each ref's package names in --json output (off by default)`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let n=Date.now(),i=await Bx(t,e.packages===!0,n);Z(t,r,Hx(i,n),i)})()})},qx=e=>e===void 0?null:e,Jx=()=>Object.keys(pl.shape).toSorted().join(`, `),Yx=e=>`unknown package field '${e}' — valid fields: ${Jx()}`,Xx=e=>Object.hasOwn(pl.shape,e),Zx=(e,t,n)=>{if(!Xx(t))throw y(Yx(t));let r=e[t],i=pl.safeParse({...e,[t]:n});if(!i.success)throw b(E(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},Qx=async e=>{let t=Mx(e.entry,e.key,e.packageName),n=Zx(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await uu(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:qx(n.newValue),old:qx(n.oldValue)}},$x=(e,t)=>`package '${e}' is already registered on ref '${t}' — edit its fields instead`,eS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n),r=Gx(e,t.query),i=Ax(e,r);if(Object.hasOwn(i.packages??{},t.packageName))throw b($x(t.packageName,r));let a=ml.safeParse({...i,packages:{...i.packages,[t.packageName]:{description:t.description,path:t.path}}});if(!a.success)throw b(E(a.error));return await uu(n,{...e,refs:{...e.refs,[r]:a.data}}),{created:!0,field:`packages`,key:r,new:{description:t.description,name:t.packageName,path:t.path},old:null}})},tS=`packages`,nS=()=>Object.keys(ml.shape).filter(e=>e!==tS).toSorted().join(`, `),rS=e=>`unknown ref field '${e}' — valid fields: ${nS()}`,iS=e=>Object.hasOwn(ml.shape,e),aS=(e,t,n)=>`failed to rewrite git remote at ${e} to '${W(t)}': ${n.trim()}`,oS=async(e,t)=>{if(nu(t.home,t.dest),!U(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(aS(t.dest,t.cloneUrl,n.stderr))},sS=async(e,t)=>{let n=hf(t.value,{allowFileUrls:hv(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=V(t.home,t.key);return await oS(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},cS=(e,t,n)=>{let r={...e,[t]:n},i=ml.safeParse(r);if(!i.success)throw b(E(i.error));return i.data},lS=(e,t)=>t.field===`url`?sS(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(cS(t.entry,t.field,t.value)),uS=async(e,t)=>{let{field:n}=t;if(n===tS)throw y(`use --package <name> <field> <value>`);if(!iS(n))throw y(rS(n));let r=t.entry[n],i=await lS(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},dS=(e,t)=>{let n=B(e.env),{field:r,opts:i,query:a,value:o}=t;return G(n,`home`,async()=>{let t=await H(n),s=Gx(t,a),c=Ax(t,s);if(i.packageName!==void 0)return Qx({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await uS(e,{entry:c,field:r,home:n,key:s,value:o});return await uu(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:qx(l.new),old:qx(l.old)}})},fS=`settings`,pS=[],mS=()=>Object.keys(dl.shape).toSorted().join(`, `),hS=e=>`unknown setting '${e}' — valid settings: ${mS()}`,gS=e=>Object.hasOwn(dl.shape,e),_S=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,vS=e=>{try{let t=Gx(e,fS);return[_S(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[_S("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return pS;throw e}},yS=e=>({data:{field:e.key,key:fS,new:qx(e.parsed[e.key]),old:qx(e.old)},warnings:vS(e.config)}),bS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n);if(!gS(t.key))throw y(hS(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=dl.safeParse(i);if(!a.success)throw b(E(a.error));return await uu(n,{...e,settings:a.data}),yS({config:e,key:t.key,old:r,parsed:a.data})})},xS=[],SS=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},CS=e=>{let{description:t,path:n}=e.create,{packageName:r}=e.opts;if(r===void 0||t===void 0||n===void 0||e.second!==void 0||e.value!==void 0)throw y(`--create registers a new package: it needs --package <name>, --path <path> and --description <text>, and takes no <field> <value> arguments`);return{description:t,packageName:r,path:n}},wS=e=>{if(e.second===void 0||e.value===void 0)throw y(`missing <field> and <value> — see 'refs edit --help'`);return{field:e.second,value:e.value}},TS=async(e,t)=>{let{description:n,packageName:r,path:i}=CS(t);return{data:await eS(e,{description:n,packageName:r,path:i,query:t.first}),warnings:xS}},ES=(e,t,n)=>{if(t.opts.packageName!==void 0)throw y(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return bS(e,n)},DS=async(e,t)=>{if(t.create.create===!0)return TS(e,t);if(t.create.description!==void 0||t.create.path!==void 0)throw y(`--path and --description only apply to --create — to change one field of a registered package use: refs edit <ref> <field> <value> --package <name>`);let{field:n,value:r}=wS(t);return t.first===`settings`?ES(e,t,{key:n,value:r}):{data:await dS(e,{field:n,opts:t.opts,query:t.first,value:r}),warnings:xS}},OS=e=>e==null?`(unset)`:String(e),kS=e=>{if(e.created===!0){let t=e.new;return[`${e.key}: registered '${t.name}' at ${t.path}`]}return[`${e.key}: ${e.field} '${OS(e.old)}' -> '${OS(e.new)}'`]},AS=(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. With --create, registers a package the config does not have yet.`).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`).option(`--create`,`register --package as a new package on this ref`).option(`--path <path>`,`with --create: the package path, relative to the checkout root`).option(`--description <text>`,`with --create: what the package is`).action((e,n,r,i,a)=>{let o=X(a);return Q(t,o,async()=>{let{data:a,warnings:s}=await DS(t,{create:i,first:e,opts:SS(i),second:n,value:r});Z(t,o,kS(a),a,s)})()})},jS=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,MS={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},NS=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})},PS=async e=>{let t=B(e.env);return await NS(t),{config:await G(t,`home`,async()=>{let e=await bu(t,w_);return await Nd(t),e}),home:t.root,skill_hint:jS}},FS=(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=X(n);return Q(t,r,async()=>{let e=await PS(t);Z(t,r,[`home: ${e.home}`,`config: ${MS[e.config]}`,``,jS],e)})()})},IS=async e=>{let t=B(e.env),n=await G(t,`home`,()=>bu(t,w_));return n===`migrated`?{backup:Ql(t),result:n}:{backup:null,result:n}},LS=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${re(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,RS=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let e=await IS(t);Z(t,r,LS(e),e)})()})},zS=async e=>{try{return await i(e),!0}catch(e){if(z(e))return!1;throw e}},BS=async e=>{try{return await c(e)}catch(e){if(z(e))return;throw e}},VS=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(z(e))return;throw e}},HS=async e=>{let t=await BS(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await f(e)}catch(e){if(!z(e))throw e}return!0},US=async e=>{let t=await VS(e);return t===void 0?!0:t?HS(e):!1},WS=async(e,t)=>{t!==e.sourcesDir&&await US(t)&&await WS(e,ie(t))},GS=async(e,t)=>await zS(t)?(nu(e,t),await d(t,{force:!0,recursive:!0}),await WS(e,ie(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},KS=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),qS=async(e,t)=>{let n=await H(e),r={...n,refs:KS(n.refs,t)};await uu(e,r);let i=await jg(e),a={...i,refs:KS(i.refs,t)};await Mg(e,a)},JS=async(e,t)=>{let n=B(e.env),r=await H(n),i=Gx(r,t),a=V(n,i),{removedCheckout:o,warning:s}=await G(n,mv(i),()=>GS(n,a));return await G(n,`home`,()=>qS(n,i)),{data:{key:i,removed_checkout:o},warnings:W_(s)}},YS=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],XS=(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=X(r);return Q(t,i,async()=>{let{data:n,warnings:r}=await JS(t,e);Z(t,i,YS(n),n,r)})()})},ZS=async e=>{let t=await Xh(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:QS(e)},QS=async e=>vb(e,await C_(e.checkoutDir)),$S=async e=>{try{return await G(e.home,mv(e.key),()=>ZS(e),e.lockTimeoutMs===void 0?void 0:{timeoutMs:e.lockTimeoutMs})}catch(t){if(t instanceof _&&t.code===`conflict`)return{path:e.configuredPath,reason:`could not acquire the ref lock in time`,status:`unverifiable`};throw t}},eC=async e=>{if(!U(e.checkoutDir))return{path:e.configuredPath,status:`unmaterialized`};let t=await Xh(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:(e.onProbed?.(),$S(e))},tC=(e,t)=>({local_path:null,name:e,path:null,reason:t,status:`unverifiable`}),nC=async e=>{if(!e.checkoutManaged)return tC(e.packageName,e.checkoutReason);let t=await eC(e);return{...t.candidates===void 0?{}:{candidates:t.candidates},...t.configuredPath===void 0?{}:{configured_path:t.configuredPath},local_path:t.path===null?null:m(e.checkoutDir,t.path),name:e.packageName,path:t.path,...t.reason===void 0?{}:{reason:t.reason},status:t.status}},rC=e=>[`package: ${e.name}`,`package path: ${e.local_path??`(unknown)`}`,...e.status===`verified`?[]:[`package status: ${e.status}`],...e.configured_path===void 0?[]:[`configured path: ${e.configured_path}`],...e.candidates===void 0?[]:[`candidates: ${e.candidates.join(`, `)}`],...e.reason===void 0?[]:[`reason: ${e.reason}`]],iC=`node_modules`,aC=[`.pnp.cjs`,`.pnp.js`],oC=new Set([``,`.`,`..`]),sC=e=>!ae(e)&&!e.includes(`\\`)&&e.split(`/`).every(e=>!oC.has(e)),cC=function*(e){let t=ce(e);for(;;){re(t)!==iC&&(yield m(t,iC));let e=ie(t);if(e===t)return;t=e}},lC=async e=>{if(await fC(e)!==`absent`)try{let t=JSON.parse(await s(e,`utf8`)),{name:n,version:r}=typeof t==`object`&&t?t:{};return typeof r!=`string`||r===``?{package_json:e,reason:`manifest_has_no_version`,status:`unverifiable`}:{...typeof n==`string`?{name:n}:{},package_json:e,status:`found`,version:r}}catch{return{package_json:e,reason:`manifest_unreadable`,status:`unverifiable`}}},uC=new Set([`ENOENT`,`ENOTDIR`]),dC=async e=>{try{return(await c(e)).length===0}catch{return!1}},fC=async e=>{try{return await p(e),`present`}catch(e){let t=typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0;return t!==void 0&&uC.has(t)?`absent`:`unreadable`}},pC=async e=>{for(let t of cC(e)){let e=ie(t);if((await Promise.all(aC.map(t=>fC(m(e,t))))).includes(`present`))return!0}return!1},mC=async e=>{try{if(!(await p(e)).isDirectory())throw y(`--project must be a directory: ${e}`)}catch(t){throw t instanceof Error&&t.message.startsWith(`--project`)?t:y(`--project path does not exist: ${e}`)}},hC=async e=>{let t=await fC(e);if(t===`unreadable`)return{reason:`slot_unreadable`,status:`unverifiable`};if(t===`absent`)return;let n=await lC(m(e,`package.json`));return n===void 0?await dC(e)?void 0:{reason:`installed_without_manifest`,status:`unverifiable`}:n},gC=async(e,t)=>{if(!sC(t))return{reason:`unsupported_package_name`,status:`unverifiable`};for(let n of cC(e)){let e=await hC(m(n,...t.split(`/`)));if(e!==void 0)return e}return await pC(e)?{reason:`yarn_pnp`,status:`unsupported_layout`}:{status:`not_materialized`}},_C={'"':`"`,"\\":`\\`,b:`\b`,n:`
351
- `,t:` `},vC={'"':`"`,"\\":`\\`},yC=new Set([` `,` `]),$=Symbol(`malformed git config`),bC=e=>e!==void 0&&!e.quoted&&yC.has(e.char),xC=e=>{let t=0,n=e.length;for(;t<n&&bC(e[t]);)t+=1;for(;n>t&&bC(e[n-1]);)--n;return e.slice(t,n).map(e=>e.char).join(``)},SC=e=>{let t=[],n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`\\`){r+=1;let n=_C[e[r]??``];if(n===void 0)return $;t.push({char:n,quoted:!0})}else if(i===`"`)n=!n;else if(!n&&(i===`#`||i===`;`))return xC(t);else t.push({char:i??``,quoted:n})}return n?$:xC(t)},CC=e=>{let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`\\`){n+=1;let r=vC[e[n]??``];if(r===void 0)return $;t+=r}else t+=r??``}return t},wC=/^[ \t]+|[ \t]+$/gu,TC=e=>e.replace(wC,``),EC=/^\[[ \t]*(?<section>[A-Za-z0-9.-]+)[ \t]*(?:"(?<subsection>(?:[^"\\]|\\.)*)")?[ \t]*\]/u,DC=/^(?<name>[A-Za-z][A-Za-z0-9-]*)[ \t]*(?:=[ \t]*(?<value>.*))?$/u,OC=function*(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`
349
+ packages to describe: ${Object.keys(e).toSorted().join(`, `)}`)},lv=e=>{if(Object.keys(e).length!==0)return e},uv=e=>{let t={default_branch:e.default_branch,description:e.description,url:e.url};return e.packages!==void 0&&(t.packages=e.packages),e.tag_format!==void 0&&(t.tag_format=e.tag_format),t},dv=`ref.`,fv=`${dv}_`,pv=`${fv}_`,mv=e=>`${pv}${ue(`sha256`).update(e,`utf8`).digest(`hex`)}`,hv=e=>{let t=e.includes(`_`)?`${fv}${e.replaceAll(`_`,`_u`).replaceAll(`/`,`_s`)}`:`${dv}${e.replaceAll(`/`,`_`)}`;return Buffer.byteLength(t,`utf8`)<=212&&Rp(t)?t:mv(e)},gv=e=>e.REFS_ALLOW_FILE_URLS===`1`,_v=(e,t)=>{let n=hf(t,{allowFileUrls:gv(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},vv=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);q_(e,`resolving npm package '${t}'…`);let n=await $p(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},yv=(e,t)=>t.startsWith(`npm:`)?vv(e,t.slice(4)):Promise.resolve(_v(e,t)),bv=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Dg(`git_transport`,void 0,t);return{...e,cloneUrl:Ef(e.cloneUrl,n)}},xv=e=>`ref '${e}' already exists — use refs edit or refs remove`,Sv=(e,t)=>{if(e.refs[t]!==void 0)throw Se(xv(t))},Cv=async e=>{try{return await c(e,{withFileTypes:!0})}catch(e){if(z(e))return;throw e}},wv=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),Tv=async(e,t)=>{let n=await Cv(e);if(n===void 0)return{kind:`stop`};let r=wv(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}},Ev=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await Tv(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):Ev(a.nextDir,i,[...n,r])},Dv=[],Ov=async(e,t)=>{let n=await Ev(e.sourcesDir,t.split(`/`),Dv);if(n!==void 0)throw Se(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},kv=e=>{switch(e.kind){case`candidate_not_inspected`:case`manifest_missing_name`:case`manifest_unreadable`:case`workspace_dir_unreadable`:return e.path;case`workspace_declaration_unparsed`:case`workspace_file_unreadable`:return e.file;case`unsupported_pattern`:return e.pattern;case`no_workspace_declaration`:return}},Av=e=>e.diagnostics.filter(e=>!Hh({diagnostics:[e],packages:[]})).map(e=>{let t=kv(e);return t===void 0?e.kind:`${t}: ${e.kind}`}).toSorted().join(`, `),jv=(e,t,n)=>`checkout at ${e} points at '${W(t)}' — expected '${W(n)}'; remove the checkout directory or run refs remove before retrying`,Mv=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,Nv=(e,t)=>{try{return hf(e,{allowFileUrls:t}).key}catch{return}},Pv=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=Mv(n),i=Nv(t.expectedUrl,t.allowFileUrls),a=Nv(r,t.allowFileUrls);if(i===void 0||a!==i)throw Se(jv(t.dest,r,t.expectedUrl))},Fv=e=>`checkout at ${e} exists but is not refs-managed — remove it (${X_(e)}) and retry`,Iv=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 Se(Fv(t.dest))},Lv=async(e,t)=>{await a(ie(t.dest),{recursive:!0}),q_(e,`cloning ${W(t.cloneUrl)} into ${t.dest}…`);let n=await xd(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},Rv=async(e,t)=>(nu(t.home,t.dest),U(t.dest)?(await Pv(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await Iv(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Lv(e,t)),zv=(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`,Bv=(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`,Vv=async(e,t)=>{await Pv(e,t),await Iv(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(zv(t.key,t.dest));let r=n.stdout.trim();if(!Tg.shape.head_sha.safeParse(r).success)throw b(Bv(t.key,t.dest,r));return r},Hv=e=>Hh(e)?void 0:`workspace detection could not fully inspect the declared workspaces (${Av(e)}) — members may be missing from the detected packages; the repository's own workspace declaration is what settles it`,Uv=(e,t)=>{let n=nv(e.packages,t.resolved.npmDirectory,t.resolved.npmPkgName),r=av(e.packages,n),i=Hv(e);return{defaultBranch:t.defaultBranch,...i===void 0?{}:{detectionWarning:i},packages:n,...r===void 0?{}:{rootPackageName:r},tagFormatCandidate:t.tagFormatCandidate}},Wv=e=>e.complete?Ud(e.tags):null,Gv=async(e,t,n)=>{let r=await Cd(e.runner,t),i=await Nd(e.runner,t),a=Wv(i);q_(e,`detecting workspace packages…`);let o=await C_(t);return Uv(o,{defaultBranch:r,resolved:n,tagFormatCandidate:a})},Kv=(e,t)=>G(t.home,hv(t.resolved.key),async()=>{let n=await Rv(e,{allowFileUrls:gv(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await Gv(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),qv=(e,t)=>({default_branch:e.defaultBranch,description:``,key:t.key,packages:e.packages,tag_format_candidate:e.tagFormatCandidate,url:t.cloneUrl}),Jv=e=>{let{effectiveMode:t,fields:n,warning:r}=e.cloneResult;return{dest:e.dest,proposal:qv(n,e.resolved),...n.detectionWarning===void 0?{}:{detectionWarning:n.detectionWarning},...n.rootPackageName===void 0?{}:{rootPackageName:n.rootPackageName},...t===void 0?{}:{effectiveCloneMode:t},...r===void 0?{}:{warning:r}}},Yv=async(e,t)=>{let n=B(e.env),r=await H(n),i=bv(await yv(e,t),r.settings);Sv(r,i.key),await Ov(n,i.key);let a=V(n,i.key),o=Dg(`clone_mode`,void 0,r.settings),s=await Kv(e,{cloneMode:o,dest:a,home:n,resolved:i});return Jv({cloneResult:s,dest:a,resolved:i})},Xv=(e,t,n)=>G(e,`home`,async()=>{let r=await H(e);Sv(r,t);let i=await Ag(e),a=i.refs[t],o=n??a?.effective_clone_mode,s={...a,pending_proposal_at:new Date().toISOString()};o!==void 0&&(s.effective_clone_mode=o),i.refs[t]=s,await jg(e,i)}),Zv=(e,t)=>{let n=vl.safeParse(e);if(!n.success)throw b(E(n.error));let r=Eg.safeParse(t);if(!r.success)throw b(E(r.error));return{config:n.data,state:r.data}},Qv=async(e,t)=>{let n=await H(e.home);Sv(n,e.ref.key);let r=uv(e.ref);n.refs[e.ref.key]=r;let i=await Ag(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Dg(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...Zv(n,i),entry:r}},$v=async(e,t)=>{let n=gv(e.env),r=await G(t.home,hv(t.ref.key),()=>(nu(t.home,t.dest),Vv(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return G(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await Qv(t,r);return await jg(t.home,i),await uu(t.home,e),{entry:n,key:t.ref.key}})},ey=(e,t)=>t===`-`?e.readStdin():s(t,`utf8`),ty=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${G_(e)}`)}},ny=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ry=e=>ny(e)&&`ok`in e&&!(`key`in e),iy=e=>{if(!ry(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(ny(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},ay=e=>e.code===`unrecognized_keys`,oy=e=>e.path.length===0,sy=(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}`},cy=e=>{let t=new Map;for(let n of e){let e=Jt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>sy(e,t))},ly=e=>`✖ invalid proposal: ${e.message}`,uy=e=>{let t=e.issues.filter(e=>ay(e)),n=e.issues.filter(e=>!ay(e)),r=n.filter(e=>oy(e));if(t.length===0&&r.length===0)return E(e);let i=n.filter(e=>!oy(e)),a=[...cy(t),...r.map(e=>ly(e))];return i.length>0&&a.push(E({issues:i})),a.join(`
350
+ `)},dy=e=>{let t=wg.safeParse(e);if(!t.success)throw b(uy(t.error));return t.data},fy=async(e,t)=>{let n=await ey(e,t);return dy(iy(ty(n)))},py=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],my=e=>[...W_(e.warning),...W_(e.detectionWarning)],hy=async(e,t)=>{let n=await Yv(e,t),r=B(e.env);await Xv(r,n.proposal.key,n.effectiveCloneMode);let i=my(n);return{data:n.proposal,human:py(n.proposal.key,n.dest),warnings:i}},gy=e=>[`refs add: '${e}' added to config`],_y=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,url:e.url};e.tag_format_candidate!==null&&(t.tag_format=e.tag_format_candidate);let n=lv(e.packages);return n!==void 0&&(t.packages=n),t},vy=async(e,t)=>{let n=await fy(e,t),r=B(e.env),i=V(r,n.key);if(!U(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=_y(n),{entry:o,key:s}=await $v(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:gy(s),warnings:[]}},yy=(e,t,n)=>{cv(e.proposal.packages,n,e.rootPackageName);let r={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(r.tag_format=e.proposal.tag_format_candidate);let i=iv(e.proposal.packages,{refDescription:t,...e.rootPackageName===void 0?{}:{rootPackageName:e.rootPackageName}});return i!==void 0&&(r.packages=i),r},by=async(e,t,n)=>{let r=await Yv(e,t),i=B(e.env);await Xv(i,r.proposal.key,r.effectiveCloneMode);let a=yy(r,n,t),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await $v(e,o);return{data:{entry:s,key:c},human:gy(c),warnings:my(r)}},xy=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`)},Sy=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},Cy=(e,t)=>(xy(t),t.proposal===void 0?t.description===void 0?hy(e,Sy(t.source)):by(e,Sy(t.source),t.description):vy(e,t.proposal)),wy=(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},Ty=(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=X(r);return Q(t,i,async()=>{let r=await Cy(t,wy(e,n));Z(t,i,r.human,r.data,r.warnings)})()})},Ey=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`}},Dy=/^v(?<major>\d+)\.(?<minor>\d+)/u,Oy=e=>{let t=Dy.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},ky=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,Ay=e=>{let{nodeVersion:t}=e;return ky(Oy(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},jy=()=>vl.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),My=async e=>{try{return{config:await H(e)}}catch(e){return{config:jy(),errorMessage:G_(e)}}},Ny=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},Py={ci:`update check is off in CI — set REFS_UPDATE_CHECK=1 to run it here anyway`,config:`update check is off ([updates].check = false in config.toml)`,env:`update check is off (REFS_UPDATE_CHECK=0)`},Fy=(e,t,n)=>{if(Ug(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${Wg(e,t)}${r}`,name:`cli-update`,status:`warn`}}return n?{detail:`could not reach npm to check; its last answer was ${t}, which this CLI (${e}) already has`,name:`cli-update`,status:`warn`}:{detail:`this CLI (${e}) is npm's latest published release`,name:`cli-update`,status:`ok`}},Iy=async(e,t)=>{let n=Jg({env:e.env,updates:t.updates});if(n!==`on`)return{detail:Py[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await Hg({fetch:e.fetcher,home:B(e.env),nowMs:Date.now()});return r===void 0?{detail:`could not reach npm to learn the latest published version — not a fault of your setup, and nothing else depends on it`,name:`cli-update`,status:`warn`}:Fy(e.cliVersion,r,i)},Ly=(e,t)=>Object.keys(t.refs).map(e=>rl.parse(e)).map(t=>({dest:V(e,t),key:t})).filter(e=>U(e.dest)),Ry=[`pre-commit`,`pre-push`],zy=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},By=async e=>{let t=await Promise.all(Ry.map(t=>zy(e,t)));return Ry.filter((e,n)=>!t[n])},Vy=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},Hy=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:`${Ry.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},Uy=async(e,t,n)=>{let r=Ly(t,n),[i,a]=await Promise.all([By(t),Promise.all(r.map(n=>Vy(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return Hy({badKeys:o,checkoutCount:r.length,missingHooks:i})},Wy=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}},Gy=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`}},Ky=async(e,t,n)=>{let r=Ly(t,n),i=await Promise.all(r.map(t=>Wy(e,t)));return Gy(i)},qy=async e=>{try{return await Ag(e)}catch{return Eg.parse({})}},Jy=async e=>{try{return(await c(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(z(e))return[];throw e}},Yy=async(e,t)=>{if(U(e))return[[...t]];let n=await Jy(e);return(await Promise.all(n.map(n=>Yy(m(e,n),[...t,n])))).flat()},Xy=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},Zy=(e,t,n)=>Xy(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: ${X_(e.dest)}`,Qy=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),$y=async(e,t,n)=>{let r=(await Yy(e.sourcesDir,[])).map(t=>Qy(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=>Zy(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},eb=e=>e!==`unmaterialized`&&e!==`verified`,tb=new Set([`ambiguous`,`missing`,`relocated`,`unregistered`]),nb=(e,t)=>{let[n]=e;if(n===void 0)return t===void 0?{status:`ok`}:{discovery_incomplete:t,status:`unknown`};let r={packages:[...e],status:e.some(e=>tb.has(e.status))?`drift`:`unknown`};return t!==void 0&&(r.discovery_incomplete=t),r},rb=`(unknown)`,ib=e=>Gc(e.name)&&ll.safeParse(e.path).success,ab=(e,t)=>{let n=`${e.name}: declared in this checkout but not registered — it cannot be resolved by name until it is`;return e.path===void 0?`${n}. Declared at several paths (${(e.candidates??[]).join(`, `)}) — pick one`:ib(e)?`${n}. To register it: ${Y_([`--package=${J_(e.name)}`,`--create`,`--path=${J_(e.path)}`,`--description="<what it is>"`],[t])}`:`${n}. Its name or path is one the configuration cannot hold, so there is no command for it — report it and leave it unregistered`},ob=(e,t,n)=>{let r=`${e.name}: moved to ${e.path??rb} — update the entry's path (${n})`,i=Y_([`--package=${J_(e.name)}`],[t,`path`,e.path??``]);return ll.safeParse(e.path).success?`${r}. To fix it: ${i}`:r},sb=(e,t)=>{let n=`configured: ${e.configured_path??rb}`;if(e.status===`relocated`)return ob(e,t,n);if(e.status===`missing`){let r=Y_([`--package=${J_(e.name)}`,`--remove`],[t]);return`${e.name}: gone from this repo's workspaces (${n}) — repoint the entry if it moved out of them, or unregister it: ${r}`}if(e.status===`ambiguous`){let t=(e.candidates??[]).join(`, `);return`${e.name}: declared at several paths (${t}) — point the entry at one (${n})`}return`${e.name}: could not be checked — ${e.reason??`(no reason given)`} (${n})`},cb=(e,t)=>e.status===`unregistered`?ab(e,t):sb(e,t),lb=e=>`could not check for unregistered packages — ${e}`,ub=(e,t)=>{if(e.reason!==void 0)return[`could not be checked — ${e.reason}`];let n=(e.packages??[]).map(e=>cb(e,t));return e.discovery_incomplete===void 0?n:[...n,lb(e.discovery_incomplete)]},db=e=>{let t;return()=>(t??=C_(e),t)},fb=async(e,t,n)=>{let r=await c_(e);if(r===void 0||t.some(e=>e.packageName===r.name))return{issues:[]};let i=await n();if(!Hh(i))return{incomplete:Av(i),issues:[]};let a=Qh(i.packages,r.name);return a.kind===`ambiguous`?{issues:[{candidates:a.paths,name:r.name,status:`unregistered`}]}:{issues:a.kind===`found`?[{name:r.name,path:a.path,status:`unregistered`}]:[]}},pb=e=>{let t=new Map;for(let n of e)t.set(n.name,[...t.get(n.name)??[],n.path]);return t},mb=(e,t)=>{let n=new Set(e.changedDirs),r=t.filter(e=>!n.has(e.path)).map(e=>e.name);return new Set([...e.namesBefore,...r])},hb=(e,t)=>t.length===1&&t[0]!==void 0?{name:e,path:t[0],status:`unregistered`}:{candidates:[...t],name:e,status:`unregistered`},gb=async(e,t,n)=>{if(t.kind===`arrivals`&&t.changedDirs.length===0)return{issues:[]};let r=await n();if(!Hh(r))return{incomplete:Av(r),issues:[]};let i=new Set(e.map(e=>e.packageName)),a=r.packages.filter(e=>e.path!==`.`),o=t.kind===`all`?void 0:mb(t,a);return{issues:[...pb(a)].filter(([e])=>!i.has(e)).filter(([e])=>o===void 0||!o.has(e)).map(([e,t])=>hb(e,t)).toSorted((e,t)=>e.name.localeCompare(t.name))}},_b=(e,t)=>({path:e.configuredPath,reason:t,status:`unverifiable`}),vb=(e,t)=>Uh(t)?{configuredPath:e.configuredPath,path:null,status:`missing`}:_b(e,`this repo declares no workspaces, so there was nowhere to search`),yb=(e,t)=>t===e.configuredPath,bb=e=>e.packages.filter(e=>e.path!==`.`),xb=(e,t)=>{let n=Qh(bb(t),e.packageName);return n.kind===`ambiguous`?{candidates:n.paths,configuredPath:e.configuredPath,path:null,status:`ambiguous`}:Hh(t)?n.kind===`absent`?vb(e,t):yb(e,n.path)?_b(e,`the checkout changed while it was being inspected`):{configuredPath:e.configuredPath,path:n.path,status:`relocated`}:_b(e,n.kind===`found`?`workspace detection was incomplete, so the new location is not confirmed unique`:`workspace detection was incomplete`)},Sb=e=>{let t=new Map(Object.entries(e??{}));return[...t.keys()].toSorted().flatMap(e=>{let n=t.get(e);return n===void 0?[]:[{configuredPath:n.path,packageName:e}]})},Cb=async(e,t)=>{let n=await Yh(e,t.configuredPath,t.packageName);if(n.kind===`match`)return{path:t.configuredPath,status:`verified`};if(n.kind===`unreadable`)return{path:t.configuredPath,reason:n.reason,status:`unverifiable`}},wb=e=>e.flatMap(e=>e.settled===void 0?[]:[{outcome:e.settled,query:e.query}]),Tb=async(e,t,n)=>{let r=await Promise.all(t.map(async t=>({query:t,settled:await Cb(e,t)})));if(r.every(e=>e.settled!==void 0))return wb(r);let i=await n();return r.map(e=>({outcome:e.settled??xb(e.query,i),query:e.query}))},Eb=e=>{let{outcome:t,query:n}=e;return eb(t.status)?[{...t.candidates===void 0?{}:{candidates:t.candidates},configured_path:n.configuredPath,name:n.packageName,...t.status===`relocated`&&t.path!==null?{path:t.path}:{},...t.reason===void 0?{}:{reason:t.reason},status:t.status}]:[]},Db=(e,t)=>{let n=new Set(e.map(e=>e.name));return[...e,...t.filter(e=>!n.has(e.name))]},Ob=async(e,t,n)=>{let r=Sb(t),[i]=r;if(i===void 0)return{status:`ok`};let a=db(e);try{let[t,i,o]=await Promise.all([Tb(e,r,a),fb(e,r,a),gb(r,n,a)]);return nb([...t.flatMap(e=>Eb(e)),...Db(i.issues,o.issues)],o.incomplete??i.incomplete)}catch(e){return{reason:G_(e),status:`unknown`}}},kb=async(e,t,n)=>{try{return await G(e,hv(n.key),()=>Ob(n.dest,t.refs[n.key]?.packages,{kind:`all`}),{timeoutMs:100})}catch(e){if(e instanceof _&&e.code===`conflict`)return{reason:`another refs process is holding this ref`,status:`unknown`};throw e}},Ab=`config-drift`,jb=(e,t)=>{let[n]=e;return n===void 0?{detail:`every configured package path resolves in ${t} checkout(s)`,name:Ab,status:`ok`}:{detail:e.join(`; `),name:Ab,status:`warn`}},Mb=async(e,t,n)=>{let[r,...i]=n;if(r===void 0)return[];let a=await kb(e,t,r),o=await Mb(e,t,i);return[...ub(a,r.key).map(e=>`${r.key}: ${e}`),...o]},Nb=async(e,t)=>{let n=Ly(e,t);return jb(await Mb(e,t,n),n.length)},Pb=e=>{let{diagnosis:t}=e;return e.kind===`claim`||!e.isDirectory||t.pidState===`definitely-dead`||t.stale||t.meta===`malformed`||t.meta===`unreadable`||t.policy===`unknown`?!1:t.ageMs===void 0||t.ageMs>=0},Fb=e=>{let{ageMs:t,budgetMs:n,policy:r}=e;return r===`unknown`?`, state could not be read`:t===void 0||n===void 0?``:t<0?`, recorded time is in the future — check the system clock`:`, ${xp(t)} into a ${xp(n)} window`},Ib=e=>e.pid===void 0?`owner unknown (metadata ${e.meta})`:e.pidState===`definitely-dead`?`recorded pid ${e.pid} is not running`:`recorded pid ${e.pid} present`,Lb=(e,t)=>{let n=m(e.locksDir,ap,t.name),r=t.diagnosis.ageMs===void 0?``:` for ${xp(t.diagnosis.ageMs)}`;return`steal claim on ${t.name}: present${r}. Stealing this lock is blocked while it is here. A reclaim in progress clears it within a moment; if it stays, ${Rb}: ${Z_(n)}`},Rb=`stop every refs process using this home — including suspended ones — and then run`,zb=(e,t)=>{let{diagnosis:n}=t;if($f(n))return`, reclaimable now`;if(!n.stale&&t.isDirectory)return``;let r=m(e.locksDir,t.name);return`, not automatically reclaimable — if it is genuinely abandoned, ${Rb}: ${X_(r)}`},Bb=(e,t)=>{let{diagnosis:n}=t,r=t.isDirectory?``:`not a directory, `,i=zb(e,t);return`${t.name}: ${r}${Ib(n)}${Fb(n)}${i}`},Vb=async e=>{let t=await bp(e),[n]=t;return n===void 0?{detail:`no locks held`,name:`locks`,status:`ok`}:{detail:t.map(t=>t.kind===`claim`?Lb(e,t):Bb(e,t)).join(`; `),name:`locks`,status:t.every(e=>Pb(e))?`ok`:`warn`}},Hb=[`.agents`,`skills`,`refs`,`SKILL.md`],Ub=[`skills`,`refs`,`SKILL.md`],Wb=[`.claude`,`skills`,`refs`,`SKILL.md`],Gb=`npx skills add kaisers-io/refs`,Kb=`npm i -g @kaisers-io/refs@latest`,qb=(e,t)=>e===void 0?void 0:{display:t,path:e},Jb=e=>{let{dirName:t,env:n,home:r,overrideName:i}=e,a=n[i]?.trim();return a!==void 0&&a.length>0?{display:a,path:a}:qb(r===void 0?void 0:m(r,t),`~/${t}`)},Yb=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:qb(t,`~/.agents`),segments:Hb},{label:`Claude Code`,root:Jb({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:Ub},{label:`Codex`,root:Jb({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:Ub},{label:`project ./.agents`,root:qb(e.cwd,`./.agents`),segments:Hb},{label:`project ./.claude`,root:qb(e.cwd,`./.claude`),segments:Wb}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:m(t.path,...n)}])},Xb=async(e,t)=>{try{let n=await l(e);return{label:t,realPath:n,source:await s(n,`utf8`)}}catch{return}},Zb=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Qb=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,$b=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,ex=e=>{let t=Qb.exec(e)?.groups?.body;if(t!==void 0)return $b.exec(t)?.groups?.version},tx=(e,t)=>{if(e===t)return`match`;let n=Fg(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},nx={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${Kb}`,match:(e,t)=>`the refs skill is installed and matches this CLI (${t})`,"skill-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the skill: ${Gb}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${Kb} and ${Gb}`},rx=e=>{let{cliVersion:t,label:n,skillVersion:r}=e;if(r===void 0)return{detail:`the refs skill (${n}) predates the version gate — update it: ${Gb}`,name:`skill`,status:`warn`};let i=tx(r,t);return{detail:`${n}: ${nx[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},ix=e=>({detail:`refs skill not found in the locations this check knows about (${e.map(e=>e.display).join(`, `)}) — an install anywhere else is invisible here and still works; if it really is missing: ${Gb}`,name:`skill`,status:`warn`}),ax=async e=>{let t=Yb(e),n=await Promise.all(t.map(e=>Xb(e.path,e.label))),r=Zb(n.filter(e=>e!==void 0)).map(t=>rx({cliVersion:e.cliVersion,label:t.label,skillVersion:ex(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??ix(t)},ox=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,sx=e=>e===``?{}:{user:e},cx=e=>e===``?{}:{port:e},lx=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...sx(t.username),...cx(t.port)}:void 0}catch{return}},ux=e=>{let t=ox.exec(e),n=t?.groups?.host;return n===void 0?lx(e):{host:n,user:t?.groups?.user??`git`}},dx=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,fx=e=>e.user===void 0?dx(e):`${e.user}@${dx(e)}`,px=e=>{let t=Object.values(e.refs).map(e=>ux(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(fx(e),e);return[...n.values()].toSorted((e,t)=>fx(e).localeCompare(fx(t)))},mx=/Permission denied/u,hx=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],gx=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,_x=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=gx(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},vx=async(e,t,n)=>{let r=fx(t),i=await e.runner.run(`ssh`,_x(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:mx.test(i.stderr)?{host:r,outcome:`denied`}:hx.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},yx=(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`}},bx=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`}},xx=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`}},Sx=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),Cx=(e,t)=>yx(e,t)??bx(e)??xx(e)??Sx(e),wx=async(e,t,n)=>{let r=px(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>vx(e,t,i)));return Cx(a,i)},Tx=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${G_(t)}`,name:e.name,status:`fail`}}},Ex=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await Tx(t),i=await Ex(n);return r===void 0?i:[r,...i]},Dx=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Ey(n)},{name:`node`,run:()=>Promise.resolve(Ay(n))},{name:`config`,run:()=>Promise.resolve(Ny(t.errorMessage))},{name:`hooks-guard`,run:()=>Uy(n,r,t.config)},{name:`dirty-checkouts`,run:()=>Ky(n,r,t.config)},{name:`config-drift`,run:()=>Nb(r,t.config)},{name:`orphans`,run:()=>$y(r,t.config,i)},{name:`locks`,run:()=>Vb(r)},{name:`skill`,run:()=>ax(n)},{name:`cli-update`,run:()=>Iy(n,t.config)},{name:`ssh-auth`,run:()=>wx(n,t.config)}]},Ox=async e=>{let t=B(e.env),n=await My(t),r=await qy(t);return Ex(Dx({configLoad:n,ctx:e,home:t,state:r}))},kx={fail:`FAIL`,ok:`OK`,warn:`WARN`},Ax=e=>e.map(e=>`[${kx[e.status]}] ${e.name}: ${e.detail}`),jx=e=>e.some(e=>e.status===`fail`),Mx=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, drift, locks, ssh).`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let e=await Ox(t);Z(t,r,Ax(e),{checks:e}),jx(e)&&(process.exitCode=g.UNEXPECTED)})()})},Nx=(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},Px=(e,t)=>{if(!U(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},Fx=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},Ix=`never`,Lx=(e,t,n)=>e===void 0||n-Date.parse(e)>t,Rx=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,zx=(e,t)=>{if(e===void 0)return Ix;let n=t-Date.parse(e);if(Number.isNaN(n))return Ix;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return Rx(i,`minute`);let a=Math.floor(i/60);if(a<24)return Rx(a,`hour`);let o=Math.floor(a/24);return o<365?Rx(o,`day`):Rx(Math.floor(o/365),`year`)},Bx=e=>{let t=zx(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==Ix&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},Vx=(e,t,n)=>{let r=e.state.refs[t],i=al(Dg(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:Dg(`clone_mode`,n,e.settings),description:n.description,key:t,...r?.last_fetched_at===void 0?{}:{last_fetched_at:r.last_fetched_at},missing:!U(V(e.home,rl.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:Lx(r?.last_fetched_at,i,e.now)}},Hx=e=>{let t={home:e.home,includePackages:e.includePackages,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>Vx(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},Ux=async(e,t,n)=>{let r=B(e.env),i=await H(r),a=await Ag(r);return Hx({config:i,home:r,includePackages:t,now:n,state:a})},Wx=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...Bx({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],Gx=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...Wx(n,t)),e),[]),Kx=e=>e.split(`/`),qx=(e,t)=>{let n=Kx(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Jx=(e,t)=>{if(Object.hasOwn(e.refs,t))return rl.parse(t);let n=Kx(t),r=Object.keys(e.refs).filter(e=>qx(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 rl.parse(i)},Yx=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).option(`--packages`,`include each ref's package names in --json output (off by default)`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let n=Date.now(),i=await Ux(t,e.packages===!0,n);Z(t,r,Gx(i,n),i)})()})},Xx=e=>e===void 0?null:e,Zx=`packages`,Qx=()=>Object.keys(pl.shape).toSorted().join(`, `),$x=e=>`unknown package field '${e}' — valid fields: ${Qx()}`,eS=e=>Object.hasOwn(pl.shape,e),tS=(e,t,n)=>{if(!eS(t))throw y($x(t));let r=e[t],i=pl.safeParse({...e,[t]:n});if(!i.success)throw b(E(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},nS=async e=>{let t=Fx(e.entry,e.key,e.packageName),n=tS(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await uu(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:Xx(n.newValue),old:Xx(n.oldValue)}},rS=(e,t)=>`package '${e}' is already registered on ref '${t}' — edit its fields instead`,iS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n),r=Jx(e,t.query),i=Nx(e,r);if(Object.hasOwn(i.packages??{},t.packageName))throw b(rS(t.packageName,r));let a=ml.safeParse({...i,packages:{...i.packages,[t.packageName]:{description:t.description,path:t.path}}});if(!a.success)throw b(E(a.error));return await uu(n,{...e,refs:{...e.refs,[r]:a.data}}),{created:!0,field:Zx,key:r,new:{description:t.description,name:t.packageName,path:t.path},old:null}})},aS=(e,t)=>`package '${e}' is not registered on ref '${t}' — nothing to remove`,oS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n),r=Jx(e,t.query),i=Nx(e,r),a=i.packages??{};if(!Object.hasOwn(a,t.packageName))throw b(aS(t.packageName,r));let{[t.packageName]:o,...s}=a,c=Object.keys(s).length===0?sS(i):{...i,packages:s};return await uu(n,{...e,refs:{...e.refs,[r]:c}}),{field:Zx,key:r,new:null,old:{description:o?.description??``,name:t.packageName,path:o?.path??``},removed:!0}})},sS=e=>{let{packages:t,...n}=e;return n},cS=`packages`,lS=()=>Object.keys(ml.shape).filter(e=>e!==cS).toSorted().join(`, `),uS=e=>`unknown ref field '${e}' — valid fields: ${lS()}`,dS=e=>Object.hasOwn(ml.shape,e),fS=(e,t,n)=>`failed to rewrite git remote at ${e} to '${W(t)}': ${n.trim()}`,pS=async(e,t)=>{if(nu(t.home,t.dest),!U(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(fS(t.dest,t.cloneUrl,n.stderr))},mS=async(e,t)=>{let n=hf(t.value,{allowFileUrls:gv(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=V(t.home,t.key);return await pS(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},hS=(e,t,n)=>{let r={...e,[t]:n},i=ml.safeParse(r);if(!i.success)throw b(E(i.error));return i.data},gS=(e,t)=>t.field===`url`?mS(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(hS(t.entry,t.field,t.value)),_S=async(e,t)=>{let{field:n}=t;if(n===cS)throw y(`use --package <name> <field> <value>`);if(!dS(n))throw y(uS(n));let r=t.entry[n],i=await gS(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},vS=(e,t)=>{let n=B(e.env),{field:r,opts:i,query:a,value:o}=t;return G(n,`home`,async()=>{let t=await H(n),s=Jx(t,a),c=Nx(t,s);if(i.packageName!==void 0)return nS({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await _S(e,{entry:c,field:r,home:n,key:s,value:o});return await uu(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:Xx(l.new),old:Xx(l.old)}})},yS=`settings`,bS=[],xS=()=>Object.keys(dl.shape).toSorted().join(`, `),SS=e=>`unknown setting '${e}' — valid settings: ${xS()}`,CS=e=>Object.hasOwn(dl.shape,e),wS=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,TS=e=>{try{let t=Jx(e,yS);return[wS(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[wS("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return bS;throw e}},ES=e=>({data:{field:e.key,key:yS,new:Xx(e.parsed[e.key]),old:Xx(e.old)},warnings:TS(e.config)}),DS=(e,t)=>{let n=B(e.env);return G(n,`home`,async()=>{let e=await H(n);if(!CS(t.key))throw y(SS(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=dl.safeParse(i);if(!a.success)throw b(E(a.error));return await uu(n,{...e,settings:a.data}),ES({config:e,key:t.key,old:r,parsed:a.data})})},OS=[],kS=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},AS=e=>{let{description:t,path:n}=e.create,{packageName:r}=e.opts;if(r===void 0||t===void 0||n===void 0||e.second!==void 0||e.value!==void 0)throw y(`--create registers a new package: it needs --package <name>, --path <path> and --description <text>, and takes no <field> <value> arguments`);return{description:t,packageName:r,path:n}},jS=e=>{if(e.second===void 0||e.value===void 0)throw y(`missing <field> and <value> — see 'refs edit --help'`);return{field:e.second,value:e.value}},MS=e=>{let{packageName:t}=e.opts;if(t===void 0||e.second!==void 0||e.value!==void 0||e.create.path!==void 0||e.create.description!==void 0)throw y(`--remove unregisters a package: it needs --package <name>, and takes no <field> <value> arguments, no --path and no --description`);return{packageName:t}},NS=async(e,t)=>{let{packageName:n}=MS(t);return{data:await oS(e,{packageName:n,query:t.first}),warnings:OS}},PS=async(e,t)=>{let{description:n,packageName:r,path:i}=AS(t);return{data:await iS(e,{description:n,packageName:r,path:i,query:t.first}),warnings:OS}},FS=(e,t,n)=>{if(t.opts.packageName!==void 0)throw y(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return DS(e,n)},IS=e=>{if(e.create===!0&&e.remove===!0)throw y(`use either --create or --remove, not both: one registers a package and the other unregisters it`);return e.create===!0?`create`:e.remove===!0?`remove`:void 0},LS=async(e,t)=>{if(t.create.description!==void 0||t.create.path!==void 0)throw y(`--path and --description only apply to --create — to change one field of a registered package use: refs edit <ref> <field> <value> --package <name>`);let{field:n,value:r}=jS(t);return t.first===`settings`?FS(e,t,{key:n,value:r}):{data:await vS(e,{field:n,opts:t.opts,query:t.first,value:r}),warnings:OS}},RS=(e,t)=>{let n=IS(t.create);return n===`create`?PS(e,t):n===`remove`?NS(e,t):LS(e,t)},zS=e=>e==null?`(unset)`:String(e),BS=e=>{if(e.created===!0){let t=e.new;return[`${e.key}: registered '${t.name}' at ${t.path}`]}if(e.removed===!0){let t=e.old;return[`${e.key}: unregistered '${t.name}' (was at ${t.path})`]}return[`${e.key}: ${e.field} '${zS(e.old)}' -> '${zS(e.new)}'`]},VS=(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. With --create, registers a package the config does not have yet; with --remove, unregisters one it has.`).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`).option(`--create`,`register --package as a new package on this ref`).option(`--remove`,`unregister --package from this ref, leaving the checkout alone`).option(`--path <path>`,`with --create: the package path, relative to the checkout root`).option(`--description <text>`,`with --create: what the package is`).action((e,n,r,i,a)=>{let o=X(a);return Q(t,o,async()=>{let{data:a,warnings:s}=await RS(t,{create:i,first:e,opts:kS(i),second:n,value:r});Z(t,o,BS(a),a,s)})()})},HS=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,US={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},WS=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})},GS=async e=>{let t=B(e.env);return await WS(t),{config:await G(t,`home`,async()=>{let e=await bu(t,w_);return await Md(t),e}),home:t.root,skill_hint:HS}},KS=(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=X(n);return Q(t,r,async()=>{let e=await GS(t);Z(t,r,[`home: ${e.home}`,`config: ${US[e.config]}`,``,HS],e)})()})},qS=async e=>{let t=B(e.env),n=await G(t,`home`,()=>bu(t,w_));return n===`migrated`?{backup:Ql(t),result:n}:{backup:null,result:n}},JS=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${re(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,YS=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=X(n);return Q(t,r,async()=>{let e=await qS(t);Z(t,r,JS(e),e)})()})},XS=async e=>{try{return await i(e),!0}catch(e){if(z(e))return!1;throw e}},ZS=async e=>{try{return await c(e)}catch(e){if(z(e))return;throw e}},QS=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(z(e))return;throw e}},$S=async e=>{let t=await ZS(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await f(e)}catch(e){if(!z(e))throw e}return!0},eC=async e=>{let t=await QS(e);return t===void 0?!0:t?$S(e):!1},tC=async(e,t)=>{t!==e.sourcesDir&&await eC(t)&&await tC(e,ie(t))},nC=async(e,t)=>await XS(t)?(nu(e,t),await d(t,{force:!0,recursive:!0}),await tC(e,ie(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},rC=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),iC=async(e,t)=>{let n=await H(e),r={...n,refs:rC(n.refs,t)};await uu(e,r);let i=await Ag(e),a={...i,refs:rC(i.refs,t)};await jg(e,a)},aC=async(e,t)=>{let n=B(e.env),r=await H(n),i=Jx(r,t),a=V(n,i),{removedCheckout:o,warning:s}=await G(n,hv(i),()=>nC(n,a));return await G(n,`home`,()=>iC(n,i)),{data:{key:i,removed_checkout:o},warnings:W_(s)}},oC=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],sC=(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=X(r);return Q(t,i,async()=>{let{data:n,warnings:r}=await aC(t,e);Z(t,i,oC(n),n,r)})()})},cC=async e=>{let t=await Yh(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:lC(e)},lC=async e=>xb(e,await C_(e.checkoutDir)),uC=async e=>{try{return await G(e.home,hv(e.key),()=>cC(e),e.lockTimeoutMs===void 0?void 0:{timeoutMs:e.lockTimeoutMs})}catch(t){if(t instanceof _&&t.code===`conflict`)return{path:e.configuredPath,reason:`could not acquire the ref lock in time`,status:`unverifiable`};throw t}},dC=async e=>{if(!U(e.checkoutDir))return{path:e.configuredPath,status:`unmaterialized`};let t=await Yh(e.checkoutDir,e.configuredPath,e.packageName);return t.kind===`match`?{path:e.configuredPath,status:`verified`}:t.kind===`unreadable`?{path:e.configuredPath,reason:t.reason,status:`unverifiable`}:(e.onProbed?.(),uC(e))},fC=(e,t)=>({local_path:null,name:e,path:null,reason:t,status:`unverifiable`}),pC=async e=>{if(!e.checkoutManaged)return fC(e.packageName,e.checkoutReason);let t=await dC(e);return{...t.candidates===void 0?{}:{candidates:t.candidates},...t.configuredPath===void 0?{}:{configured_path:t.configuredPath},local_path:t.path===null?null:m(e.checkoutDir,t.path),name:e.packageName,path:t.path,...t.reason===void 0?{}:{reason:t.reason},status:t.status}},mC=e=>[`package: ${e.name}`,`package path: ${e.local_path??`(unknown)`}`,...e.status===`verified`?[]:[`package status: ${e.status}`],...e.configured_path===void 0?[]:[`configured path: ${e.configured_path}`],...e.candidates===void 0?[]:[`candidates: ${e.candidates.join(`, `)}`],...e.reason===void 0?[]:[`reason: ${e.reason}`]],hC=`node_modules`,gC=[`.pnp.cjs`,`.pnp.js`],_C=new Set([``,`.`,`..`]),vC=e=>!ae(e)&&!e.includes(`\\`)&&e.split(`/`).every(e=>!_C.has(e)),yC=function*(e){let t=ce(e);for(;;){re(t)!==hC&&(yield m(t,hC));let e=ie(t);if(e===t)return;t=e}},bC=async e=>{if(await CC(e)!==`absent`)try{let t=JSON.parse(await s(e,`utf8`)),{name:n,version:r}=typeof t==`object`&&t?t:{};return typeof r!=`string`||r===``?{package_json:e,reason:`manifest_has_no_version`,status:`unverifiable`}:{...typeof n==`string`?{name:n}:{},package_json:e,status:`found`,version:r}}catch{return{package_json:e,reason:`manifest_unreadable`,status:`unverifiable`}}},xC=new Set([`ENOENT`,`ENOTDIR`]),SC=async e=>{try{return(await c(e)).length===0}catch{return!1}},CC=async e=>{try{return await p(e),`present`}catch(e){let t=typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0;return t!==void 0&&xC.has(t)?`absent`:`unreadable`}},wC=async e=>{for(let t of yC(e)){let e=ie(t);if((await Promise.all(gC.map(t=>CC(m(e,t))))).includes(`present`))return!0}return!1},TC=async e=>{try{if(!(await p(e)).isDirectory())throw y(`--project must be a directory: ${e}`)}catch(t){throw t instanceof Error&&t.message.startsWith(`--project`)?t:y(`--project path does not exist: ${e}`)}},EC=async e=>{let t=await CC(e);if(t===`unreadable`)return{reason:`slot_unreadable`,status:`unverifiable`};if(t===`absent`)return;let n=await bC(m(e,`package.json`));return n===void 0?await SC(e)?void 0:{reason:`installed_without_manifest`,status:`unverifiable`}:n},DC=async(e,t)=>{if(!vC(t))return{reason:`unsupported_package_name`,status:`unverifiable`};for(let n of yC(e)){let e=await EC(m(n,...t.split(`/`)));if(e!==void 0)return e}return await wC(e)?{reason:`yarn_pnp`,status:`unsupported_layout`}:{status:`not_materialized`}},OC={'"':`"`,"\\":`\\`,b:`\b`,n:`
351
+ `,t:` `},kC={'"':`"`,"\\":`\\`},AC=new Set([` `,` `]),$=Symbol(`malformed git config`),jC=e=>e!==void 0&&!e.quoted&&AC.has(e.char),MC=e=>{let t=0,n=e.length;for(;t<n&&jC(e[t]);)t+=1;for(;n>t&&jC(e[n-1]);)--n;return e.slice(t,n).map(e=>e.char).join(``)},NC=e=>{let t=[],n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`\\`){r+=1;let n=OC[e[r]??``];if(n===void 0)return $;t.push({char:n,quoted:!0})}else if(i===`"`)n=!n;else if(!n&&(i===`#`||i===`;`))return MC(t);else t.push({char:i??``,quoted:n})}return n?$:MC(t)},PC=e=>{let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`\\`){n+=1;let r=kC[e[n]??``];if(r===void 0)return $;t+=r}else t+=r??``}return t},FC=/^[ \t]+|[ \t]+$/gu,IC=e=>e.replace(FC,``),LC=/^\[[ \t]*(?<section>[A-Za-z0-9.-]+)[ \t]*(?:"(?<subsection>(?:[^"\\]|\\.)*)")?[ \t]*\]/u,RC=/^(?<name>[A-Za-z][A-Za-z0-9-]*)[ \t]*(?:=[ \t]*(?<value>.*))?$/u,zC=function*(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`
352
352
  `)yield t,t=``,n=!1,r=!1;else if(a!==`\r`||e[i+1]!==`
353
353
  `){if(r)t+=a;else if(a===`\\`){let n=e[i+1];n===`
354
354
  `||n===`\r`&&e[i+2]===`
355
- `?i+=n===`\r`?2:1:(t+=a+(n??``),i+=1)}else a===`"`?n=!n:!n&&(a===`#`||a===`;`)&&(r=!0),t+=a}}t!==``&&(yield t)},kC=(e,t)=>e.subsection===void 0?`${e.name}.${t.toLowerCase()}`:`${e.name}.${e.subsection}.${t.toLowerCase()}`,AC=(e,t)=>{let n=e.toLowerCase();if(t===void 0)return{name:n};let r=CC(t);return r===$?$:{name:n,subsection:r}},jC=e=>{let t=EC.exec(e),n=t?.groups?.section;if(n===void 0)return;let r=TC(e.slice(t?.[0].length??0)),i=AC(n,t?.groups?.subsection);return i===$?$:{rest:r,section:i}},MC=e=>e===``||e.startsWith(`#`)||e.startsWith(`;`),NC=e=>{let t=DC.exec(e),n=t?.groups?.name;if(n===void 0)return $;let r=SC(t?.groups?.value??``);return r===$?$:{name:n,value:r}},PC=(e,t)=>{let n=NC(t.line);if(n===$)return`malformed`;let r=kC(t.section,n.name);return t.wanted.includes(r)&&e.set(r,[...e.get(r)??[],n.value]),`ok`},FC=(e,t,n)=>t.rest===``||MC(t.rest)?t.section:PC(e,{line:t.rest,section:t.section,wanted:n})===`malformed`?$:t.section,IC=(e,t)=>{let n=jC(t.line);return n===$?$:n===void 0?t.section===LC||PC(e,t)===`malformed`?$:t.section:FC(e,n,t.wanted)},LC={name:``},RC=(e,t)=>{let n=new Map,r=LC;for(let i of OC(e)){let e=TC(i),a=MC(e)?r:IC(n,{line:e,section:r,wanted:t});if(a===$)return;r=a}return n},zC=`core.hookspath`,BC=`remote.origin.url`,VC=[zC,BC],HC={status:`managed`},UC={status:`missing`},WC=e=>({reason:e,status:`unmanaged`}),GC=e=>({reason:e,status:`unverifiable`}),KC=new Set([`ENOENT`,`ENOTDIR`]),qC=e=>typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0,JC=async e=>{try{return await i(e),`present`}catch(e){let t=qC(e);return t!==void 0&&KC.has(t)?`absent`:`unreadable`}},YC=async e=>{try{let t=await i(m(e,`.git`));return t.isSymbolicLink()?WC(`git_is_symlink`):t.isDirectory()?void 0:WC(`git_is_file`)}catch(e){let t=qC(e);return t!==void 0&&KC.has(t)?WC(`no_git`):GC(`git_unreadable`)}},XC=(e,t)=>{let n=e.get(t);if(n===void 0||n.length!==1)return;let[r]=n;return r===void 0||r===``?void 0:r},ZC=(e,t,n)=>{try{return hf(e,{allowFileUrls:n}).key===hf(t,{allowFileUrls:n}).key}catch{return!1}},QC=e=>(e.get(zC)?.length??0)>1||(e.get(BC)?.length??0)>1,$C=(e,t)=>{let n=RC(e,VC);return n===void 0?GC(`config_malformed`):QC(n)?GC(`duplicate_config_values`):ew(n,t)},ew=(e,t)=>{if(XC(e,zC)!==t.hooksDir)return WC(`no_refs_marker`);let n=XC(e,BC);return n===void 0?WC(`no_origin`):ZC(n,t.expectedUrl,t.allowFileUrls)?HC:WC(`origin_mismatch`)},tw={missing:UC,outside:WC(`outside_sources`),unreadable:GC(`path_unreadable`)},nw=async e=>{let t=await Eu(e.sourcesDir,e.dest);if(t.kind!==`inside`)return t.kind===`unreadable`?await JC(e.sourcesDir)===`absent`?UC:tw.unreadable:tw[t.kind]},rw=async e=>{let t=await nw(e);if(t!==void 0)return t;let n=await YC(e.dest);if(n!==void 0)return n;try{return $C(await s(m(e.dest,`.git`,`config`),`utf8`),e)}catch{return GC(`config_unreadable`)}},iw=e=>`no registered package or ref matches '${e}' — this does not establish that the repository is untracked; it may be registered under a different identifier. Run: refs list --json`,aw=e=>`ref '${e}' is not in the active refs configuration — to track it: refs add <url>`,ow=e=>`--ref '${e}' matched no configured ref — pass a full ref key or a unique suffix of one. Run: refs list --json`,sw=/^[a-z][a-z0-9+.-]*:\/\//iu,cw=/^git@[^:/\s]+:[^\s]+$/u,lw=e=>sw.test(e)||cw.test(e),uw=(e,t)=>{try{return hf(e,t)}catch{if(lw(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}},dw=(e,t,n)=>{let r=uw(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(aw(r.key),`ref_not_registered`)}},fw=(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:rl.parse(r)})}return n},pw=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — pick one with: refs resolve ${e} --ref <ref>`,mw=(e,t)=>{let n=fw(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(pw(t,n.map(e=>e.key)));return r}},hw=function*(e){let t=e.split(`/`);for(let e=t.length-1;e>=1;--e)yield t.slice(0,e).join(`/`)},gw=(e,t)=>{for(let n of hw(t)){let t=mw(e,n);if(t!==void 0)return{...t,name:n}}},_w=(e,t,n)=>{try{return Gx(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(n,`unmatched_query`):e}},vw=(e,t)=>{let n=e[t];if(n!==void 0)return{entry:n,name:t};for(let n of hw(t)){let t=e[n];if(t!==void 0)return{entry:t,name:n}}},yw=(e,t,n)=>{let r=_w(e,n,ow(n)),i=vw(e.refs[r]?.packages??{},t);if(i===void 0)throw v(lw(t)?`ref '${r}' is tracked but registers no package matching that query — inspect: refs show ${r} --packages --json`:`ref '${r}' is tracked but registers no package matching '${t}' — inspect: refs show ${r} --packages --json`,`package_not_registered`);return{key:r,packageMatch:{...i,key:r}}},bw=(e,t,n)=>{let r=dw(e,t,n);if(r!==void 0)return r;let i=mw(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=gw(e,t);return a===void 0?{key:_w(e,t,iw(t))}:{key:a.key,packageMatch:a}},xw=(e,t,n)=>n.ref===void 0?bw(e,t,n):yw(e,t,n.ref),Sw=(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},Cw=async(e,t,n)=>{let r=await H(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await uu(e,r))},ww=(e,t,n)=>G(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Cw(e,t,n.branchRenamedTo);let r=await jg(e);r.refs[t]=Sw(r.refs[t],n),await Mg(e,r)}),Tw=2e3,Ew=e=>{if(e.length<=Tw)return e;let t=e.slice(0,1500),n=e.slice(e.length-500),r=e.length-Tw;return`${t}\n… ${String(r)} characters omitted …\n${n}`},Dw=async(e,t,n)=>{try{await G(e,`home`,async()=>{let r=await jg(e);r.refs[t]={...r.refs[t],last_error:Ew(n)},await Mg(e,r)})}catch{}},Ow=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()}}},kw=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Aw=(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`,jw=(e,t,n)=>{if(!Eg.shape.head_sha.safeParse(n).success)throw b(Aw(e,t,n));return n},Mw=(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},Nw=async(e,t,n)=>{await a(ie(n),{recursive:!0});let r=Og(`clone_mode`,t.ref,t.settings),i=await xd(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Cd(e.runner,n),s=await Bv(e.runner,{allowFileUrls:hv(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return Mw(t,i,{actualBranch:o,headSha:s})},Pw=async(e,t,n)=>{await Fv(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await Nv(e.runner,{allowFileUrls:hv(e.env),dest:n,expectedUrl:t.ref.url});let r=await kd(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:jw(t.key,n,r.newSha),previousSha:r.oldSha,status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Fw=(e,t,n)=>(nu(t.home,n),U(n)?Pw(e,t,n):Nw(e,t,n)),Iw={changedDirs:[],kind:`arrivals`,namesBefore:[]},Lw=async(e,t,n)=>{if(n.previousSha===void 0)return Iw;let r=await ld(e.runner,{dir:t,from:n.previousSha,to:n.headSha});return r===void 0?Iw:{...r,kind:`arrivals`}},Rw=(e,t)=>G(t.home,mv(t.key),async()=>{let n=V(t.home,t.key),r=await Fw(e,t,n),i=await Lw(e,n,r);return{...r,structure:await Tb(n,t.ref.packages,i)}}),zw=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(` | `)},Bw=(e,t)=>{let n={key:e,status:t.status},r=zw(t);return r!==void 0&&(n.warning=r),t.structure!==void 0&&(n.structure=t.structure),n},Vw=async(e,t)=>{try{let n=await Rw(e,t);return await ww(t.home,t.key,n),n}catch(e){throw await Dw(t.home,t.key,G_(e)),e}},Hw=async(e,t)=>{try{return Bw(t.key,await Vw(e,t))}catch(e){return{error:G_(e),key:t.key,status:`failed`}}},Uw=(e,t)=>e.status===`rejected`?{error:G_(e.reason),key:t,status:`failed`}:e.value,Ww=async(e,t)=>{let n=Ow(4);return(await Promise.allSettled(t.map(t=>kw(n,()=>Hw(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return Uw(e,r.key)})},Gw=async e=>{let{packageMatch:t}=e.match;return t===void 0?null:await nC({checkoutDir:e.dest,checkoutManaged:e.checkout.status===`managed`||e.checkout.status===`missing`,checkoutReason:`checkout is ${e.checkout.status}`,configuredPath:t.entry.path,home:e.home,key:e.match.key,packageName:t.name})},Kw=(e,t,n)=>xw(t,n.query,{allowFileUrls:hv(e.env),...n.ref===void 0?{}:{ref:n.ref}}),qw=async(e,t)=>{let n=B(e.env),r=await H(n);return{config:r,home:n,match:Kw(e,r,t),state:await jg(n)}},Jw=async(e,t)=>{if(t===void 0)return;let{packageMatch:n}=e;if(n===void 0)throw y(`--project needs a query that names a package; '${e.key}' resolves to the ref itself`);return await gC(t,n.name)},Yw=(e,t)=>{if(e.status!==`managed`&&e.status!==`missing`)throw b(`refusing to sync ${t}: its checkout is ${e.status}${e.reason===void 0?``:` (${e.reason})`} — run: refs doctor`)},Xw=async(e,t)=>(await Vw(e,{home:t.home,key:t.match.key,ref:Ax(t.config,t.match.key),settings:t.config.settings})).status,Zw=async(e,t)=>{t.project!==void 0&&await mC(t.project);let n=await qw(e,t),r=await $w(e,n,t);return t.syncIfStale!==!0||!(r.stale||r.missing)?r:(Yw(r.checkout,r.key),await Qw(e,{key:r.key,opts:t,target:n}))},Qw=async(e,t)=>{let{key:n,opts:r}=t,i=await Xw(e,t.target),a=await qw(e,r);if(a.match.key!==n)throw Se(`configuration changed while resolving '${r.query}' — retry`);return{...await $w(e,a,r),sync:{status:i}}},$w=async(e,t,n)=>{let{config:r,home:i,match:a,state:o}=t,{now:s}=n,c=Ax(r,a.key),l=V(i,a.key),u=al(Og(`sync_ttl`,c,r.settings)),d=o.refs[a.key]?.last_fetched_at,f=await rw({allowFileUrls:hv(e.env),dest:l,expectedUrl:c.url,hooksDir:i.hooksDir,sourcesDir:i.sourcesDir}),p=await Jw(a,n.project);return{checkout:f,key:a.key,...d===void 0?{}:{last_fetched_at:d},...p===void 0?{}:{installed:p},local_path:l,missing:f.status===`missing`,package:await Gw({checkout:f,dest:l,home:i,match:a}),stale:Px(d,u,s)}},eT=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...Lx({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale}),...e.checkout.status===`managed`||e.checkout.status===`missing`?[]:[`checkout: ${e.checkout.status}${e.checkout.reason===void 0?``:` (${e.checkout.reason})`}`]];return e.package!==null&&n.push(...rC(e.package)),e.sync!==void 0&&n.push(`sync: ${e.sync.status}`),e.installed!==void 0&&n.push(`installed: ${e.installed.version??`(${e.installed.status})`}`,...e.installed.name===void 0?[]:[`installed name: ${e.installed.name}`],...e.installed.reason===void 0?[]:[`installed reason: ${e.installed.reason}`]),n},tT=(e,t,n)=>({now:t,...n.project===void 0?{}:{project:n.project},query:e,...n.ref===void 0?{}:{ref:n.ref},...n.syncIfStale===!0?{syncIfStale:!0}:{}}),nT=(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`).option(`--ref <ref>`,`resolve the query as a package within this ref (full key or unique suffix)`).option(`--project <dir>`,`report the version this project has installed of the query's package`).option(`--sync-if-stale`,`fetch or clone first when the ref is stale or its checkout is absent`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r=Date.now(),a=await Zw(t,tT(e,r,n));Z(t,i,eT(a,r),a)})()})},rT={},iT=async(e,t)=>{if(!U(t))return{tags:[]};try{return{tags:await Ad(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${G_(e)}`}}},aT=async(e,t,n,r)=>{let i=B(e.env),a=await H(i),o=Gx(a,t),s=Ax(a,o),c=await jg(i),l=V(i,o),{packages:u,...d}=s,f=n.tags?await iT(e,l):void 0,p=c.refs[o]??rT;return{data:{...d,key:o,local_path:l,missing:!U(l),...n.packages?{packages:u??{}}:{},packages_count:Object.keys(u??{}).length,...f===void 0?{}:{sample_tags:f.tags},stale:Px(p.last_fetched_at,al(Og(`sync_ttl`,s,a.settings)),r),state:p},warnings:W_(f?.warning)}},oT=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...Lx({lastFetchedAt:e.state.last_fetched_at,missing:e.missing,now:t,stale:e.stale})];return e.sample_tags!==void 0&&e.sample_tags.length>0&&n.push(`tags: ${e.sample_tags.join(`, `)}`),n},sT=(e,t)=>{e.command(`show`).description(`Show a configured ref: entry, state, local path, package count; --packages/--tags add the package map and sample tags to --json.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).option(`--packages`,`include the ref's full package map in --json output (off by default)`).option(`--tags`,`include sample tags in --json output (human output always probes for them)`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r={packages:n.packages===!0,tags:!i.json||n.tags===!0},a=Date.now(),{data:o,warnings:s}=await aT(t,e,r,a);Z(t,i,oT(o,a),o,s)})()})},cT=(e,t,n)=>({home:e,key:n,ref:Ax(t,n),settings:t.settings}),lT=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>cT(e,t,rl.parse(n))):n.map(n=>cT(e,t,Gx(t,n))),uT=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=al(Og(`sync_ttl`,t.ref,t.settings)),a=Px(n.refs[t.key]?.last_fetched_at,i,r),o=!U(V(e,t.key));return a||o})},dT=async(e,t,n)=>{if(!Zg({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await Ug({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!Wg(e.cliVersion,r)?[]:[Gg(e.cliVersion,r)]},fT=async(e,t,n)=>{if(!n)return t;let r=await jg(e);return uT(e,t,r)},pT=async(e,t)=>{let n=B(e.env),r=await H(n),i=lT(n,r,t.refs),a=await fT(n,i,t.staleOnly),[o,s]=await Promise.all([Ww(e,a),a.length>0?dT(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},mT=[`updated`,`fresh`,`cloned`,`restored`,`failed`],hT={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},gT=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},_T=e=>{if(e.status===`failed`)return[` ${e.key}: ${e.error??`unknown error`}`];let t=e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`;return e.structure===void 0?[t]:[t,...sb(e.structure,e.key).map(e=>` ${e}`)]},vT=e=>{let t=gT(e),n=[mT.map(e=>`${hT[e]} (${t[e].length})`).join(` / `)];for(let e of mT)for(let r of t[e])n.push(..._T(r));return n},yT=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),bT=(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=X(r);return Q(t,i,async()=>{let r=await pT(t,yT(e,n));Z(t,i,vT(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},xT=(e,t,n)=>n===void 0?e.tag_format:Mx(e,t,n).tag_format??e.tag_format,ST=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?``:` --package ${J_(n)}`;throw b(`${r} has no tag_format configured — inspect the repository's real tags and set one with: refs edit ${J_(t)} tag_format '<format>'${i}`)},CT=async(e,t)=>{let n=B(e.env),r=await H(n),i=Gx(r,t.query),a=Ax(r,i),o=ST(xT(a,i,t.opts.packageName),i,t.opts.packageName),s=V(n,i);jx(s,i);let c=await Gd(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},wT=e=>[`${e.key}@${e.version} -> ${e.tag}`],TT=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},ET=[FS,Cy,AS,Kx,kx,RS,XS,nT,sT,bT,(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=X(i);return Q(t,a,async()=>{let i=await CT(t,{opts:TT(r),query:e,version:n});Z(t,a,wT(i),i)})()})}],DT=(e,t)=>{for(let n of ET)n(e,t)},OT=[``,`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(`
356
- `),kT=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),AT=`--json`,jT=`--verbose`,MT=/\n$/u,NT=/^error: /u,PT=e=>e.replace(NT,``),FT=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},IT=e=>FT(e,AT),LT=e=>FT(e,jT),RT=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,zT=e=>{let t=new z_().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(w_).option(AT,`emit machine-readable JSON on stdout instead of human-readable text`).option(jT,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(MT,``))},writeOut:t=>{e.out(t.replace(MT,``))}});return t.addHelpText(`after`,OT),DT(t,e),t},BT=()=>{process.exitCode=g.OK},VT=(e,t,n)=>{let r={code:`usage`,message:RT(PT(n.message),n.stack,t.verbose)};K_(e,t,r),process.exitCode=g.USAGE},HT=(e,t,n)=>{if(kT.has(n.code)){BT();return}VT(e,t,n)},UT=(e,t,n)=>{let r=we(n,{verbose:t.verbose});K_(e,t,r),process.exitCode=r.exitCode},WT=async(e,t,n)=>{let r={json:IT(n),verbose:LT(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof O_){HT(e,r,t);return}UT(e,r,t)}},GT=(e,t)=>WT(e,zT(e),t);import.meta.main&&await GT(D_(),process.argv);export{zT as buildProgram,X as cliOptsOf,Z as emit,K_ as emitError,G_ as errorMessageOf,q_ as progress,D_ as realContext,DT as registerCommands,GT as run,WT as runProgram,W_ as warningsFor,Q as wrapAction};
355
+ `?i+=n===`\r`?2:1:(t+=a+(n??``),i+=1)}else a===`"`?n=!n:!n&&(a===`#`||a===`;`)&&(r=!0),t+=a}}t!==``&&(yield t)},BC=(e,t)=>e.subsection===void 0?`${e.name}.${t.toLowerCase()}`:`${e.name}.${e.subsection}.${t.toLowerCase()}`,VC=(e,t)=>{let n=e.toLowerCase();if(t===void 0)return{name:n};let r=PC(t);return r===$?$:{name:n,subsection:r}},HC=e=>{let t=LC.exec(e),n=t?.groups?.section;if(n===void 0)return;let r=IC(e.slice(t?.[0].length??0)),i=VC(n,t?.groups?.subsection);return i===$?$:{rest:r,section:i}},UC=e=>e===``||e.startsWith(`#`)||e.startsWith(`;`),WC=e=>{let t=RC.exec(e),n=t?.groups?.name;if(n===void 0)return $;let r=NC(t?.groups?.value??``);return r===$?$:{name:n,value:r}},GC=(e,t)=>{let n=WC(t.line);if(n===$)return`malformed`;let r=BC(t.section,n.name);return t.wanted.includes(r)&&e.set(r,[...e.get(r)??[],n.value]),`ok`},KC=(e,t,n)=>t.rest===``||UC(t.rest)?t.section:GC(e,{line:t.rest,section:t.section,wanted:n})===`malformed`?$:t.section,qC=(e,t)=>{let n=HC(t.line);return n===$?$:n===void 0?t.section===JC||GC(e,t)===`malformed`?$:t.section:KC(e,n,t.wanted)},JC={name:``},YC=(e,t)=>{let n=new Map,r=JC;for(let i of zC(e)){let e=IC(i),a=UC(e)?r:qC(n,{line:e,section:r,wanted:t});if(a===$)return;r=a}return n},XC=`core.hookspath`,ZC=`remote.origin.url`,QC=[XC,ZC],$C={status:`managed`},ew={status:`missing`},tw=e=>({reason:e,status:`unmanaged`}),nw=e=>({reason:e,status:`unverifiable`}),rw=new Set([`ENOENT`,`ENOTDIR`]),iw=e=>typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0,aw=async e=>{try{return await i(e),`present`}catch(e){let t=iw(e);return t!==void 0&&rw.has(t)?`absent`:`unreadable`}},ow=async e=>{try{let t=await i(m(e,`.git`));return t.isSymbolicLink()?tw(`git_is_symlink`):t.isDirectory()?void 0:tw(`git_is_file`)}catch(e){let t=iw(e);return t!==void 0&&rw.has(t)?tw(`no_git`):nw(`git_unreadable`)}},sw=(e,t)=>{let n=e.get(t);if(n===void 0||n.length!==1)return;let[r]=n;return r===void 0||r===``?void 0:r},cw=(e,t,n)=>{try{return hf(e,{allowFileUrls:n}).key===hf(t,{allowFileUrls:n}).key}catch{return!1}},lw=e=>(e.get(XC)?.length??0)>1||(e.get(ZC)?.length??0)>1,uw=(e,t)=>{let n=YC(e,QC);return n===void 0?nw(`config_malformed`):lw(n)?nw(`duplicate_config_values`):dw(n,t)},dw=(e,t)=>{if(sw(e,XC)!==t.hooksDir)return tw(`no_refs_marker`);let n=sw(e,ZC);return n===void 0?tw(`no_origin`):cw(n,t.expectedUrl,t.allowFileUrls)?$C:tw(`origin_mismatch`)},fw={missing:ew,outside:tw(`outside_sources`),unreadable:nw(`path_unreadable`)},pw=async e=>{let t=await Eu(e.sourcesDir,e.dest);if(t.kind!==`inside`)return t.kind===`unreadable`?await aw(e.sourcesDir)===`absent`?ew:fw.unreadable:fw[t.kind]},mw=async e=>{let t=await pw(e);if(t!==void 0)return t;let n=await ow(e.dest);if(n!==void 0)return n;try{return uw(await s(m(e.dest,`.git`,`config`),`utf8`),e)}catch{return nw(`config_unreadable`)}},hw=e=>`no registered package or ref matches '${e}' — this does not establish that the repository is untracked; it may be registered under a different identifier. Run: refs list --json`,gw=e=>`ref '${e}' is not in the active refs configuration — to track it: refs add <url>`,_w=e=>`--ref '${e}' matched no configured ref — pass a full ref key or a unique suffix of one. Run: refs list --json`,vw=/^[a-z][a-z0-9+.-]*:\/\//iu,yw=/^git@[^:/\s]+:[^\s]+$/u,bw=e=>vw.test(e)||yw.test(e),xw=(e,t)=>{try{return hf(e,t)}catch{if(bw(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}},Sw=(e,t,n)=>{let r=xw(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(gw(r.key),`ref_not_registered`)}},Cw=(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:rl.parse(r)})}return n},ww=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — pick one with: refs resolve ${e} --ref <ref>`,Tw=(e,t)=>{let n=Cw(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(ww(t,n.map(e=>e.key)));return r}},Ew=function*(e){let t=e.split(`/`);for(let e=t.length-1;e>=1;--e)yield t.slice(0,e).join(`/`)},Dw=(e,t)=>{for(let n of Ew(t)){let t=Tw(e,n);if(t!==void 0)return{...t,name:n}}},Ow=(e,t,n)=>{try{return Jx(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(n,`unmatched_query`):e}},kw=(e,t)=>{let n=e[t];if(n!==void 0)return{entry:n,name:t};for(let n of Ew(t)){let t=e[n];if(t!==void 0)return{entry:t,name:n}}},Aw=(e,t,n)=>{let r=Ow(e,n,_w(n)),i=kw(e.refs[r]?.packages??{},t);if(i===void 0)throw v(bw(t)?`ref '${r}' is tracked but registers no package matching that query — inspect: refs show ${r} --packages --json`:`ref '${r}' is tracked but registers no package matching '${t}' — inspect: refs show ${r} --packages --json`,`package_not_registered`);return{key:r,packageMatch:{...i,key:r}}},jw=(e,t,n)=>{let r=Sw(e,t,n);if(r!==void 0)return r;let i=Tw(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=Dw(e,t);return a===void 0?{key:Ow(e,t,hw(t))}:{key:a.key,packageMatch:a}},Mw=(e,t,n)=>n.ref===void 0?jw(e,t,n):Aw(e,t,n.ref),Nw=(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},Pw=async(e,t,n)=>{let r=await H(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await uu(e,r))},Fw=(e,t,n)=>G(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Pw(e,t,n.branchRenamedTo);let r=await Ag(e);r.refs[t]=Nw(r.refs[t],n),await jg(e,r)}),Iw=2e3,Lw=e=>{if(e.length<=Iw)return e;let t=e.slice(0,1500),n=e.slice(e.length-500),r=e.length-Iw;return`${t}\n… ${String(r)} characters omitted …\n${n}`},Rw=async(e,t,n)=>{try{await G(e,`home`,async()=>{let r=await Ag(e);r.refs[t]={...r.refs[t],last_error:Lw(n)},await jg(e,r)})}catch{}},zw=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()}}},Bw=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Vw=(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`,Hw=(e,t,n)=>{if(!Tg.shape.head_sha.safeParse(n).success)throw b(Vw(e,t,n));return n},Uw=(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},Ww=async(e,t,n)=>{await a(ie(n),{recursive:!0});let r=Dg(`clone_mode`,t.ref,t.settings),i=await xd(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Cd(e.runner,n),s=await Vv(e.runner,{allowFileUrls:gv(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return Uw(t,i,{actualBranch:o,headSha:s})},Gw=async(e,t,n)=>{await Iv(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await Pv(e.runner,{allowFileUrls:gv(e.env),dest:n,expectedUrl:t.ref.url});let r=await kd(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Hw(t.key,n,r.newSha),previousSha:r.oldSha,status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Kw=(e,t,n)=>(nu(t.home,n),U(n)?Gw(e,t,n):Ww(e,t,n)),qw={changedDirs:[],kind:`arrivals`,namesBefore:[]},Jw=async(e,t,n)=>{if(n.previousSha===void 0)return qw;let r=await ld(e.runner,{dir:t,from:n.previousSha,to:n.headSha});return r===void 0?qw:{...r,kind:`arrivals`}},Yw=(e,t)=>G(t.home,hv(t.key),async()=>{let n=V(t.home,t.key),r=await Kw(e,t,n),i=await Jw(e,n,r);return{...r,structure:await Ob(n,t.ref.packages,i)}}),Xw=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(` | `)},Zw=(e,t)=>{let n={key:e,status:t.status},r=Xw(t);return r!==void 0&&(n.warning=r),t.structure!==void 0&&(n.structure=t.structure),n},Qw=async(e,t)=>{try{let n=await Yw(e,t);return await Fw(t.home,t.key,n),n}catch(e){throw await Rw(t.home,t.key,G_(e)),e}},$w=async(e,t)=>{try{return Zw(t.key,await Qw(e,t))}catch(e){return{error:G_(e),key:t.key,status:`failed`}}},eT=(e,t)=>e.status===`rejected`?{error:G_(e.reason),key:t,status:`failed`}:e.value,tT=async(e,t)=>{let n=zw(4);return(await Promise.allSettled(t.map(t=>Bw(n,()=>$w(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return eT(e,r.key)})},nT=async e=>{let{packageMatch:t}=e.match;return t===void 0?null:await pC({checkoutDir:e.dest,checkoutManaged:e.checkout.status===`managed`||e.checkout.status===`missing`,checkoutReason:`checkout is ${e.checkout.status}`,configuredPath:t.entry.path,home:e.home,key:e.match.key,packageName:t.name})},rT=(e,t,n)=>Mw(t,n.query,{allowFileUrls:gv(e.env),...n.ref===void 0?{}:{ref:n.ref}}),iT=async(e,t)=>{let n=B(e.env),r=await H(n);return{config:r,home:n,match:rT(e,r,t),state:await Ag(n)}},aT=async(e,t)=>{if(t===void 0)return;let{packageMatch:n}=e;if(n===void 0)throw y(`--project needs a query that names a package; '${e.key}' resolves to the ref itself`);return await DC(t,n.name)},oT=(e,t)=>{if(e.status!==`managed`&&e.status!==`missing`)throw b(`refusing to sync ${t}: its checkout is ${e.status}${e.reason===void 0?``:` (${e.reason})`} — run: refs doctor`)},sT=async(e,t)=>(await Qw(e,{home:t.home,key:t.match.key,ref:Nx(t.config,t.match.key),settings:t.config.settings})).status,cT=async(e,t)=>{t.project!==void 0&&await TC(t.project);let n=await iT(e,t),r=await uT(e,n,t);return t.syncIfStale!==!0||!(r.stale||r.missing)?r:(oT(r.checkout,r.key),await lT(e,{key:r.key,opts:t,target:n}))},lT=async(e,t)=>{let{key:n,opts:r}=t,i=await sT(e,t.target),a=await iT(e,r);if(a.match.key!==n)throw Se(`configuration changed while resolving '${r.query}' — retry`);return{...await uT(e,a,r),sync:{status:i}}},uT=async(e,t,n)=>{let{config:r,home:i,match:a,state:o}=t,{now:s}=n,c=Nx(r,a.key),l=V(i,a.key),u=al(Dg(`sync_ttl`,c,r.settings)),d=o.refs[a.key]?.last_fetched_at,f=await mw({allowFileUrls:gv(e.env),dest:l,expectedUrl:c.url,hooksDir:i.hooksDir,sourcesDir:i.sourcesDir}),p=await aT(a,n.project);return{checkout:f,key:a.key,...d===void 0?{}:{last_fetched_at:d},...p===void 0?{}:{installed:p},local_path:l,missing:f.status===`missing`,package:await nT({checkout:f,dest:l,home:i,match:a}),stale:Lx(d,u,s)}},dT=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...Bx({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale}),...e.checkout.status===`managed`||e.checkout.status===`missing`?[]:[`checkout: ${e.checkout.status}${e.checkout.reason===void 0?``:` (${e.checkout.reason})`}`]];return e.package!==null&&n.push(...mC(e.package)),e.sync!==void 0&&n.push(`sync: ${e.sync.status}`),e.installed!==void 0&&n.push(`installed: ${e.installed.version??`(${e.installed.status})`}`,...e.installed.name===void 0?[]:[`installed name: ${e.installed.name}`],...e.installed.reason===void 0?[]:[`installed reason: ${e.installed.reason}`]),n},fT=(e,t,n)=>({now:t,...n.project===void 0?{}:{project:n.project},query:e,...n.ref===void 0?{}:{ref:n.ref},...n.syncIfStale===!0?{syncIfStale:!0}:{}}),pT=(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`).option(`--ref <ref>`,`resolve the query as a package within this ref (full key or unique suffix)`).option(`--project <dir>`,`report the version this project has installed of the query's package`).option(`--sync-if-stale`,`fetch or clone first when the ref is stale or its checkout is absent`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r=Date.now(),a=await cT(t,fT(e,r,n));Z(t,i,dT(a,r),a)})()})},mT={},hT=async(e,t)=>{if(!U(t))return{tags:[]};try{let{tags:n}=await Nd(e.runner,t,5);return{tags:n}}catch(e){return{tags:[],warning:`could not list tags: ${G_(e)}`}}},gT=async(e,t,n,r)=>{let i=B(e.env),a=await H(i),o=Jx(a,t),s=Nx(a,o),c=await Ag(i),l=V(i,o),{packages:u,...d}=s,f=n.tags?await hT(e,l):void 0,p=c.refs[o]??mT;return{data:{...d,key:o,local_path:l,missing:!U(l),...n.packages?{packages:u??{}}:{},packages_count:Object.keys(u??{}).length,...f===void 0?{}:{sample_tags:f.tags},stale:Lx(p.last_fetched_at,al(Dg(`sync_ttl`,s,a.settings)),r),state:p},warnings:W_(f?.warning)}},_T=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...Bx({lastFetchedAt:e.state.last_fetched_at,missing:e.missing,now:t,stale:e.stale})];return e.sample_tags!==void 0&&e.sample_tags.length>0&&n.push(`tags: ${e.sample_tags.join(`, `)}`),n},vT=(e,t)=>{e.command(`show`).description(`Show a configured ref: entry, state, local path, package count; --packages/--tags add the package map and sample tags to --json.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).option(`--packages`,`include the ref's full package map in --json output (off by default)`).option(`--tags`,`include sample tags in --json output (human output always probes for them)`).action((e,n,r)=>{let i=X(r);return Q(t,i,async()=>{let r={packages:n.packages===!0,tags:!i.json||n.tags===!0},a=Date.now(),{data:o,warnings:s}=await gT(t,e,r,a);Z(t,i,_T(o,a),o,s)})()})},yT=(e,t,n)=>({home:e,key:n,ref:Nx(t,n),settings:t.settings}),bT=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>yT(e,t,rl.parse(n))):n.map(n=>yT(e,t,Jx(t,n))),xT=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=al(Dg(`sync_ttl`,t.ref,t.settings)),a=Lx(n.refs[t.key]?.last_fetched_at,i,r),o=!U(V(e,t.key));return a||o})},ST=async(e,t,n)=>{if(!Xg({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await Hg({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!Ug(e.cliVersion,r)?[]:[Wg(e.cliVersion,r)]},CT=async(e,t,n)=>{if(!n)return t;let r=await Ag(e);return xT(e,t,r)},wT=async(e,t)=>{let n=B(e.env),r=await H(n),i=bT(n,r,t.refs),a=await CT(n,i,t.staleOnly),[o,s]=await Promise.all([tT(e,a),a.length>0?ST(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},TT=[`updated`,`fresh`,`cloned`,`restored`,`failed`],ET={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},DT=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},OT=e=>{if(e.status===`failed`)return[` ${e.key}: ${e.error??`unknown error`}`];let t=e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`;return e.structure===void 0?[t]:[t,...ub(e.structure,e.key).map(e=>` ${e}`)]},kT=e=>{let t=DT(e),n=[TT.map(e=>`${ET[e]} (${t[e].length})`).join(` / `)];for(let e of TT)for(let r of t[e])n.push(...OT(r));return n},AT=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),jT=(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=X(r);return Q(t,i,async()=>{let r=await wT(t,AT(e,n));Z(t,i,kT(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},MT=(e,t,n)=>n===void 0?e.tag_format:Fx(e,t,n).tag_format??e.tag_format,NT=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?[]:[`--package=${J_(n)}`];throw b(`${r} has no tag_format configured — inspect the repository's real tags and set one with: ${Y_(i,[t,`tag_format`,`<format>`])}`)},PT=async(e,t)=>{let n=B(e.env),r=await H(n),i=Jx(r,t.query),a=Nx(r,i),o=NT(MT(a,i,t.opts.packageName),i,t.opts.packageName),s=V(n,i);Px(s,i);let c=await Gd(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},FT=e=>[`${e.key}@${e.version} -> ${e.tag}`],IT=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},LT=[KS,Ty,VS,Yx,Mx,YS,sC,pT,vT,jT,(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=X(i);return Q(t,a,async()=>{let i=await PT(t,{opts:IT(r),query:e,version:n});Z(t,a,FT(i),i)})()})}],RT=(e,t)=>{for(let n of LT)n(e,t)},zT=[``,`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(`
356
+ `),BT=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),VT=`--json`,HT=`--verbose`,UT=/\n$/u,WT=/^error: /u,GT=e=>e.replace(WT,``),KT=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},qT=e=>KT(e,VT),JT=e=>KT(e,HT),YT=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,XT=e=>{let t=new z_().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(w_).option(VT,`emit machine-readable JSON on stdout instead of human-readable text`).option(HT,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(UT,``))},writeOut:t=>{e.out(t.replace(UT,``))}});return t.addHelpText(`after`,zT),RT(t,e),t},ZT=()=>{process.exitCode=g.OK},QT=(e,t,n)=>{let r={code:`usage`,message:YT(GT(n.message),n.stack,t.verbose)};K_(e,t,r),process.exitCode=g.USAGE},$T=(e,t,n)=>{if(BT.has(n.code)){ZT();return}QT(e,t,n)},eE=(e,t,n)=>{let r=we(n,{verbose:t.verbose});K_(e,t,r),process.exitCode=r.exitCode},tE=async(e,t,n)=>{let r={json:qT(n),verbose:JT(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof O_){$T(e,r,t);return}eE(e,r,t)}},nE=(e,t)=>tE(e,XT(e),t);import.meta.main&&await nE(D_(),process.argv);export{XT as buildProgram,X as cliOptsOf,Z as emit,K_ as emitError,G_ as errorMessageOf,q_ as progress,D_ as realContext,RT as registerCommands,nE as run,tE as runProgram,W_ as warningsFor,Q as wrapAction};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaisers-io/refs",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "Gives coding agents the real source of your dependencies, not a guess.",
5
5
  "keywords": [
6
6
  "ai",