@kaisers-io/refs 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +222 -1
  2. package/dist/refs.mjs +68 -91
  3. package/package.json +3 -3
package/dist/refs.mjs CHANGED
@@ -1,69 +1,55 @@
1
1
  #!/usr/bin/env node
2
- import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a,readFile as o,readdir as s,realpath as c,rename as l,rm as u,rmdir as d,stat as f,writeFile as p}from"node:fs/promises";import m,{basename as ee,dirname as te,isAbsolute as ne,join as h,posix as re,relative as ie,resolve as ae,sep as oe}from"node:path";import{randomUUID as se}from"node:crypto";import ce,{existsSync as le,realpathSync as ue}from"node:fs";import{homedir as de}from"node:os";import{setTimeout as fe}from"node:timers/promises";import{EventEmitter as pe,once as me}from"node:events";import he,{spawn as ge}from"node:child_process";import g from"node:process";import{stripVTControlCharacters as _e}from"node:util";const _={CONFLICT:5,NOT_FOUND:4,OK:0,UNEXPECTED:1,USAGE:2,VALIDATION:3};var v=class extends Error{code;exitCode;constructor(e,t,n,r){super(n,r),this.code=t,this.exitCode=e,this.name=`RefsError`}};const ve=e=>new v(_.CONFLICT,`conflict`,e),y=e=>new v(_.NOT_FOUND,`not_found`,e),b=e=>new v(_.USAGE,`usage`,e),x=e=>new v(_.VALIDATION,`validation`,e),ye=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,be=(e,t)=>e instanceof v?{code:e.code,exitCode:e.exitCode,message:ye(e.message,e.stack,t.verbose)}:e instanceof Error?{code:`unexpected`,exitCode:_.UNEXPECTED,message:ye(e.message,e.stack,t.verbose)}:{code:`unexpected`,exitCode:_.UNEXPECTED,message:String(e)};var xe;function S(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Se=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ce=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(xe=globalThis).__zod_globalConfig??(xe.__zod_globalConfig={});const we=globalThis.__zod_globalConfig;function C(e){return e&&Object.assign(we,e),we}function Te(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Ee(e,t){return typeof t==`bigint`?t.toString():t}function De(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Oe(e){return e==null}function ke(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ae(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}const je=Symbol(`evaluating`);function w(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==je)return r===void 0&&(r=je,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Me(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function T(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ne(e){return JSON.stringify(e)}function Pe(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Fe=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Le=De(()=>{if(we.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Re(e){if(Ie(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Ie(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ze(e){return Re(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Be=new Set([`string`,`number`,`symbol`]);function Ve(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function He(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function E(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ue(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const We={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ge(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return He(e,T(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Me(this,`shape`,e),e},checks:[]}))}function Ke(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return He(e,T(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Me(this,`shape`,r),r},checks:[]}))}function qe(e,t){if(!Re(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return He(e,T(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function Je(e,t){if(!Re(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return He(e,T(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function Ye(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return He(e,T(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Me(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Xe(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return He(t,T(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Me(this,`shape`,i),i},checks:[]}))}function Ze(e,t,n){return He(t,T(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Me(this,`shape`,i),i}}))}function Qe(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function $e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function et(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function tt(e){return typeof e==`string`?e:e?.message}function D(e,t,n){let r=e.message?e.message:tt(e.inst?._zod.def?.error?.(e))??tt(t?.error?.(e))??tt(n.customError?.(e))??tt(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function nt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function rt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const it=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Ee,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},at=S(`$ZodError`,it),ot=S(`$ZodError`,it,{Parent:Error});function st(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function ct(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}function lt(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function O(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${lt(e.path)}`);return t.join(`
3
- `)}const ut=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Se;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>D(e,a,C())));throw Fe(t,i?.callee),t}return o.value},dt=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>D(e,a,C())));throw Fe(t,i?.callee),t}return o.value},ft=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Se;return a.issues.length?{success:!1,error:new(e??at)(a.issues.map(e=>D(e,i,C())))}:{success:!0,data:a.value}},pt=ft(ot),mt=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>D(e,i,C())))}:{success:!0,data:a.value}},ht=mt(ot),gt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ut(e)(t,n,i)},_t=e=>(t,n,r)=>ut(e)(t,n,r),vt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return dt(e)(t,n,i)},yt=e=>async(t,n,r)=>dt(e)(t,n,r),bt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ft(e)(t,n,i)},xt=e=>(t,n,r)=>ft(e)(t,n,r),St=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return mt(e)(t,n,i)},Ct=e=>async(t,n,r)=>mt(e)(t,n,r),wt=/^[cC][0-9a-z]{6,}$/,Tt=/^[0-9a-z]+$/,Et=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dt=/^[0-9a-vA-V]{20}$/,Ot=/^[A-Za-z0-9]{27}$/,kt=/^[a-zA-Z0-9_-]{21}$/,At=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Mt=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Nt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Pt(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const Ft=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,It=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Lt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Rt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bt=/^[A-Za-z0-9_-]*$/,Vt=/^https?$/,Ht=/^\+[1-9]\d{6,14}$/,Ut=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Wt=RegExp(`^${Ut}$`);function Gt(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Kt(e){return RegExp(`^${Gt(e)}$`)}function qt(e){let t=Gt({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Ut}T(?:${r})$`)}const Jt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Yt=/^-?\d+$/,Xt=/^-?\d+(?:\.\d+)?$/,Zt=/^(?:true|false)$/i,Qt=/^[^A-Z]*$/,$t=/^[^a-z]*$/,k=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),en={number:`number`,bigint:`bigint`,object:`date`},tn=S(`$ZodCheckLessThan`,(e,t)=>{k.init(e,t);let n=en[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),nn=S(`$ZodCheckGreaterThan`,(e,t)=>{k.init(e,t);let n=en[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rn=S(`$ZodCheckMultipleOf`,(e,t)=>{k.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Ae(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),an=S(`$ZodCheckNumberFormat`,(e,t)=>{k.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=We[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Yt)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),on=S(`$ZodCheckMaxLength`,(e,t)=>{var n;k.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=nt(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),sn=S(`$ZodCheckMinLength`,(e,t)=>{var n;k.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=nt(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),cn=S(`$ZodCheckLengthEquals`,(e,t)=>{var n;k.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=nt(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ln=S(`$ZodCheckStringFormat`,(e,t)=>{var n,r;k.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),un=S(`$ZodCheckRegex`,(e,t)=>{ln.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),dn=S(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Qt,ln.init(e,t)}),fn=S(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=$t,ln.init(e,t)}),pn=S(`$ZodCheckIncludes`,(e,t)=>{k.init(e,t);let n=Ve(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),mn=S(`$ZodCheckStartsWith`,(e,t)=>{k.init(e,t);let n=RegExp(`^${Ve(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),hn=S(`$ZodCheckEndsWith`,(e,t)=>{k.init(e,t);let n=RegExp(`.*${Ve(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),gn=S(`$ZodCheckOverwrite`,(e,t)=>{k.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var _n=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
4
- `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
5
- `))}};const vn={major:4,minor:4,patch:3},A=S(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=vn;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Qe(e),i;for(let a of t){if(a._zod.def.when){if($e(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Se;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Qe(e,t))});else{if(e.issues.length===t)continue;r||=Qe(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Qe(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Se;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Se;return o.then(e=>t(e,r,a))}return t(o,r,a)}}w(e,`~standard`,()=>({validate:t=>{try{let n=pt(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return ht(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),yn=S(`$ZodString`,(e,t)=>{A.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jt(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),j=S(`$ZodStringFormat`,(e,t)=>{ln.init(e,t),yn.init(e,t)}),bn=S(`$ZodGUID`,(e,t)=>{t.pattern??=jt,j.init(e,t)}),xn=S(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Mt(e)}else t.pattern??=Mt();j.init(e,t)}),Sn=S(`$ZodEmail`,(e,t)=>{t.pattern??=Nt,j.init(e,t)}),Cn=S(`$ZodURL`,(e,t)=>{j.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Vt.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),wn=S(`$ZodEmoji`,(e,t)=>{t.pattern??=Pt(),j.init(e,t)}),Tn=S(`$ZodNanoID`,(e,t)=>{t.pattern??=kt,j.init(e,t)}),En=S(`$ZodCUID`,(e,t)=>{t.pattern??=wt,j.init(e,t)}),Dn=S(`$ZodCUID2`,(e,t)=>{t.pattern??=Tt,j.init(e,t)}),On=S(`$ZodULID`,(e,t)=>{t.pattern??=Et,j.init(e,t)}),kn=S(`$ZodXID`,(e,t)=>{t.pattern??=Dt,j.init(e,t)}),An=S(`$ZodKSUID`,(e,t)=>{t.pattern??=Ot,j.init(e,t)}),jn=S(`$ZodISODateTime`,(e,t)=>{t.pattern??=qt(t),j.init(e,t)}),Mn=S(`$ZodISODate`,(e,t)=>{t.pattern??=Wt,j.init(e,t)}),Nn=S(`$ZodISOTime`,(e,t)=>{t.pattern??=Kt(t),j.init(e,t)}),Pn=S(`$ZodISODuration`,(e,t)=>{t.pattern??=At,j.init(e,t)}),Fn=S(`$ZodIPv4`,(e,t)=>{t.pattern??=Ft,j.init(e,t),e._zod.bag.format=`ipv4`}),In=S(`$ZodIPv6`,(e,t)=>{t.pattern??=It,j.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Ln=S(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Lt,j.init(e,t)}),Rn=S(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Rt,j.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function zn(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Bn=S(`$ZodBase64`,(e,t)=>{t.pattern??=zt,j.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{zn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Vn(e){if(!Bt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return zn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Hn=S(`$ZodBase64URL`,(e,t)=>{t.pattern??=Bt,j.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Vn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Un=S(`$ZodE164`,(e,t)=>{t.pattern??=Ht,j.init(e,t)});function Wn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Gn=S(`$ZodJWT`,(e,t)=>{j.init(e,t),e._zod.check=n=>{Wn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Kn=S(`$ZodNumber`,(e,t)=>{A.init(e,t),e._zod.pattern=e._zod.bag.pattern??Xt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),qn=S(`$ZodNumberFormat`,(e,t)=>{an.init(e,t),Kn.init(e,t)}),Jn=S(`$ZodBoolean`,(e,t)=>{A.init(e,t),e._zod.pattern=Zt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Yn=S(`$ZodUnknown`,(e,t)=>{A.init(e,t),e._zod.parse=e=>e}),Xn=S(`$ZodNever`,(e,t)=>{A.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Zn(e,t,n){e.issues.length&&t.issues.push(...et(n,e.issues)),t.value[n]=e.value}const Qn=S(`$ZodArray`,(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Zn(t,n,e))):Zn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function $n(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...et(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function er(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Ue(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function tr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>$n(e,n,i,t,u,d))):$n(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const nr=S(`$ZodObject`,(e,t)=>{if(A.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=De(()=>er(t));w(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Ie,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>$n(n,t,e,s,r,i))):$n(a,t,e,s,r,i)}return i?tr(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),rr=S(`$ZodObjectJIT`,(e,t)=>{nr.init(e,t);let n=e._zod.parse,r=De(()=>er(t)),i=e=>{let t=new _n([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Ne(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Ne(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
6
- if (${n}.issues.length) {
7
- if (${o} in input) {
8
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
9
- ...iss,
10
- path: iss.path ? [${o}, ...iss.path] : [${o}]
11
- })));
2
+ import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a,open as o,readFile as s,readdir as c,realpath as l,rename as u,rm as d,rmdir as f,stat as p,utimes as ee,writeFile as te}from"node:fs/promises";import ne,{basename as re,dirname as ie,isAbsolute as ae,join as m,posix as oe,relative as se,resolve as ce,sep as le}from"node:path";import{randomUUID as ue}from"node:crypto";import de,{existsSync as fe,realpathSync as pe}from"node:fs";import{homedir as me}from"node:os";import{setTimeout as he}from"node:timers/promises";import{EventEmitter as ge,once as _e}from"node:events";import ve,{spawn as ye}from"node:child_process";import h from"node:process";import{stripVTControlCharacters as be}from"node:util";const g={CONFLICT:5,NOT_FOUND:4,OK:0,UNEXPECTED:1,USAGE:2,VALIDATION:3};var _=class extends Error{code;exitCode;constructor(e,t,n,r){super(n,r),this.code=t,this.exitCode=e,this.name=`RefsError`}};const xe=e=>new _(g.CONFLICT,`conflict`,e),v=e=>new _(g.NOT_FOUND,`not_found`,e),y=e=>new _(g.USAGE,`usage`,e),b=e=>new _(g.VALIDATION,`validation`,e),Se=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,Ce=(e,t)=>e instanceof _?{code:e.code,exitCode:e.exitCode,message:Se(e.message,e.stack,t.verbose)}:e instanceof Error?{code:`unexpected`,exitCode:g.UNEXPECTED,message:Se(e.message,e.stack,t.verbose)}:{code:`unexpected`,exitCode:g.UNEXPECTED,message:String(e)};function we(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Te(e,t=`|`){return e.map(e=>He(e)).join(t)}function Ee(e,t){return typeof t==`bigint`?t.toString():t}function De(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Oe(e){return e==null}function ke(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ae(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function x(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function je(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Me(e){return JSON.stringify(e)}function Ne(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Pe=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Fe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ie=De(()=>{if(T.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Le(e){if(Fe(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Fe(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Re(e){return Le(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const ze=new Set([`string`,`number`,`symbol`]);function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ve(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function S(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function He(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Ue(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const We={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ge(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Ve(e,je(e._zod.def,{get shape(){let e={};for(let r of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,r))throw Error(`Unrecognized key: "${String(r)}"`);t[r]&&x(e,r,n.shape[r])}return x(this,`shape`,e),e},checks:[]}))}function Ke(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Ve(e,je(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,e))throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&delete r[e]}return x(this,`shape`,r),r},checks:[]}))}function qe(e,t){if(!Le(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ve(e,je(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return x(this,`shape`,n),n}}))}function Je(e,t){if(!Le(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ve(e,je(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return x(this,`shape`,n),n}}))}function Ye(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Ve(e,je(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return x(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Xe(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);return Ve(t,je(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(r,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t of Reflect.ownKeys(r))i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return x(this,`shape`,i),i},checks:[]}))}function Ze(e,t,n){return Ve(t,je(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(i,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t of Reflect.ownKeys(r))i[t]=new e({type:`nonoptional`,innerType:r[t]});return x(this,`shape`,i),i}}))}function Qe(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function $e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function et(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function tt(e){return typeof e==`string`?e:e?.message}function nt(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function rt(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:tt(e.inst?._zod.def?.error?.(e))??tt(a?.(e))??tt(t?.error?.(e))??tt(n.customError?.(e))??tt(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}const it=/[\uD800-\uDBFF]/;function at(e){let t=e.length;if(!it.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function ot(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function st(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function ct(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function lt(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):ft(e,n,r.value)}}function ut(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function dt(e,t,n){return ut(e,t,n,!1)}function ft(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:ut(this,t,n.bind(this))},set(e){ut(this,t,e)}})}function pt(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let mt,ht=!1;const gt={configurable:!0,get(){ht=!0}};function C(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&mt!==e._zod){mt=void 0;return}mt=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,gt);let e=ht;ht=!1;try{let r=n(this);return ht?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),ht||=e,r}catch(n){throw delete this[t],ht||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function _t(e,t,n,r){let i=pt(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function vt(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var yt;const bt={value:void 0,enumerable:!1};let xt=`captureStackTrace`in Error?Error:null;function St(e){let t=xt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return xt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function w(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){bt.value=new a(r);try{Object.defineProperty(n,"_zod",bt)}finally{bt.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),lt(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?St(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Ct=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},wt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(yt=globalThis).__zod_globalConfig??(yt.__zod_globalConfig={});const T=globalThis.__zod_globalConfig;function E(e){return e&&Object.assign(T,e),T}function Tt(){let e=this._zod;return e.message??=JSON.stringify(e.def,Ee,2),e.message}function Et(e){this._zod.message=e}const Dt={get:Tt,set:Et,enumerable:!0,configurable:!0},Ot={value:void 0,enumerable:!1},kt={value:void 0,enumerable:!1},At=new WeakSet([Object.prototype,Error.prototype]),jt=(e,t)=>{e.name=`$ZodError`,Ot.value=e._zod,Object.defineProperty(e,"_zod",Ot),kt.value=t,Object.defineProperty(e,"issues",kt),Ot.value=void 0,kt.value=void 0,Object.defineProperty(e,"message",Dt);let n=Object.getPrototypeOf(e);At.has(n)||(At.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Mt=w(`$ZodError`,jt),Nt=w(`$ZodError`,jt,void 0,{Parent:Error});function Pt(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Ft(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Pt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function It(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Lt(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function D(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${Lt(e.path)}`);return t.join(`
3
+ `)}function Rt(e,t){return{callee:t?.callee??e,Err:t?.Err}}const zt=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ct;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>rt(e,o,E())));throw Pe(n,a?.callee??t),n}return s.value};return t},Bt=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>rt(e,o,E())));throw Pe(n,a?.callee??t),n}return s.value};return t},Vt=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ct;return a.issues.length?{success:!1,error:new(e??Mt)(a.issues.map(e=>rt(e,i,E())))}:{success:!0,data:a.value}},Ht=Vt(Nt),Ut=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>rt(e,i,E())))}:{success:!0,data:a.value}},Wt=Ut(Nt),Gt=e=>{let t=zt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Rt(n,a))};return n},Kt=e=>{let t=zt(e),n=(e,r,i,a)=>t(e,r,i,Rt(n,a));return n},qt=e=>{let t=Bt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Rt(n,a))};return n},Jt=e=>{let t=Bt(e),n=async(e,r,i,a)=>await t(e,r,i,Rt(n,a));return n},Yt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Vt(e)(t,n,i)},Xt=e=>(t,n,r)=>Vt(e)(t,n,r),Zt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ut(e)(t,n,i)},Qt=e=>async(t,n,r)=>Ut(e)(t,n,r),$t=/^[cC][0-9a-z]{6,}$/,en=/^[0-9a-z]+$/,tn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,nn=/^[0-9a-vA-V]{20}$/,rn=/^[A-Za-z0-9]{27}$/,an=/^[a-zA-Z0-9_-]{21}$/;function on(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const sn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,cn=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ln=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,un=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function dn(){return RegExp(`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const fn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,mn=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,hn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_n=/^[A-Za-z0-9_-]*$/,vn=/^https?$/,yn=/^\+[1-9]\d{6,14}$/,bn=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function xn(e){return RegExp(`^${e}$`)}const Sn=xn(bn);function Cn(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function wn(e){return RegExp(`^${Cn(e)}$`)}function Tn(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Cn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Cn({precision:e.precision})}`:n;return RegExp(`^${bn}T(?:${r})$`)}const En=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Dn=/^-?\d+$/,On=/^-?\d+(?:\.\d+)?$/,kn=/^(?:true|false)$/i,An=/^[^A-Z]*$/,jn=/^[^a-z]*$/,O=w(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Mn=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0},Nn={number:`number`,bigint:`bigint`,object:`date`},Pn=w(`$ZodCheckLessThan`,(e,t)=>{O.init(e,t);let n=Nn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Nn[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Fn=w(`$ZodCheckGreaterThan`,(e,t)=>{O.init(e,t);let n=Nn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Nn[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),In=w(`$ZodCheckMultipleOf`,(e,t)=>{O.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Ae(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ln=w(`$ZodCheckNumberFormat`,(e,t)=>{O.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=We[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Dn)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Rn=w(`$ZodCheckMaxLength`,(e,t)=>{var n;O.init(e,t),(n=e._zod.def).when??(n.when=Mn),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?at(r):i)<=t.maximum)return;let a=ot(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),zn=w(`$ZodCheckMinLength`,(e,t)=>{var n;O.init(e,t),(n=e._zod.def).when??(n.when=Mn),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?at(r):i)>=t.minimum)return;let a=ot(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Bn=w(`$ZodCheckLengthEquals`,(e,t)=>{var n;O.init(e,t),(n=e._zod.def).when??(n.when=Mn),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?at(r):i;if(a===t.length)return;let o=ot(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Vn=w(`$ZodCheckStringFormat`,(e,t)=>{var n,r;O.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Hn=w(`$ZodCheckRegex`,(e,t)=>{Vn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Un=w(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=An,Vn.init(e,t)}),Wn=w(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=jn,Vn.init(e,t)}),Gn=w(`$ZodCheckIncludes`,(e,t)=>{O.init(e,t);let n=Be(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Kn=w(`$ZodCheckStartsWith`,(e,t)=>{O.init(e,t);let n=RegExp(`^${Be(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),qn=w(`$ZodCheckEndsWith`,(e,t)=>{O.init(e,t);let n=RegExp(`.*${Be(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Jn=w(`$ZodCheckOverwrite`,(e,t)=>{O.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Yn=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
4
+ `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
5
+ `)}\n};`)(...Object.values(this.closed))}};const Xn={major:4,minor:5,patch:2},k=w(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Xn;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=Qe(t),a;for(let o of n){if(o._zod.def.when){if($e(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Ct;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(nt(t.issues,n,e),i||=Qe(t,n))});else{if(t.issues.length===n)continue;nt(t.issues,n,e),i||=Qe(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(Qe(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Ct;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Ct;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return dt(this,`~standard`,Qn(this))},set"~standard"(e){ut(this,`~standard`,e)}}),Zn=e=>e.success?{value:e.data}:{issues:e.error?.issues};function Qn(e){return{validate:t=>{try{return Zn(Ht(e,t))}catch{return Wt(e,t).then(Zn)}},vendor:`zod`,version:1}}const $n=w(`$ZodString`,(e,t)=>{k.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??En(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),A=w(`$ZodStringFormat`,(e,t)=>{Vn.init(e,t),$n.init(e,t)}),er=w(`$ZodGUID`,(e,t)=>{t.pattern??=cn,A.init(e,t)}),tr=w(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=ln(e)}else t.pattern??=ln();A.init(e,t)}),nr=w(`$ZodEmail`,(e,t)=>{t.pattern??=un,A.init(e,t)});function rr(e,t){if(!t.normalize&&t.protocol?.source===vn.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}const ir=/[\t\n\r]/g;function ar(e){return e.replace(ir,``)}function or(e,t){return t.lastIndex=0,t.test(e.hostname)}function sr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const cr=w(`$ZodURL`,(e,t)=>{A.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=rr(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}t.hostname&&!or(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!sr(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:ar(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),lr=w(`$ZodEmoji`,(e,t)=>{t.pattern??=dn(),A.init(e,t)}),ur=w(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?an:on(t.length),A.init(e,t)}),dr=w(`$ZodCUID`,(e,t)=>{t.pattern??=$t,A.init(e,t)}),fr=w(`$ZodCUID2`,(e,t)=>{t.pattern??=en,A.init(e,t)}),pr=w(`$ZodULID`,(e,t)=>{t.pattern??=tn,A.init(e,t)}),mr=w(`$ZodXID`,(e,t)=>{t.pattern??=nn,A.init(e,t)}),hr=w(`$ZodKSUID`,(e,t)=>{t.pattern??=rn,A.init(e,t)}),gr=w(`$ZodISODateTime`,(e,t)=>{t.pattern??=Tn(t),A.init(e,t),(t.local||t.precision===-1)&&(e._zod.bag.laxFormat=!0,e._zod.onattach.push(e=>{e._zod.bag.laxFormat=!0}))}),_r=w(`$ZodISODate`,(e,t)=>{t.pattern??=Sn,A.init(e,t)}),vr=w(`$ZodISOTime`,(e,t)=>{t.pattern??=wn(t),A.init(e,t)}),yr=w(`$ZodISODuration`,(e,t)=>{t.pattern??=sn,A.init(e,t)}),br=w(`$ZodIPv4`,(e,t)=>{t.pattern??=fn,A.init(e,t),e._zod.bag.format=`ipv4`}),xr=/^[0-9a-fA-F:.]+$/;function Sr(e){if(!xr.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}const Cr=w(`$ZodIPv6`,(e,t)=>{t.pattern??=pn,A.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{Sr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),wr=w(`$ZodCIDRv4`,(e,t)=>{t.pattern??=mn,A.init(e,t)});function Tr(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Sr(n)}const Er=w(`$ZodCIDRv6`,(e,t)=>{t.pattern??=hn,A.init(e,t),e._zod.check=n=>{Tr(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Dr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Or=w(`$ZodBase64`,(e,t)=>{t.pattern??=gn,A.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Dr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function kr(e){if(!_n.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Dr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Ar=w(`$ZodBase64URL`,(e,t)=>{t.pattern??=_n,A.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{kr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),jr=w(`$ZodE164`,(e,t)=>{t.pattern??=yn,A.init(e,t)});function Mr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Nr=w(`$ZodJWT`,(e,t)=>{A.init(e,t),e._zod.check=n=>{Mr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Pr=w(`$ZodNumber`,(e,t)=>{k.init(e,t),e._zod.pattern=e._zod.bag.pattern??On,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Fr=w(`$ZodNumberFormat`,(e,t)=>{Ln.init(e,t),Pr.init(e,t)}),Ir=w(`$ZodBoolean`,(e,t)=>{k.init(e,t),e._zod.pattern=kn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Lr=w(`$ZodUnknown`,(e,t)=>{k.init(e,t),e._zod.parse=e=>e}),Rr=w(`$ZodNever`,(e,t)=>{k.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function zr(e,t,n){e.issues.length&&t.issues.push(...et(n,e.issues)),t.value[n]=e.value}const Br=w(`$ZodArray`,(e,t)=>{k.init(e,t);let n=T.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>zr(t,r,e))):zr(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function Vr(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(!(!o&&s&&i===`optional`)){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...et(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}}const Hr=[];function Ur(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Hr,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Ue(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Wr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Vr(e,n,i,t,u,d))):Vr(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Gr=new WeakMap,Kr=w(`$ZodObject`,(e,t)=>{if(k.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Gr.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),Gr.set(t,n),n}})}let n=De(()=>Ur(t));C(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||x(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let r=Fe,i=t.catchall,a,o=T.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>Vr(n,t,e,c,r,i))):Vr(a,t,e,c,r,i)}return i?Wr(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),qr=w(`$ZodObjectJIT`,(e,t)=>{Kr.init(e,t);let n=e._zod.parse,r=De(()=>Ur(t)),i=T.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Yn([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
6
+ for (let i = 0; i < ${e}.issues.length; i++) {
7
+ const iss = ${e}.issues[i];
8
+ iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
9
+ payload.issues.push(iss);
10
+ }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:Me(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
11
+ const ${n}_present = ${i};
12
+ if (!${n}.issues.length || ${n}_present) {
13
+ if (${n}.issues.length) {${c(n,r)}
12
14
  }
13
- }
14
-
15
- if (${n}.value === undefined) {
16
- if (${o} in input) {
17
- newResult[${o}] = undefined;
15
+
16
+ if (${e}) {
17
+ newResult[${r}] = ${n}.value;
18
18
  }
19
- } else {
20
- newResult[${o}] = ${n}.value;
21
19
  }
22
-
23
- `):c?t.write(`
24
- if (${n}.issues.length) {
25
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
26
- ...iss,
27
- path: iss.path ? [${o}, ...iss.path] : [${o}]
28
- })));
20
+
21
+ `)}else f?o.write(`
22
+ if (${n}.issues.length) {${c(n,r)}
29
23
  }
30
24
 
31
25
  if (${n}.value === undefined) {
32
- if (${o} in input) {
33
- newResult[${o}] = undefined;
26
+ if (${i}) {
27
+ newResult[${r}] = undefined;
34
28
  }
35
29
  } else {
36
- newResult[${o}] = ${n}.value;
30
+ newResult[${r}] = ${n}.value;
37
31
  }
38
-
39
- `):t.write(`
40
- const ${n}_present = ${o} in input;
41
- if (${n}.issues.length) {
42
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
43
- ...iss,
44
- path: iss.path ? [${o}, ...iss.path] : [${o}]
45
- })));
32
+
33
+ `):o.write(`
34
+ const ${n}_present = ${i};
35
+ if (${n}.issues.length) {${c(n,r)}
46
36
  }
47
37
  if (!${n}_present && !${n}.issues.length) {
48
38
  payload.issues.push({
49
39
  code: "invalid_type",
50
40
  expected: "nonoptional",
51
41
  input: undefined,
52
- path: [${o}]
42
+ path: [${r}]
53
43
  });
54
44
  }
55
45
 
56
46
  if (${n}_present) {
57
- if (${n}.value === undefined) {
58
- newResult[${o}] = undefined;
59
- } else {
60
- newResult[${o}] = ${n}.value;
61
- }
47
+ newResult[${r}] = ${n}.value;
62
48
  }
63
49
 
64
- `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Ie,s=!we.jitless,c=s&&Le.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?tr([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function ir(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Qe(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>D(e,r,C())))}),t)}const ar=S(`$ZodUnion`,(e,t)=>{A.init(e,t),w(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),w(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),w(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),w(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>ke(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>ir(t,r,e,i)):ir(o,r,e,i)}}),or=S(`$ZodIntersection`,(e,t)=>{A.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>cr(e,t,n)):cr(e,i,a)}});function sr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Re(e)&&Re(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=sr(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=sr(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function cr(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Qe(e))return e;let o=sr(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const lr=S(`$ZodRecord`,(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Re(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>D(e,r,C())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...et(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...et(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Xt.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>D(e,r,C())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...et(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...et(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ur=S(`$ZodEnum`,(e,t)=>{A.init(e,t);let n=Te(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Be.has(typeof e)).map(e=>typeof e==`string`?Ve(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),dr=S(`$ZodTransform`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Se;return n.value=i,n.fallback=!0,n}});function fr(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const pr=S(`$ZodOptional`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,w(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),w(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ke(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>fr(e,r)):fr(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),mr=S(`$ZodExactOptional`,(e,t)=>{pr.init(e,t),w(e._zod,`values`,()=>t.innerType._zod.values),w(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),hr=S(`$ZodNullable`,(e,t)=>{A.init(e,t),w(e._zod,`optin`,()=>t.innerType._zod.optin),w(e._zod,`optout`,()=>t.innerType._zod.optout),w(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ke(e.source)}|null)$`):void 0}),w(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),gr=S(`$ZodDefault`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,w(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>_r(e,t)):_r(r,t)}});function _r(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const vr=S(`$ZodPrefault`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,w(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),yr=S(`$ZodNonOptional`,(e,t)=>{A.init(e,t),w(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>br(t,e)):br(i,e)}});function br(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const xr=S(`$ZodCatch`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,w(e._zod,`optout`,()=>t.innerType._zod.optout),w(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>D(e,n,C()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>D(e,n,C()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Sr=S(`$ZodPipe`,(e,t)=>{A.init(e,t),w(e._zod,`values`,()=>t.in._zod.values),w(e._zod,`optin`,()=>t.in._zod.optin),w(e._zod,`optout`,()=>t.out._zod.optout),w(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Cr(e,t.in,n)):Cr(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Cr(e,t.out,n)):Cr(r,t.out,n)}});function Cr(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const wr=S(`$ZodPreprocess`,(e,t)=>{Sr.init(e,t)}),Tr=S(`$ZodReadonly`,(e,t)=>{A.init(e,t),w(e._zod,`propValues`,()=>t.innerType._zod.propValues),w(e._zod,`values`,()=>t.innerType._zod.values),w(e._zod,`optin`,()=>t.innerType?._zod?.optin),w(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Er):Er(r)}});function Er(e){return e.value=Object.freeze(e.value),e}const Dr=S(`$ZodCustom`,(e,t)=>{k.init(e,t),A.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Or(t,n,r,e));Or(i,n,r,e)}});function Or(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(rt(e))}}var kr,Ar=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function jr(){return new Ar}(kr=globalThis).__zod_globalRegistry??(kr.__zod_globalRegistry=jr());const Mr=globalThis.__zod_globalRegistry;function Nr(e,t){return new e({type:`string`,...E(t)})}function Pr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...E(t)})}function Fr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...E(t)})}function Ir(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...E(t)})}function Lr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...E(t)})}function Rr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...E(t)})}function zr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...E(t)})}function Br(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...E(t)})}function Vr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...E(t)})}function Hr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...E(t)})}function Ur(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...E(t)})}function Wr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...E(t)})}function Gr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...E(t)})}function Kr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...E(t)})}function qr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...E(t)})}function Jr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...E(t)})}function Yr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...E(t)})}function Xr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...E(t)})}function Zr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...E(t)})}function Qr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...E(t)})}function $r(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...E(t)})}function ei(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...E(t)})}function ti(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...E(t)})}function ni(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...E(t)})}function ri(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...E(t)})}function ii(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...E(t)})}function ai(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...E(t)})}function oi(e,t){return new e({type:`number`,checks:[],...E(t)})}function si(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...E(t)})}function ci(e,t){return new e({type:`boolean`,...E(t)})}function li(e){return new e({type:`unknown`})}function ui(e,t){return new e({type:`never`,...E(t)})}function di(e,t){return new tn({check:`less_than`,...E(t),value:e,inclusive:!1})}function fi(e,t){return new tn({check:`less_than`,...E(t),value:e,inclusive:!0})}function pi(e,t){return new nn({check:`greater_than`,...E(t),value:e,inclusive:!1})}function mi(e,t){return new nn({check:`greater_than`,...E(t),value:e,inclusive:!0})}function hi(e,t){return new rn({check:`multiple_of`,...E(t),value:e})}function gi(e,t){return new on({check:`max_length`,...E(t),maximum:e})}function _i(e,t){return new sn({check:`min_length`,...E(t),minimum:e})}function vi(e,t){return new cn({check:`length_equals`,...E(t),length:e})}function yi(e,t){return new un({check:`string_format`,format:`regex`,...E(t),pattern:e})}function bi(e){return new dn({check:`string_format`,format:`lowercase`,...E(e)})}function xi(e){return new fn({check:`string_format`,format:`uppercase`,...E(e)})}function Si(e,t){return new pn({check:`string_format`,format:`includes`,...E(t),includes:e})}function Ci(e,t){return new mn({check:`string_format`,format:`starts_with`,...E(t),prefix:e})}function wi(e,t){return new hn({check:`string_format`,format:`ends_with`,...E(t),suffix:e})}function Ti(e){return new gn({check:`overwrite`,tx:e})}function Ei(e){return Ti(t=>t.normalize(e))}function Di(){return Ti(e=>e.trim())}function Oi(){return Ti(e=>e.toLowerCase())}function ki(){return Ti(e=>e.toUpperCase())}function Ai(){return Ti(e=>Pe(e))}function ji(e,t,n){return new e({type:`array`,element:t,...E(n)})}function Mi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...E(n)})}function Ni(e,t){let n=Pi(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(rt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(rt(r))}},e(t.value,t)),t);return n}function Pi(e,t){let n=new k({check:`custom`,...E(t)});return n._zod.check=e,n}function Fi(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Mr,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function M(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,M(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&N(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ii(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
50
+ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Fe,c=!T.jitless,l=c&&Ie.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Wr([],p,i,f,d,e):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Jr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Qe(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>rt(e,r,E())))}),t)}const Yr=w(`$ZodUnion`,(e,t)=>{k.init(e,t),C(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),C(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),C(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),C(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>ke(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Jr(t,r,e,i)):Jr(o,r,e,i)}}),Xr=w(`$ZodIntersection`,(e,t)=>{k.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Qr(e,t,n)):Qr(e,i,a)}});function Zr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Le(e)&&Le(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=Zr(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Zr(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Qr(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=Zr(t.value,n.value);if(!c.valid){if(Qe(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const $r=w(`$ZodRecord`,(e,t)=>{k.init(e,t);let n=T.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Le(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>rt(e,i,E())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...et(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...et(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&On.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>rt(e,i,E())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...et(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...et(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),ei=w(`$ZodEnum`,(e,t)=>{k.init(e,t);let n=we(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>ze.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>Be(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),ti=w(`$ZodTransform`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,T.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new wt(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Ct;return n.value=i,n}});function ni(e,t){return e.value=t.issues.length?void 0:t.value,e}const ri=w(`$ZodOptional`,(e,t)=>{k.init(e,t),C(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,C(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),C(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${ke(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ni(e,t)):ni(e,r)}return t.innerType._zod.run(e,n)}}),ii=w(`$ZodExactOptional`,(e,t)=>{ri.init(e,t),C(e,`values`,e=>e.def.innerType._zod.values),C(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ai=w(`$ZodNullable`,(e,t)=>{k.init(e,t),C(e,`optin`,e=>e.def.innerType._zod.optin),C(e,`optout`,e=>e.def.innerType._zod.optout),C(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${ke(t.source)}|null)$`):void 0}),C(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),oi=w(`$ZodDefault`,(e,t)=>{k.init(e,t),e._zod.optin=`defaulted`,C(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>si(e,t)):si(r,t)}});function si(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const ci=w(`$ZodPrefault`,(e,t)=>{k.init(e,t),e._zod.optin=`defaulted`,C(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),li=w(`$ZodNonOptional`,(e,t)=>{k.init(e,t),C(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>ui(t,e)):ui(i,e)}});function ui(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function di(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>rt(e,r,E()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const fi=w(`$ZodCatch`,(e,t)=>{k.init(e,t),C(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),C(e,`optout`,e=>e.def.innerType._zod.optout),C(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>di(e,r,t,n)):di(e,r,t,n)}}),pi=w(`$ZodPipe`,(e,t)=>{k.init(e,t),C(e,`values`,e=>e.def.in._zod.values),C(e,`optin`,e=>e.def.in._zod.optin),C(e,`optout`,e=>e.def.out._zod.optout),C(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>mi(e,t.in,n)):mi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>mi(e,t.out,n)):mi(r,t.out,n)}});function mi(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const hi=w(`$ZodPreprocess`,(e,t)=>{pi.init(e,t)}),gi=w(`$ZodReadonly`,(e,t)=>{k.init(e,t),C(e,`propValues`,e=>e.def.innerType._zod.propValues),C(e,`values`,e=>e.def.innerType._zod.values),C(e,`optin`,e=>e.def.innerType?._zod?.optin),C(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(_i):_i(r)}});function _i(e){return e.memo||(e.value=Object.freeze(e.value)),e}const vi=w(`$ZodCustom`,(e,t)=>{O.init(e,t),k.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>yi(t,n,r,e));yi(i,n,r,e)}});function yi(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ct(e))}}var bi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const xi=`~memo`,Si=[];function Ci(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const wi=new WeakMap;function Ti(e,t){let n=wi.get(e);if(n!==void 0)return n;if(t.has(e))return!0;t.add(e);let r=!1,i=e=>{!r&&e?._zod&&Ti(e,t)&&(r=!0)},a=e._zod.def;if(a.type===`lazy`)i(e._zod.innerType);else{let e=a.shape;if(e)for(let t of Reflect.ownKeys(e))i(e[t]);for(let e in a){let t=a[e];if(!(!t||typeof t!=`object`)){if(t._zod)i(t);else if(Array.isArray(t))for(let e of t)i(e)}}}return t.delete(e),wi.set(e,r),r}function Ei(e,t){let n=e.buckets.get(t);return n||(n=new Map,e.buckets.set(t,n)),n}let Di;const Oi=[],ki={alloc(e,t,n){let r=Di;if(!r)return n;Di=void 0;let i={value:n,issues:null};return r.set(t.value,i),Oi.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&ji(n,e.value))throw new bi;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,a=(o,s)=>{if(n===void 0&&(n=Ti(e,new Set),!n))return e._zod.parse=t,e._zod.run===a&&(e._zod.run=t),t(o,s);let c=o.value;if(typeof c!=`object`||!c)return t(o,s);let l=s[xi];l||(l={buckets:new Map,backEdges:void 0},s[xi]=l);let u;r===s?u=i:(u=Ei(l,e),r=s,i=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...Ci(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=new Set),l.backEdges.add(d.value)),o;Di=u;let f=Oi.length,p=t(o,s);Di=void 0;let ee=Oi.length>f?Oi.pop():void 0;return p instanceof Promise?p.then(e=>(ee&&(ee.issues=e.issues.length?Ci(e.issues):Si),e)):(ee&&(ee.issues=p.issues.length?Ci(p.issues):Si),p)};e._zod.parse=a,e._zod.run===t&&(e._zod.run=a)})}};function Ai(){return ki}function ji(e,t){let n=e[xi]?.backEdges;return n!==void 0&&typeof t==`object`&&!!t&&n.has(t)}const Mi=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,credit_card:`credit card number`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(st(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${He(e.values[0])}`:`Invalid option: expected one of ${Te(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${Te(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Ni(){return{localeError:Mi()}}var Pi,Fi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ii(){return new Fi}(Pi=globalThis).__zod_globalRegistry??(Pi.__zod_globalRegistry=Ii());const Li=globalThis.__zod_globalRegistry;function Ri(e,t){return new e({type:`string`,...S(t)})}function zi(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...S(t)})}function Bi(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...S(t)})}function Vi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...S(t)})}function Hi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...S(t)})}function Ui(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...S(t)})}function Wi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...S(t)})}function Gi(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...S(t)})}function Ki(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...S(t)})}function qi(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...S(t)})}function Ji(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...S(t)})}function Yi(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...S(t)})}function Xi(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...S(t)})}function Zi(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...S(t)})}function Qi(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...S(t)})}function $i(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...S(t)})}function ea(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...S(t)})}function ta(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...S(t)})}function na(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...S(t)})}function ra(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...S(t)})}function ia(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...S(t)})}function aa(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...S(t)})}function oa(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...S(t)})}function sa(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...S(t)})}function ca(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...S(t)})}function la(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...S(t)})}function ua(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...S(t)})}function da(e,t){return new e({type:`number`,checks:[],...S(t)})}function fa(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...S(t)})}function pa(e,t){return new e({type:`boolean`,...S(t)})}function ma(e){return new e({type:`unknown`})}function ha(e,t){return new e({type:`never`,...S(t)})}function ga(e,t){return new Pn({check:`less_than`,...S(t),value:e,inclusive:!1})}function _a(e,t){return new Pn({check:`less_than`,...S(t),value:e,inclusive:!0})}function va(e,t){return new Fn({check:`greater_than`,...S(t),value:e,inclusive:!1})}function ya(e,t){return new Fn({check:`greater_than`,...S(t),value:e,inclusive:!0})}function ba(e,t){return new In({check:`multiple_of`,...S(t),value:e})}function xa(e,t){return new Rn({check:`max_length`,...S(t),maximum:e})}function Sa(e,t){return new zn({check:`min_length`,...S(t),minimum:e})}function Ca(e,t){return new Bn({check:`length_equals`,...S(t),length:e})}function wa(e,t){return new Hn({check:`string_format`,format:`regex`,...S(t),pattern:e})}function Ta(e){return new Un({check:`string_format`,format:`lowercase`,...S(e)})}function Ea(e){return new Wn({check:`string_format`,format:`uppercase`,...S(e)})}function Da(e,t){return new Gn({check:`string_format`,format:`includes`,...S(t),includes:e})}function Oa(e,t){return new Kn({check:`string_format`,format:`starts_with`,...S(t),prefix:e})}function ka(e,t){return new qn({check:`string_format`,format:`ends_with`,...S(t),suffix:e})}function Aa(e){return new Jn({check:`overwrite`,tx:e})}function ja(e){return Aa(t=>t.normalize(e))}function Ma(){return Aa(e=>e.trim())}function Na(){return Aa(e=>e.toLowerCase())}function Pa(){return Aa(e=>e.toUpperCase())}function Fa(){return Aa(e=>Ne(e))}function Ia(e,t,n){return new e({type:`array`,element:t,...S(n)})}function La(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...S(n)})}function Ra(e,t){let n=za(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(ct(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(ct(r))}},e(t.value,t)),t);return n}function za(e,t){let n=new O({check:`custom`,...S(t)});return n._zod.check=e,n}function Ba(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&x(e,t,n[t]);return e}function Va(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Li,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],external:e?.external??void 0}}function Ha(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function j(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,j(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Ba(o.schema,c),t.io===`input`&&M(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ua(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Wa(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${Ua(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+Ua(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
65
51
 
66
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Li(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:zi(t,`input`,e.processors),output:zi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function N(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return N(r.element,n);if(r.type===`set`)return N(r.valueType,n);if(r.type===`lazy`)return N(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return N(r.innerType,n);if(r.type===`intersection`)return N(r.left,n)||N(r.right,n);if(r.type===`record`||r.type===`map`)return N(r.keyType,n)||N(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:N(r.in,n)||N(r.out,n);if(r.type===`object`){for(let e in r.shape)if(N(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(N(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(N(e,n))return!0;return!!(r.rest&&N(r.rest,n))}return!1}const Ri=(e,t={})=>n=>{let r=Fi({...n,processors:t});return M(e,r),Ii(r,e),Li(r,e)},zi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Fi({...i??{},target:a,io:t,processors:n});return M(e,o),Ii(o,e),Li(o,e)},Bi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Vi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Bi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Hi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Ui=(e,t,n,r)=>{n.type=`boolean`},Wi=(e,t,n,r)=>{n.not={}},Gi=(e,t,n,r)=>{let i=e._zod.def,a=Te(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ki=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},qi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ji=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=M(a.element,t,{...r,path:[...r.path,`items`]})},Yi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=M(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=M(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Xi=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>M(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Zi=(e,t,n,r)=>{let i=e._zod.def,a=M(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=M(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Qi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=M(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=M(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=M(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},$i=(e,t,n,r)=>{let i=e._zod.def,a=M(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},ea=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ta=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},na=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ra=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},ia=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;M(o,t,r);let s=t.seen.get(e);s.ref=o},aa=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},oa=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},sa=S(`ZodISODateTime`,(e,t)=>{jn.init(e,t),L.init(e,t)});function ca(e){return ni(sa,e)}const la=S(`ZodISODate`,(e,t)=>{Mn.init(e,t),L.init(e,t)});function ua(e){return ri(la,e)}const da=S(`ZodISOTime`,(e,t)=>{Nn.init(e,t),L.init(e,t)});function fa(e){return ii(da,e)}const pa=S(`ZodISODuration`,(e,t)=>{Pn.init(e,t),L.init(e,t)});function ma(e){return ai(pa,e)}const P=S(`ZodError`,(e,t)=>{at.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>ct(e,t)},flatten:{value:t=>st(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ee,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ee,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ha=ut(P),ga=dt(P),_a=ft(P),va=mt(P),ya=gt(P),ba=_t(P),xa=vt(P),Sa=yt(P),Ca=bt(P),wa=xt(P),Ta=St(P),Ea=Ct(P),Da=new WeakMap;function Oa(e,t,n){let r=Object.getPrototypeOf(e),i=Da.get(r);if(i||(i=new Set,Da.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}const F=S(`ZodType`,(e,t)=>(A.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:zi(e,`input`),output:zi(e,`output`)}}),e.toJSONSchema=Ri(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>ha(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>_a(e,t,n),e.parseAsync=async(t,n)=>ga(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>va(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ya(e,t,n),e.decode=(t,n)=>ba(e,t,n),e.encodeAsync=async(t,n)=>xa(e,t,n),e.decodeAsync=async(t,n)=>Sa(e,t,n),e.safeEncode=(t,n)=>Ca(e,t,n),e.safeDecode=(t,n)=>wa(e,t,n),e.safeEncodeAsync=async(t,n)=>Ta(e,t,n),e.safeDecodeAsync=async(t,n)=>Ea(e,t,n),Oa(e,`ZodType`,{check(...e){let t=this.def;return this.clone(T(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return He(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Vo(e,t))},superRefine(e,t){return this.check(Ho(e,t))},overwrite(e){return this.check(Ti(e))},optional(){return So(this)},exactOptional(){return wo(this)},nullable(){return Eo(this)},nullish(){return So(Eo(this))},nonoptional(e){return Mo(this,e)},array(){return so(this)},or(e){return fo([this,e])},and(e){return mo(this,e)},transform(e){return Io(this,bo(e))},default(e){return Oo(this,e)},prefault(e){return Ao(this,e)},catch(e){return Po(this,e)},pipe(e){return Io(this,e)},readonly(){return zo(this)},describe(e){let t=this.clone();return Mr.add(t,{description:e}),t},meta(...e){if(e.length===0)return Mr.get(this);let t=this.clone();return Mr.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Mr.get(e)?.description},configurable:!0}),e)),ka=S(`_ZodString`,(e,t)=>{yn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Oa(e,`_ZodString`,{regex(...e){return this.check(yi(...e))},includes(...e){return this.check(Si(...e))},startsWith(...e){return this.check(Ci(...e))},endsWith(...e){return this.check(wi(...e))},min(...e){return this.check(_i(...e))},max(...e){return this.check(gi(...e))},length(...e){return this.check(vi(...e))},nonempty(...e){return this.check(_i(1,...e))},lowercase(e){return this.check(bi(e))},uppercase(e){return this.check(xi(e))},trim(){return this.check(Di())},normalize(...e){return this.check(Ei(...e))},toLowerCase(){return this.check(Oi())},toUpperCase(){return this.check(ki())},slugify(){return this.check(Ai())}})}),Aa=S(`ZodString`,(e,t)=>{yn.init(e,t),ka.init(e,t),e.email=t=>e.check(Pr(ja,t)),e.url=t=>e.check(Br(Pa,t)),e.jwt=t=>e.check(ti(Ya,t)),e.emoji=t=>e.check(Vr(Fa,t)),e.guid=t=>e.check(Fr(Ma,t)),e.uuid=t=>e.check(Ir(Na,t)),e.uuidv4=t=>e.check(Lr(Na,t)),e.uuidv6=t=>e.check(Rr(Na,t)),e.uuidv7=t=>e.check(zr(Na,t)),e.nanoid=t=>e.check(Hr(Ia,t)),e.guid=t=>e.check(Fr(Ma,t)),e.cuid=t=>e.check(Ur(La,t)),e.cuid2=t=>e.check(Wr(Ra,t)),e.ulid=t=>e.check(Gr(za,t)),e.base64=t=>e.check(Qr(Ka,t)),e.base64url=t=>e.check($r(qa,t)),e.xid=t=>e.check(Kr(Ba,t)),e.ksuid=t=>e.check(qr(Va,t)),e.ipv4=t=>e.check(Jr(Ha,t)),e.ipv6=t=>e.check(Yr(Ua,t)),e.cidrv4=t=>e.check(Xr(Wa,t)),e.cidrv6=t=>e.check(Zr(Ga,t)),e.e164=t=>e.check(ei(Ja,t)),e.datetime=t=>e.check(ca(t)),e.date=t=>e.check(ua(t)),e.time=t=>e.check(fa(t)),e.duration=t=>e.check(ma(t))});function I(e){return Nr(Aa,e)}const L=S(`ZodStringFormat`,(e,t)=>{j.init(e,t),ka.init(e,t)}),ja=S(`ZodEmail`,(e,t)=>{Sn.init(e,t),L.init(e,t)}),Ma=S(`ZodGUID`,(e,t)=>{bn.init(e,t),L.init(e,t)}),Na=S(`ZodUUID`,(e,t)=>{xn.init(e,t),L.init(e,t)}),Pa=S(`ZodURL`,(e,t)=>{Cn.init(e,t),L.init(e,t)}),Fa=S(`ZodEmoji`,(e,t)=>{wn.init(e,t),L.init(e,t)}),Ia=S(`ZodNanoID`,(e,t)=>{Tn.init(e,t),L.init(e,t)}),La=S(`ZodCUID`,(e,t)=>{En.init(e,t),L.init(e,t)}),Ra=S(`ZodCUID2`,(e,t)=>{Dn.init(e,t),L.init(e,t)}),za=S(`ZodULID`,(e,t)=>{On.init(e,t),L.init(e,t)}),Ba=S(`ZodXID`,(e,t)=>{kn.init(e,t),L.init(e,t)}),Va=S(`ZodKSUID`,(e,t)=>{An.init(e,t),L.init(e,t)}),Ha=S(`ZodIPv4`,(e,t)=>{Fn.init(e,t),L.init(e,t)}),Ua=S(`ZodIPv6`,(e,t)=>{In.init(e,t),L.init(e,t)}),Wa=S(`ZodCIDRv4`,(e,t)=>{Ln.init(e,t),L.init(e,t)}),Ga=S(`ZodCIDRv6`,(e,t)=>{Rn.init(e,t),L.init(e,t)}),Ka=S(`ZodBase64`,(e,t)=>{Bn.init(e,t),L.init(e,t)}),qa=S(`ZodBase64URL`,(e,t)=>{Hn.init(e,t),L.init(e,t)}),Ja=S(`ZodE164`,(e,t)=>{Un.init(e,t),L.init(e,t)}),Ya=S(`ZodJWT`,(e,t)=>{Gn.init(e,t),L.init(e,t)}),Xa=S(`ZodNumber`,(e,t)=>{Kn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(e,t,n,r),Oa(e,`ZodNumber`,{gt(e,t){return this.check(pi(e,t))},gte(e,t){return this.check(mi(e,t))},min(e,t){return this.check(mi(e,t))},lt(e,t){return this.check(di(e,t))},lte(e,t){return this.check(fi(e,t))},max(e,t){return this.check(fi(e,t))},int(e){return this.check($a(e))},safe(e){return this.check($a(e))},positive(e){return this.check(pi(0,e))},nonnegative(e){return this.check(mi(0,e))},negative(e){return this.check(di(0,e))},nonpositive(e){return this.check(fi(0,e))},multipleOf(e,t){return this.check(hi(e,t))},step(e,t){return this.check(hi(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Za(e){return oi(Xa,e)}const Qa=S(`ZodNumberFormat`,(e,t)=>{qn.init(e,t),Xa.init(e,t)});function $a(e){return si(Qa,e)}const eo=S(`ZodBoolean`,(e,t)=>{Jn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(e,t,n,r)});function to(e){return ci(eo,e)}const no=S(`ZodUnknown`,(e,t)=>{Yn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function ro(){return li(no)}const io=S(`ZodNever`,(e,t)=>{Xn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r)});function ao(e){return ui(io,e)}const oo=S(`ZodArray`,(e,t)=>{Qn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ji(e,t,n,r),e.element=t.element,Oa(e,`ZodArray`,{min(e,t){return this.check(_i(e,t))},nonempty(e){return this.check(_i(1,e))},max(e,t){return this.check(gi(e,t))},length(e,t){return this.check(vi(e,t))},unwrap(){return this.element}})});function so(e,t){return ji(oo,e,t)}const co=S(`ZodObject`,(e,t)=>{rr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yi(e,t,n,r),w(e,`shape`,()=>t.shape),Oa(e,`ZodObject`,{keyof(){return vo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:ro()})},loose(){return this.clone({...this._zod.def,catchall:ro()})},strict(){return this.clone({...this._zod.def,catchall:ao()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return qe(this,e)},safeExtend(e){return Je(this,e)},merge(e){return Ye(this,e)},pick(e){return Ge(this,e)},omit(e){return Ke(this,e)},partial(...e){return Xe(xo,this,e[0])},required(...e){return Ze(jo,this,e[0])}})});function R(e,t){return new co({type:`object`,shape:e,catchall:ao(),...E(t)})}function lo(e,t){return new co({type:`object`,shape:e,catchall:ro(),...E(t)})}const uo=S(`ZodUnion`,(e,t)=>{ar.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.options=t.options});function fo(e,t){return new uo({type:`union`,options:e,...E(t)})}const po=S(`ZodIntersection`,(e,t)=>{or.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r)});function mo(e,t){return new po({type:`intersection`,left:e,right:t})}const ho=S(`ZodRecord`,(e,t)=>{lr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function go(e,t,n){return!t||!t._zod?new ho({type:`record`,keyType:I(),valueType:e,...E(t)}):new ho({type:`record`,keyType:e,valueType:t,...E(n)})}const _o=S(`ZodEnum`,(e,t)=>{ur.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new _o({...t,checks:[],...E(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new _o({...t,checks:[],...E(r),entries:i})}});function vo(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new _o({type:`enum`,entries:n,...E(t)})}const yo=S(`ZodTransform`,(e,t)=>{dr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qi(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(rt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(rt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bo(e){return new yo({type:`transform`,transform:e})}const xo=S(`ZodOptional`,(e,t)=>{pr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function So(e){return new xo({type:`optional`,innerType:e})}const Co=S(`ZodExactOptional`,(e,t)=>{mr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wo(e){return new Co({type:`optional`,innerType:e})}const To=S(`ZodNullable`,(e,t)=>{hr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Eo(e){return new To({type:`nullable`,innerType:e})}const Do=S(`ZodDefault`,(e,t)=>{gr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Oo(e,t){return new Do({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}const ko=S(`ZodPrefault`,(e,t)=>{vr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ao(e,t){return new ko({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}const jo=S(`ZodNonOptional`,(e,t)=>{yr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Mo(e,t){return new jo({type:`nonoptional`,innerType:e,...E(t)})}const No=S(`ZodCatch`,(e,t)=>{xr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Po(e,t){return new No({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const Fo=S(`ZodPipe`,(e,t)=>{Sr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r),e.in=t.in,e.out=t.out});function Io(e,t){return new Fo({type:`pipe`,in:e,out:t})}const Lo=S(`ZodPreprocess`,(e,t)=>{Fo.init(e,t),wr.init(e,t)}),Ro=S(`ZodReadonly`,(e,t)=>{Tr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function zo(e){return new Ro({type:`readonly`,innerType:e})}const Bo=S(`ZodCustom`,(e,t)=>{Dr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r)});function Vo(e,t={}){return Mi(Bo,e,t)}function Ho(e,t){return Ni(e,t)}function Uo(e,t){return new Lo({type:`pipe`,in:bo(e),out:t})}const Wo=new Set([`__proto__`,`constructor`,`prototype`]),Go=(e,t,n)=>Uo((n,r)=>{if(typeof n==`object`&&n)for(let i of Reflect.ownKeys(n))(typeof i!=`string`||!e(i))&&r.addIssue({code:`custom`,message:t(String(i)),path:[String(i)]});return n},n),Ko=e=>e.length>0&&!Wo.has(e),qo=e=>Go(Ko,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,go(I().min(1),e)),Jo=[`blobless`,`full`],Yo=[`ssh`,`https`],Xo=/^(?!\.{1,2}$)[^/\\%:]+$/u,Zo=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,Qo=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,$o={d:864e5,h:36e5,m:6e4},es=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),ts=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},ns=e=>{let[t=``,n]=e.split(`_`);return ts(n)?t.split(`.`).every(e=>es(e)):!1},z=I().refine(e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!Zo.test(t)||!ns(t)?!1:n.every(e=>Xo.test(e))},`ref key must be host/path…/repo with safe, non-empty segments`).brand(),rs=I().regex(Qo,`duration must be <n>m, <n>h, or <n>d`).brand(),is=e=>{let t=Qo.exec(e);if(t===null)throw Error(`invalid duration: ${e}`);let{amount:n,unit:r}=t.groups??{};if(!n||!r)throw Error(`invalid duration: ${e}`);return Number(n)*$o[r]},as=vo(Jo),os=vo(Yo),ss=I().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),cs=I().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>Xo.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),ls={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},us=R({clone_mode:as.default(ls.clone_mode),git_transport:os.default(ls.git_transport),sync_ttl:rs.default(rs.parse(ls.sync_ttl))}),ds=R((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(us.shape)),fs=R({description:I().min(1),path:cs,tag_format:ss.optional()}),ps=R({default_branch:I().min(1),description:I().min(1),packages:qo(fs).optional(),tag_format:ss.optional(),url:I().min(1),...ds.shape}),ms=lo({cli_version:I().min(1),schema_version:Za().int().positive()}),hs=Go(e=>z.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,go(I(),ps)),gs=R({check:to().default(!0),notify:to().default(!0)}),_s=R({meta:ms,refs:hs.default({}),settings:us,updates:gs.optional()});
52
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function Ga(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;Ga(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const Ka=new Set([`type`,`properties`,`required`,`additionalProperties`]),qa=[`oneOf`,`anyOf`];function Ja(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Ya(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Ka.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??Ja(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}x(n,r,e.length===1?e[0]:Ya(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=Ja(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Xa(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Ka)if(t in e)return;let n=t.filter(e=>qa.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Ya(t);else{let e=n[0],i=qa.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Ya([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Ba(e,r))}function Za(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Ba(i,s),Ba(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())Ga(t[1].def??t[1].schema);if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])Xa(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Ba(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,x(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:$a(t,`input`,e.processors),output:$a(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function M(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return M(r.element,n);if(r.type===`set`)return M(r.valueType,n);if(r.type===`lazy`)return M(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return M(r.innerType,n);if(r.type===`intersection`)return M(r.left,n)||M(r.right,n);if(r.type===`record`||r.type===`map`)return M(r.keyType,n)||M(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:M(r.in,n)||M(r.out,n);if(r.type===`object`){for(let e in r.shape)if(M(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(M(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(M(e,n))return!0;return!!(r.rest&&M(r.rest,n))}return!1}const Qa=(e,t={})=>n=>{let r=Va({...n,processors:t});return j(e,r),Wa(r,e),Za(r,e)},$a=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Va({...i??{},target:a,io:t,processors:n});return j(e,o),Wa(o,e),Za(o,e)},eo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},to=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=eo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},no=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(Number.isFinite(c)&&c!==0?i.multipleOf=Math.abs(c):Ha(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))},ro=(e,t,n,r)=>{n.type=`boolean`},io=(e,t,n,r)=>{n.not={}},ao=(e,t,n,r)=>{let i=e._zod.def,a=we(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},oo=(e,t,n,r)=>{Ha(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},so=(e,t,n,r)=>{Ha(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},co=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=j(a.element,t,{...r,path:[...r.path,`items`]})};function lo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?lo(t.out):t.type===`catch`?lo(t.innerType):e._zod.optin}const uo=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Ha(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)x(i.properties,e,j(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e];return t.io===`input`?lo(n)===void 0:n._zod.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=j(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},fo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>j(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},po=(e,t,n,r)=>{let i=e._zod.def,a=j(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=j(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},mo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=j(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)x(i.patternProperties,t.source,e)}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=j(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=j(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values,l=t.io===`input`&&lo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},ho=(e,t,n,r)=>{let i=e._zod.def,a=j(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},go=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},_o=Symbol();function vo(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Ha(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),_o):JSON.parse(o)}const yo=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=vo(i.defaultValue,e,t,n,r);o!==_o&&(n.default=o)},bo=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=vo(i.defaultValue,e,t,n,r);o!==_o&&(n._prefault=o)},xo=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Ha(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},So=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;j(o,t,r);let s=t.seen.get(e);s.ref=o},Co=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},wo=(e,t,n,r)=>{let i=e._zod.def;j(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},To=new WeakSet([Object.prototype,Error.prototype]);function Eo(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const N=w(`ZodError`,(e,t)=>{Mt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);To.has(n)||(To.add(n),Eo(n,`format`,e=>t=>It(e,t)),Eo(n,`flatten`,e=>t=>Ft(e,t)),Eo(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ee,2)}),Eo(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ee,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Do=zt(N),Oo=Bt(N),ko=Vt(N),Ao=Ut(N),jo=Gt(N),Mo=Kt(N),No=qt(N),Po=Jt(N),Fo=Yt(N),Io=Xt(N),Lo=Zt(N),Ro=Qt(N);function zo(){T.localeError||E(Ni())}function Bo(){T.memoizer||E({memoizer:Ai()})}const P=w(`ZodType`,(e,t)=>(zo(),k.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(je(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ve(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(nc(e,t))},superRefine(e,t){return this.check(rc(e,t))},overwrite(e){return this.check(Aa(e))},optional(){return Ls(this)},exactOptional(){return zs(this)},nullable(){return Vs(this)},nullish(){return Ls(Vs(this))},nonoptional(e){return qs(this,e)},array(){return Cs(this)},or(e){return Ds([this,e])},and(e){return ks(this,e)},transform(e){return Zs(this,Fs(e))},default(e){return Us(this,e)},prefault(e){return Gs(this,e)},catch(e){return Ys(this,e)},pipe(e){return Zs(this,e)},readonly(){return ec(this)},describe(e){let t=this.clone();return Li.add(t,{description:e}),t},meta(...e){if(e.length===0)return Li.get(this);let t=this.clone();return Li.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return dt(this,`~standard`,{...Qn(this),jsonSchema:{input:$a(this,`input`),output:$a(this,`output`)}})},set"~standard"(e){ut(this,`~standard`,e)},parse:function e(t,n){return Do(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Oo(this,t,n,{callee:e})},safeParse(e,t){return ko(this,e,t)},async safeParseAsync(e,t){return Ao(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ut(this,`spa`,e)},encode:function e(t,n){return jo(this,t,n,{callee:e})},decode:function e(t,n){return Mo(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await No(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Po(this,t,n,{callee:e})},safeEncode(e,t){return Fo(this,e,t)},safeDecode(e,t){return Io(this,e,t)},async safeEncodeAsync(e,t){return Lo(this,e,t)},async safeDecodeAsync(e,t){return Ro(this,e,t)},toJSONSchema(e){return Qa(this,{})(e)},get description(){return Li.get(this)?.description},get _def(){return this._zod.def}}),Vo=w(`_ZodString`,(e,t)=>{$n.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>to(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(wa(...e))},includes(...e){return this.check(Da(...e))},startsWith(...e){return this.check(Oa(...e))},endsWith(...e){return this.check(ka(...e))},min(...e){return this.check(Sa(...e))},max(...e){return this.check(xa(...e))},length(...e){return this.check(Ca(...e))},nonempty(...e){return this.check(Sa(1,...e))},lowercase(e){return this.check(Ta(e))},uppercase(e){return this.check(Ea(e))},trim(){return this.check(Ma())},normalize(...e){return this.check(ja(...e))},toLowerCase(){return this.check(Na())},toUpperCase(){return this.check(Pa())},slugify(){return this.check(Fa())}}),Ho=w(`ZodString`,(e,t)=>{$n.init(e,t),Vo.init(e,t)},{email(e){return this.check(zi(qo,e))},url(e){return this.check(Gi(Xo,e))},jwt(e){return this.check(oa(ds,e))},emoji(e){return this.check(Ki(Zo,e))},guid(e){return this.check(Bi(Jo,e))},uuid(e){return this.check(Vi(Yo,e))},uuidv4(e){return this.check(Hi(Yo,e))},uuidv6(e){return this.check(Ui(Yo,e))},uuidv7(e){return this.check(Wi(Yo,e))},nanoid(e){return this.check(qi(Qo,e))},cuid(e){return this.check(Ji($o,e))},cuid2(e){return this.check(Yi(es,e))},ulid(e){return this.check(Xi(ts,e))},base64(e){return this.check(ra(cs,e))},base64url(e){return this.check(ia(ls,e))},xid(e){return this.check(Zi(ns,e))},ksuid(e){return this.check(Qi(rs,e))},ipv4(e){return this.check($i(is,e))},ipv6(e){return this.check(ea(as,e))},cidrv4(e){return this.check(ta(os,e))},cidrv6(e){return this.check(na(ss,e))},e164(e){return this.check(aa(us,e))},datetime(e){return this.check(sa(Uo,e))},date(e){return this.check(ca(Wo,e))},time(e){return this.check(la(Go,e))},duration(e){return this.check(ua(Ko,e))}});function F(e){return Ri(Ho,e)}const I=w(`ZodStringFormat`,(e,t)=>{A.init(e,t),Vo.init(e,t)}),Uo=w(`ZodISODateTime`,(e,t)=>{gr.init(e,t),I.init(e,t)}),Wo=w(`ZodISODate`,(e,t)=>{_r.init(e,t),I.init(e,t)}),Go=w(`ZodISOTime`,(e,t)=>{vr.init(e,t),I.init(e,t)}),Ko=w(`ZodISODuration`,(e,t)=>{yr.init(e,t),I.init(e,t)}),qo=w(`ZodEmail`,(e,t)=>{nr.init(e,t),I.init(e,t)}),Jo=w(`ZodGUID`,(e,t)=>{er.init(e,t),I.init(e,t)}),Yo=w(`ZodUUID`,(e,t)=>{tr.init(e,t),I.init(e,t)}),Xo=w(`ZodURL`,(e,t)=>{cr.init(e,t),I.init(e,t)}),Zo=w(`ZodEmoji`,(e,t)=>{lr.init(e,t),I.init(e,t)}),Qo=w(`ZodNanoID`,(e,t)=>{ur.init(e,t),I.init(e,t)}),$o=w(`ZodCUID`,(e,t)=>{dr.init(e,t),I.init(e,t)}),es=w(`ZodCUID2`,(e,t)=>{fr.init(e,t),I.init(e,t)}),ts=w(`ZodULID`,(e,t)=>{pr.init(e,t),I.init(e,t)}),ns=w(`ZodXID`,(e,t)=>{mr.init(e,t),I.init(e,t)}),rs=w(`ZodKSUID`,(e,t)=>{hr.init(e,t),I.init(e,t)}),is=w(`ZodIPv4`,(e,t)=>{br.init(e,t),I.init(e,t)}),as=w(`ZodIPv6`,(e,t)=>{Cr.init(e,t),I.init(e,t)}),os=w(`ZodCIDRv4`,(e,t)=>{wr.init(e,t),I.init(e,t)}),ss=w(`ZodCIDRv6`,(e,t)=>{Er.init(e,t),I.init(e,t)}),cs=w(`ZodBase64`,(e,t)=>{Or.init(e,t),I.init(e,t)}),ls=w(`ZodBase64URL`,(e,t)=>{Ar.init(e,t),I.init(e,t)}),us=w(`ZodE164`,(e,t)=>{jr.init(e,t),I.init(e,t)}),ds=w(`ZodJWT`,(e,t)=>{Nr.init(e,t),I.init(e,t)}),fs=w(`ZodNumber`,(e,t)=>{Pr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>no(e,t,n,r);let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(va(e,t))},gte(e,t){return this.check(ya(e,t))},min(e,t){return this.check(ya(e,t))},lt(e,t){return this.check(ga(e,t))},lte(e,t){return this.check(_a(e,t))},max(e,t){return this.check(_a(e,t))},int(e){return this.check(hs(e))},safe(e){return this.check(hs(e))},positive(e){return this.check(va(0,e))},nonnegative(e){return this.check(ya(0,e))},negative(e){return this.check(ga(0,e))},nonpositive(e){return this.check(_a(0,e))},multipleOf(e,t){return this.check(ba(e,t))},step(e,t){return this.check(ba(e,t))},finite(){return this}});function ps(e){return da(fs,e)}const ms=w(`ZodNumberFormat`,(e,t)=>{Fr.init(e,t),fs.init(e,t)});function hs(e){return fa(ms,e)}const gs=w(`ZodBoolean`,(e,t)=>{Ir.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ro(e,t,n,r)});function _s(e){return pa(gs,e)}const vs=w(`ZodUnknown`,(e,t)=>{Lr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function ys(){return ma(vs)}const bs=w(`ZodNever`,(e,t)=>{Rr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>io(e,t,n,r)});function xs(e){return ha(bs,e)}const Ss=w(`ZodArray`,(e,t)=>{Bo(),Br.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>co(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Sa(e,t))},nonempty(e){return this.check(Sa(1,e))},max(e,t){return this.check(xa(e,t))},length(e,t){return this.check(Ca(e,t))},unwrap(){return this.element}});function Cs(e,t){return Ia(Ss,e,t)}const ws=w(`ZodObject`,(e,t)=>{Bo(),qr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uo(e,t,n,r),_t(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return Ns(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:ys()})},loose(){return this.clone({...this._zod.def,catchall:ys()})},strict(){return this.clone({...this._zod.def,catchall:xs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return qe(this,e)},safeExtend(e){return Je(this,e)},merge(e){return Ye(this,e)},pick(e){return Ge(this,e)},omit(e){return Ke(this,e)},partial(...e){return Xe(Is,this,e[0])},exactPartial(...e){return Xe(Rs,this,e[0],`exactPartial`)},required(...e){return Ze(Ks,this,e[0])}});function L(e,t){return new ws({type:`object`,shape:e,catchall:xs(),...S(t)})}function Ts(e,t){return new ws({type:`object`,shape:e,catchall:ys(),...S(t)})}const Es=w(`ZodUnion`,(e,t)=>{Yr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fo(e,t,n,r),e.options=t.options});function Ds(e,t){return new Es({type:`union`,options:e,...S(t)})}const Os=w(`ZodIntersection`,(e,t)=>{Xr.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>po(e,t,n,r)});function ks(e,t){return new Os({type:`intersection`,left:e,right:t})}const As=w(`ZodRecord`,(e,t)=>{Bo(),$r.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function js(e,t,n){return!t||!t._zod?new As({type:`record`,keyType:F(),valueType:e,...S(t)}):new As({type:`record`,keyType:e,valueType:t,...S(n)})}const Ms=w(`ZodEnum`,(e,t)=>{ei.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ao(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ms({...t,checks:[],...S(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ms({...t,checks:[],...S(r),entries:i})}});function Ns(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ms({type:`enum`,entries:n,...S(t)})}const Ps=w(`ZodTransform`,(e,t)=>{Bo(),ti.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>so(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new wt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ct(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(ct(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Fs(e){return new Ps({type:`transform`,transform:e})}const Is=w(`ZodOptional`,(e,t)=>{ri.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ls(e){return new Is({type:`optional`,innerType:e})}const Rs=w(`ZodExactOptional`,(e,t)=>{ii.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function zs(e){return new Rs({type:`optional`,innerType:e})}const Bs=w(`ZodNullable`,(e,t)=>{ai.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ho(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Vs(e){return new Bs({type:`nullable`,innerType:e})}const Hs=w(`ZodDefault`,(e,t)=>{oi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Us(e,t){return new Hs({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Re(t)}})}const Ws=w(`ZodPrefault`,(e,t)=>{ci.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Gs(e,t){return new Ws({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Re(t)}})}const Ks=w(`ZodNonOptional`,(e,t)=>{li.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>go(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qs(e,t){return new Ks({type:`nonoptional`,innerType:e,...S(t)})}const Js=w(`ZodCatch`,(e,t)=>{fi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ys(e,t){return new Js({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:vt(t)})}const Xs=w(`ZodPipe`,(e,t)=>{pi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>So(e,t,n,r),e.in=t.in,e.out=t.out});function Zs(e,t){return new Xs({type:`pipe`,in:e,out:t})}const Qs=w(`ZodPreprocess`,(e,t)=>{Xs.init(e,t),hi.init(e,t)}),$s=w(`ZodReadonly`,(e,t)=>{gi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Co(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ec(e){return new $s({type:`readonly`,innerType:e})}const tc=w(`ZodCustom`,(e,t)=>{vi.init(e,t),P.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oo(e,t,n,r)});function nc(e,t={}){return La(tc,e,t)}function rc(e,t){return Ra(e,t)}function ic(e,t){return new Qs({type:`pipe`,in:Fs(e),out:t})}function ac(e){return sa(Uo,e)}const oc=new Set([`__proto__`,`constructor`,`prototype`]),sc=(e,t,n)=>ic((n,r)=>{if(typeof n==`object`&&n)for(let i of Reflect.ownKeys(n))(typeof i!=`string`||!e(i))&&r.addIssue({code:`custom`,message:t(String(i)),path:[String(i)]});return n},n),cc=e=>e.length>0&&!oc.has(e),lc=e=>sc(cc,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,js(F().min(1),e)),uc=[`blobless`,`full`],dc=[`ssh`,`https`],fc=/^(?!\.{1,2}$)[^/\\%:]+$/u,pc=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,mc=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,hc={d:864e5,h:36e5,m:6e4},gc=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),_c=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},vc=e=>{let[t=``,n]=e.split(`_`);return _c(n)?t.split(`.`).every(e=>gc(e)):!1},R=F().refine(e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!pc.test(t)||!vc(t)?!1:n.every(e=>fc.test(e))},`ref key must be host/path…/repo with safe, non-empty segments`).brand(),yc=F().regex(mc,`duration must be <n>m, <n>h, or <n>d`).brand(),bc=e=>{let t=mc.exec(e);if(t===null)throw Error(`invalid duration: ${e}`);let{amount:n,unit:r}=t.groups??{};if(!n||!r)throw Error(`invalid duration: ${e}`);return Number(n)*hc[r]},xc=Ns(uc),Sc=Ns(dc),Cc=F().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),wc=F().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>fc.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),Tc={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},Ec=L({clone_mode:xc.default(Tc.clone_mode),git_transport:Sc.default(Tc.git_transport),sync_ttl:yc.default(yc.parse(Tc.sync_ttl))}),Dc=L((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(Ec.shape)),Oc=L({description:F().min(1),path:wc,tag_format:Cc.optional()}),kc=L({default_branch:F().min(1),description:F().min(1),packages:lc(Oc).optional(),tag_format:Cc.optional(),url:F().min(1),...Dc.shape}),Ac=Ts({cli_version:F().min(1),schema_version:ps().int().positive()}),jc=sc(e=>R.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,js(F(),kc)),Mc=L({check:_s().default(!0),notify:_s().default(!0)}),Nc=L({meta:Ac,refs:jc.default({}),settings:Ec,updates:Mc.optional()});
67
53
  /*!
68
54
  * Copyright (c) Squirrel Chat et al., All rights reserved.
69
55
  * SPDX-License-Identifier: BSD-3-Clause
@@ -91,7 +77,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
91
77
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
92
78
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
93
79
  */
94
- let vs=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var ys=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(vs);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
80
+ let Pc=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var Fc=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(Pc);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
95
81
  /*!
96
82
  * Copyright (c) Squirrel Chat et al., All rights reserved.
97
83
  * SPDX-License-Identifier: BSD-3-Clause
@@ -119,9 +105,9 @@ let vs=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]
119
105
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
120
106
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
121
107
  */
122
- function bs(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function xs(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
108
+ function Ic(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Lc(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
123
109
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
124
- `))}return i}var B=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=bs(t.toml,t.ptr),i=xs(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
110
+ `))}return i}var z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Ic(t.toml,t.ptr),i=Lc(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
125
111
  /*!
126
112
  * Copyright (c) Squirrel Chat et al., All rights reserved.
127
113
  * SPDX-License-Identifier: BSD-3-Clause
@@ -149,12 +135,8 @@ function bs(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop()
149
135
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
150
136
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
151
137
  */
152
- let Ss=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Cs=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,ws=/^[+-]?0[0-9_]/;function Ts(e,t){let n=e[t++],r=n,i=n===`'`,a=n===e[t]&&n===e[t+1];a&&(e[t+=2]===`
153
- `?t++:e[t]===`\r`&&e[t+1]===`
154
- `&&(t+=2));let o=``,s=t,c=0;for(let l=t;l<e.length;l++)if(n=e[l],a&&(n===`
155
- `||n===`\r`&&e[l+1]===`
156
- `))c&&=3;else if(n<` `&&n!==` `||n===``)throw new B(`control characters are not allowed in strings`,{toml:e,ptr:l});else if((!c||c===3)&&n===r&&(!a||e[l+1]===r&&e[l+2]===r))return a&&(e[l+3]===r&&l++,e[l+3]===r&&l++),[c?o:o+e.slice(s,l),l+(a?3:1)];else if(!c)!i&&n===`\\`&&(o+=e.slice(s,s=l),c=1);else if(c===1){if(n===`x`||n===`u`||n===`U`){let t=0,r=n===`x`?2:n===`u`?4:8;for(let n=0;n<r;n++,l++){let n=e.charCodeAt(l+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new B(`invalid non-hex character in unicode escape`,{toml:e,ptr:l+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new B(`invalid unicode escape`,{toml:e,ptr:l});o+=String.fromCodePoint(t),s=l+1,c=0}else if(n===` `||n===` `)c=2;else{if(n===`b`)o+=`\b`;else if(n===`t`)o+=` `;else if(n===`n`)o+=`
157
- `;else if(n===`f`)o+=`\f`;else if(n===`r`)o+=`\r`;else if(n===`e`)o+=`\x1B`;else if(n===`"`)o+=`"`;else if(n===`\\`)o+=`\\`;else throw new B(`unrecognized escape sequence`,{toml:e,ptr:l});s=l+1,c=0}}else if(n!==` `&&n!==` `){if(c===2)throw new B(`invalid escape: only line-ending whitespace may be escaped`,{toml:e,ptr:s});c=+(!i&&n===`\\`),s=l}throw new B(`unfinished string`,{toml:e,ptr:t})}function Es(e,t,n,r){if(e===`true`)return!0;if(e===`false`)return!1;if(e===`-inf`)return-1/0;if(e===`inf`||e===`+inf`)return 1/0;if(e===`nan`||e===`+nan`||e===`-nan`)return NaN;if(e===`-0`)return r?0n:0;let i=Ss.test(e);if(i||Cs.test(e)){if(ws.test(e))throw new B(`leading zeroes are not allowed`,{toml:t,ptr:n});e=e.replace(/_/g,``);let a=+e;if(isNaN(a))throw new B(`invalid number`,{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new B(`integer value cannot be represented losslessly`,{toml:t,ptr:n});(i||r===!0)&&(a=BigInt(e))}return a}let a=new ys(e);if(!a.isValid())throw new B(`invalid value`,{toml:t,ptr:n});return a}
138
+ function Rc(e,t=0){let n=e.indexOf(`
139
+ `,t);return e.charCodeAt(n-1)===13&&n--,n}function zc(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)throw new z(`control characters are not allowed in comments`,{toml:e.s,ptr:e.p})}}function Bc(e,t,n){let r;for(;;){for(;(r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10);)e.p++;if(n||r!==35)break;zc(e)}}function Vc(e,t,n){let r=e.p;if(!n){r=Rc(e.s,r),e.p=r<0?e.s.length:r;return}for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===35)zc(e);else if(r===n||r===t)return}throw new z(`cannot find end of structure`,{toml:e.s,ptr:r})}
158
140
  /*!
159
141
  * Copyright (c) Squirrel Chat et al., All rights reserved.
160
142
  * SPDX-License-Identifier: BSD-3-Clause
@@ -182,14 +164,8 @@ let Ss=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Cs=/^[+-]?
182
164
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
183
165
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
184
166
  */
185
- function Ds(e,t=0,n=e.length){let r=e.indexOf(`
186
- `,t);return e[r-1]===`\r`&&r--,r<=n?r:-1}function Os(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
187
- `)return n;if(r===`\r`&&e[n+1]===`
188
- `)return n+1;if(r<` `&&r!==` `||r===``)throw new B(`control characters are not allowed in comments`,{toml:e,ptr:t})}return e.length}function ks(e,t,n,r){let i;for(;;){for(;(i=e[t])===` `||i===` `||!n&&(i===`
189
- `||i===`\r`&&e[t+1]===`
190
- `);)t++;if(r||i!==`#`)break;t=Os(e,t)}return t}function As(e,t,n,r,i=!1){if(!r)return t=Ds(e,t),t<0?e.length:t;for(let a=t;a<e.length;a++){let t=e[a];if(t===`#`){if(a=Ds(e,a),a<0)break}else if(t===n)return a+1;else if(t===r||i&&(t===`
191
- `||t===`\r`&&e[a+1]===`
192
- `))return a}throw new B(`cannot find end of structure`,{toml:e,ptr:t})}
167
+ let Hc=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Uc=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Wc=/^[+-]?0[0-9_]/;function Gc(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)throw new z(`control characters are not allowed in strings`,{toml:e.s,ptr:e.p});else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r))return a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),c||(o+=e.s.slice(s,e.p)),e.p+=a?3:1,o;else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1){if(n===120||n===117||n===85){let t=0,r=n===120?2:n===117?4:8;for(let n=0;n<r;n++,e.p++){let n=e.s.charCodeAt(e.p+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new z(`invalid non-hex character in unicode escape`,{toml:e.s,ptr:e.p+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new z(`invalid unicode escape`,{toml:e.s,ptr:e.p});o+=String.fromCodePoint(t),s=e.p+1,c=0}else if(n===32||n===9)c=2;else{if(n===98)o+=`\b`;else if(n===116)o+=` `;else if(n===110)o+=`
168
+ `;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new z(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new z(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new z(`unfinished string`,{toml:e.s,ptr:t})}function Kc(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(zc({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function qc(e,t,n){let r=e.p,i={toml:e.s,ptr:r};Vc(e,44,n);let a=Kc(e,r,e.p);if(!a)throw new z(`incomplete declaration: value expected`,i);if(a===`-inf`)return-1/0;if(a===`inf`||a===`+inf`)return 1/0;if(a===`nan`||a===`+nan`||a===`-nan`)return NaN;if(a===`-0`)return t?0n:0;let o=Hc.test(a);if(o||Uc.test(a)){if(Wc.test(a))throw new z(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new z(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new z(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new Fc(a);if(!s.isValid())throw new z(`invalid value`,i);return s}
193
169
  /*!
194
170
  * Copyright (c) Squirrel Chat et al., All rights reserved.
195
171
  * SPDX-License-Identifier: BSD-3-Clause
@@ -217,8 +193,7 @@ function Ds(e,t=0,n=e.length){let r=e.indexOf(`
217
193
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
218
194
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
219
195
  */
220
- function js(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(Os(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function Ms(e,t,n,r,i){if(r===0)throw new B(`document contains excessively nested structures. aborting.`,{toml:e,ptr:t});let a=e[t];if(a===`[`||a===`{`){let[o,s]=a===`[`?Is(e,t,r,i):Fs(e,t,r,i);if(n){if(s=ks(e,s),e[s]===`,`)s++;else if(e[s]!==n)throw new B(`expected comma or end of structure`,{toml:e,ptr:s})}return[o,s]}if(a===`"`||a===`'`){let[r,i]=Ts(e,t);if(n){if(i=ks(e,i),e[i]&&e[i]!==`,`&&e[i]!==n&&e[i]!==`
221
- `&&e[i]!==`\r`)throw new B(`unexpected character encountered`,{toml:e,ptr:i});e[i]===`,`&&i++}return[r,i]}let o=As(e,t,`,`,n),s=js(e,t,o-+(e[o-1]===`,`));if(!s[0])throw new B(`incomplete key-value declaration: no value specified`,{toml:e,ptr:t});return n&&s[1]>-1&&(o=ks(e,t+s[1]),e[o]===`,`&&o++),[Es(s[0],e,t,i),o]}
196
+ function Jc(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new z(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?Qc(e,n):Zc(e,n);return e.d++,t}if(i===34||i===39)return Gc(e);if(i===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!0}if(i===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return qc(e,n,t)}
222
197
  /*!
223
198
  * Copyright (c) Squirrel Chat et al., All rights reserved.
224
199
  * SPDX-License-Identifier: BSD-3-Clause
@@ -246,9 +221,7 @@ function js(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(Os(e,i),r=r
246
221
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
247
222
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
248
223
  */
249
- let Ns=/^[a-zA-Z0-9-_]+[ \t]*$/;function Ps(e,t,n=`=`){let r=t-1,i=[],a=e.indexOf(n,t);if(a<0)throw new B(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});do{let o=e[t=++r];if(o!==` `&&o!==` `){if(o===`"`||o===`'`){if(o===e[t+1]&&o===e[t+2])throw new B(`multiline strings are not allowed in keys`,{toml:e,ptr:t});let[s,c]=Ts(e,t);r=e.indexOf(`.`,c);let l=e.slice(c,r<0||r>a?a:r),u=Ds(l);if(u>-1)throw new B(`newlines are not allowed in keys`,{toml:e,ptr:t+r+u});if(l.trimStart())throw new B(`found extra tokens after the string part`,{toml:e,ptr:c});if(a<c&&(a=e.indexOf(n,c),a<0))throw new B(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});i.push(s)}else{r=e.indexOf(`.`,t);let n=e.slice(t,r<0||r>a?a:r);if(!Ns.test(n))throw new B(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e,ptr:t});i.push(n.trimEnd())}}}while(r+1&&r<a);return[i,ks(e,a+1,!0,!0)]}function Fs(e,t,n,r){let i={},a=new Set,o;for(t++;(o=e[t++])!==`}`&&o;)if(o===`,`)throw new B(`expected value, found comma`,{toml:e,ptr:t-1});else if(o===`#`)t=Os(e,t);else if(o!==` `&&o!==` `&&o!==`
250
- `&&o!==`\r`){let o,s=i,c=!1,[l,u]=Ps(e,t-1);for(let n=0;n<l.length;n++){if(n&&(s=c?s[o]:s[o]={}),o=l[n],(c=Object.hasOwn(s,o))&&(typeof s[o]!=`object`||a.has(s[o])))throw new B(`trying to redefine an already defined value`,{toml:e,ptr:t});!c&&o===`__proto__`&&Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new B(`trying to redefine an already defined value`,{toml:e,ptr:t});let[d,f]=Ms(e,u,`}`,n-1,r);a.add(d),s[o]=d,t=f}if(!o)throw new B(`unfinished table encountered`,{toml:e,ptr:t});return[i,t]}function Is(e,t,n,r){let i=[],a;for(t++;(a=e[t++])!==`]`&&a;)if(a===`,`)throw new B(`expected value, found comma`,{toml:e,ptr:t-1});else if(a===`#`)t=Os(e,t);else if(a!==` `&&a!==` `&&a!==`
251
- `&&a!==`\r`){let a=Ms(e,t-1,`]`,n-1,r);i.push(a[0]),t=a[1]}if(!a)throw new B(`unfinished array encountered`,{toml:e,ptr:t});return[i,t]}
224
+ let Yc=/^[a-zA-Z0-9-_]+[ \t]*$/;function Xc(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++r);if(o!==32&&o!==9){if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new z(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=Gc(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=Rc(c);if(l>-1)throw new z(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new z(`found extra tokens after the string part`,{toml:e.s,ptr:e.p});if(a<e.p&&(a=e.s.indexOf(t,e.p),a<0))throw new z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});i.push(s)}else{r=e.s.indexOf(`.`,e.p);let t=e.s.slice(e.p,r<0||r>a?a:r);if(!Yc.test(t))throw new z(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e.s,ptr:e.p});i.push(t.trimEnd())}}}while(r+1&&r<a);return e.p=a+1,Bc(e,!0,!0),i}function Zc(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Bc(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Xc(e);for(let t=0;t<l.length;t++){if(t&&(o=s?o[a]:o[a]={}),a=l[t],(s=Object.hasOwn(o,a))&&(typeof o[a]!=`object`||r.has(o[a])))throw new z(`trying to redefine an already defined value`,{toml:e.s,ptr:c});!s&&a===`__proto__`&&Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})}if(s)throw new z(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=Jc(e,125,t);if(r.add(o[a]=u),Bc(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new z(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function Qc(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Bc(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Jc(e,93,t)),Bc(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new z(`unfinished array encountered`,{toml:e.s,ptr:e.p})}
252
225
  /*!
253
226
  * Copyright (c) Squirrel Chat et al., All rights reserved.
254
227
  * SPDX-License-Identifier: BSD-3-Clause
@@ -276,8 +249,7 @@ let Ns=/^[a-zA-Z0-9-_]+[ \t]*$/;function Ps(e,t,n=`=`){let r=t-1,i=[],a=e.indexO
276
249
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
277
250
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
278
251
  */
279
- function Ls(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function Rs(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},a=r,o=i;for(let s=ks(e,0);s<e.length;){if(e[s]===`[`){let t=e[++s]===`[`,n=Ps(e,s+=+t,`]`);if(t){if(e[n[1]-1]!==`]`)throw new B(`expected end of table declaration`,{toml:e,ptr:n[1]-1});n[1]++}let c=Ls(n[0],r,i,t?2:1);if(!c)throw new B(`trying to redefine an already defined table or value`,{toml:e,ptr:s});o=c[2],a=c[1],s=n[1]}else{let r=Ps(e,s),i=Ls(r[0],a,o,0);if(!i)throw new B(`trying to redefine an already defined table or value`,{toml:e,ptr:s});let c=Ms(e,r[1],void 0,t,n);i[1][i[0]]=c[0],s=c[1]}if(s=ks(e,s,!0),e[s]&&e[s]!==`
280
- `&&e[s]!==`\r`)throw new B(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:s});s=ks(e,s)}return r}
252
+ function $c(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function el(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Bc(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Xc(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new z(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=$c(n,i,a,t?2:1);if(!l)throw new z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});c=l[2],s=l[1]}else{o=r.p;let t=$c(Xc(r),s,c,0);if(!t)throw new z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=Jc(r,void 0,n)}if(Bc(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new z(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});Bc(r)}return i}
281
253
  /*!
282
254
  * Copyright (c) Squirrel Chat et al., All rights reserved.
283
255
  * SPDX-License-Identifier: BSD-3-Clause
@@ -305,13 +277,13 @@ function Ls(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i
305
277
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
306
278
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
307
279
  */
308
- let zs=/^[a-z0-9-_]+$/i;function Bs(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(e instanceof Date)return`date`}return t}function Vs(e){for(let t=0;t<e.length;t++)if(Bs(e[t])!==`object`)return!1;return e.length!=0}function Hs(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function Us(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);if(t===`number`)return isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Number.isInteger(e)&&(r||!Number.isSafeInteger(e))?e.toFixed(1):e.toString();if(t===`bigint`||t===`boolean`)return e.toString();if(t===`string`)return Hs(e);if(t===`date`){if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString()}if(t===`object`)return Ws(e,n,r);if(t===`array`)return Gs(e,n,r)}function Ws(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=zs.test(o)?o:Hs(o),i+=` = `,i+=Us(e[o],Bs(e[o]),t-1,n)}return i+` }`}function Gs(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=Us(e[i],Bs(e[i]),t-1,n)}return r+` ]`}function Ks(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
309
- `}[[${t}]]\n`,i+=qs(0,e[a],t,n,r);return i}function qs(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=Bs(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=zs.test(c)?c:Hs(c);if(e===`array`&&Vs(t[c]))o+=(o&&`
310
- `)+Ks(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
311
- `)+qs(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=Us(t[c],e,r,i),a+=`
312
- `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function Js(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(Bs(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=qs(0,e,``,t,n);return r[r.length-1]===`
280
+ let tl=/^[a-z0-9-_]+$/i;function nl(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(typeof e?.getUTCDate==`function`&&e instanceof Date)return`date`;if(globalThis.Temporal&&typeof e?.since==`function`&&(e instanceof Temporal.Instant||e instanceof Temporal.PlainDate||e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainTime||e instanceof Temporal.ZonedDateTime))return`temporal`}return t}function rl(e){for(let t=0;t<e.length;t++)if(nl(e[t])!==`object`)return!1;return e.length!=0}function il(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function al(e){return e.toString({calendarName:`never`,timeZoneName:`never`})}function ol(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);switch(t){case`number`:if(isNaN(e))return`nan`;if(e===1/0)return`inf`;if(e===-1/0)return`-inf`;if(Number.isInteger(e)&&(r||!Number.isSafeInteger(e)))return e.toFixed(1);case`bigint`:case`boolean`:return e.toString();case`string`:return il(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return sl(e,n,r);case`array`:return cl(e,n,r);case`temporal`:return al(e)}}function sl(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=tl.test(o)?o:il(o),i+=` = `,i+=ol(e[o],nl(e[o]),t-1,n)}return i+` }`}function cl(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=ol(e[i],nl(e[i]),t-1,n)}return r+` ]`}function ll(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
281
+ `}[[${t}]]\n`,i+=ul(0,e[a],t,n,r);return i}function ul(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=nl(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=tl.test(c)?c:il(c);if(e===`array`&&rl(t[c]))o+=(o&&`
282
+ `)+ll(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
283
+ `)+ul(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=ol(t[c],e,r,i),a+=`
284
+ `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function dl(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(nl(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=ul(0,e,``,t,n);return r[r.length-1]===`
313
285
  `?r:r+`
314
- `}const V=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,Ys=async(e,t)=>{await a(te(e),{recursive:!0});let n=`${e}.tmp-${se()}`;await p(n,t,`utf8`),await l(n,e)},H=e=>{let t=ae(e.REFS_HOME??h(de(),`.kaisers-io`,`refs`));return{cacheDir:h(t,`cache`),configPath:h(t,`config.toml`),hooksDir:h(t,`hooks`),locksDir:h(t,`locks`),root:t,sourcesDir:h(t,`sources`),statePath:h(t,`state.json`),updateCachePath:h(t,`cache`,`update-check.json`)}},U=(e,t)=>h(e.sourcesDir,...t.split(`/`)),Xs=e=>`${e.configPath}.bak`,Zs=e=>{let t=[],n=e;for(;!le(n);){let e=te(n);if(e===n)break;t.unshift(ee(n)),n=e}return{ancestor:n,missing:t}},Qs=e=>{let{ancestor:t,missing:n}=Zs(e),r=ue(t);return n.length===0?r:h(r,...n)},$s=(e,t,n)=>{let r=Qs(e),i=Qs(t),a=ie(r,i),o=a===`..`||a.startsWith(`..`+oe);if(!(a!==``&&!o&&!ne(a)))throw x(`path escapes ${n} (containment violation): ${t}`)},ec=(e,t)=>{$s(e.sourcesDir,t,`sources directory`)},tc=e=>typeof e==`object`&&!!e&&!Array.isArray(e),nc=(e,t)=>tc(e)?e:t,rc=async e=>{try{return await o(e.configPath,`utf8`)}catch(e){throw V(e)?y(`no config found — run: refs init`):e}},ic=(e,t)=>{try{return Rs(e)}catch(e){throw e instanceof B?x(`invalid TOML in ${t}: ${e.message}`):e}},ac=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,oc=e=>{let{meta:t}=e;if(!tc(t))return;let n=t.schema_version;if(ac(n))return n},sc=(e,t)=>{let n=oc(e);if(n===void 0)throw x(`config schema version is missing or invalid in ${t} — run: refs migrate`);if(n>1)throw x(`config schema ${n} is newer than this CLI supports — upgrade refs`);if(n<1)throw x(`config schema ${n} is older than expected 1 — run: refs migrate`)},W=async e=>{let t=await rc(e),n=ic(t,e.configPath);sc(n,e.configPath);let r=_s.safeParse(n);if(!r.success)throw x(O(r.error));return r.data},cc=async(e,t)=>{let n=_s.safeParse(t);if(!n.success)throw x(O(n.error));await Ys(e.configPath,Js(n.data))},lc=async e=>{try{return await f(e),!0}catch(e){if(V(e))return!1;throw e}},uc=async(e,t)=>await lc(e.configPath)?`noop`:(await Ys(e.configPath,`# refs configuration
286
+ `}const B=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,fl=async(e,t)=>{await a(ie(e),{recursive:!0});let n=`${e}.tmp-${ue()}`;await te(n,t,`utf8`),await u(n,e)},V=e=>{let t=ce(e.REFS_HOME??m(me(),`.kaisers-io`,`refs`));return{cacheDir:m(t,`cache`),configPath:m(t,`config.toml`),hooksDir:m(t,`hooks`),locksDir:m(t,`locks`),root:t,sourcesDir:m(t,`sources`),statePath:m(t,`state.json`),updateCachePath:m(t,`cache`,`update-check.json`)}},H=(e,t)=>m(e.sourcesDir,...t.split(`/`)),pl=e=>`${e.configPath}.bak`,ml=e=>{let t=[],n=e;for(;!fe(n);){let e=ie(n);if(e===n)break;t.unshift(re(n)),n=e}return{ancestor:n,missing:t}},hl=e=>{let{ancestor:t,missing:n}=ml(e),r=pe(t);return n.length===0?r:m(r,...n)},gl=(e,t,n)=>{let r=hl(e),i=hl(t),a=se(r,i),o=a===`..`||a.startsWith(`..`+le);if(!(a!==``&&!o&&!ae(a)))throw b(`path escapes ${n} (containment violation): ${t}`)},_l=(e,t)=>{gl(e.sourcesDir,t,`sources directory`)},vl=e=>typeof e==`object`&&!!e&&!Array.isArray(e),yl=(e,t)=>vl(e)?e:t,bl=async e=>{try{return await s(e.configPath,`utf8`)}catch(e){throw B(e)?v(`no config found — run: refs init`):e}},xl=(e,t)=>{try{return el(e)}catch(e){throw e instanceof z?b(`invalid TOML in ${t}: ${e.message}`):e}},Sl=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,Cl=e=>{let{meta:t}=e;if(!vl(t))return;let n=t.schema_version;if(Sl(n))return n},wl=(e,t)=>{let n=Cl(e);if(n===void 0)throw b(`config schema version is missing or invalid in ${t} — run: refs migrate`);if(n>1)throw b(`config schema ${n} is newer than this CLI supports — upgrade refs`);if(n<1)throw b(`config schema ${n} is older than expected 1 — run: refs migrate`)},U=async e=>{let t=await bl(e),n=xl(t,e.configPath);wl(n,e.configPath);let r=Nc.safeParse(n);if(!r.success)throw b(D(r.error));return r.data},Tl=async(e,t)=>{let n=Nc.safeParse(t);if(!n.success)throw b(D(n.error));await fl(e.configPath,dl(n.data))},El=async e=>{try{return await p(e),!0}catch(e){if(B(e))return!1;throw e}},Dl=async(e,t)=>await El(e.configPath)?`noop`:(await fl(e.configPath,`# refs configuration
315
287
  #
316
288
  # Every global setting under [settings] can also be set per-ref: add the same
317
289
  # key directly inside a [refs."host/owner/repo"] table to override it just for
@@ -342,29 +314,34 @@ sync_ttl = "1h"
342
314
  # tag_format = "v{version}"
343
315
  # # Per-ref overrides of [settings] go in the same table, e.g.:
344
316
  # # clone_mode = "full"
345
- `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),dc=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:tc(t)&&tc(r)&&(n[e]=dc(t,r))}return n},fc={meta:{},refs:{},settings:{}},pc=async e=>{try{return await rc(e)}catch(e){if(e instanceof v&&e.code===`not_found`)return;throw e}},mc=e=>{if(e!==void 0&&e>1)throw x(`config schema ${e} is newer than this CLI supports — upgrade refs`)},hc=async(e,t,n)=>{let r=nc(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await Ys(e.configPath,Js(i))},gc=async(e,t,n)=>{await r(e.configPath,Xs(e));let i=dc(t,fc),a=nc(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=_s.safeParse(o);if(!s.success)throw x(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${Xs(e)}): ${O(s.error)}`);await Ys(e.configPath,Js(o))},_c=async(e,t,n)=>{let r=ic(t,e.configPath),i=oc(r);return mc(i),i===1?(await hc(e,r,n),`noop`):(await gc(e,r,n),`migrated`)},vc=async(e,t)=>{let n=await pc(e);return n===void 0?(await uc(e,t),`seeded`):_c(e,n,t)},yc=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
346
- `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},bc=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,xc=(e,t)=>{let n=[];if(e&&n.push(`checkout had local changes (managed checkouts are read-only) — discarded and restored to the remote state`),t!==void 0&&n.push(t),n.length!==0)return n.join(` | `)},Sc=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:bc(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=xc(n,r);return o!==void 0&&(a.warning=o),a},Cc=(e,t,n)=>{let r={dirty:t,shas:n};return e.branchRenamedTo!==void 0&&(r.branchRenamedTo=e.branchRenamedTo),e.warning!==void 0&&(r.setHeadWarning=e.warning),r},G=e=>le(h(e,`.git`)),wc=e=>`refusing to sync ${e}: not a refs-managed checkout`,Tc=async(e,t)=>{if(!G(t))throw x(wc(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw x(wc(t))},Ec=/filtering not recognized/iu,Dc=e=>e===void 0?{}:{cwd:e},K=(e,t,n)=>({action:e,args:t,cmd:`git`,...Dc(n)}),Oc=async(e,t)=>{let n=await e.run(t.cmd,t.args,Dc(t.cwd));if(n.exitCode===0)return n;let r=n.stderr.trim()||n.stdout.trim()||`exit code ${n.exitCode}`;throw x(`${t.action} failed: ${r}`)},kc=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await Oc(e,K(`git clone`,n));return await Oc(e,K(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&Ec.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}},Ac=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},jc=async(e,t)=>{let n=await Ac(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await Ac(e,t);if(r!==void 0)return r;throw x(`could not detect the default branch for checkout: ${t}`)},Mc=async(e,t)=>(await Oc(e,K(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),Nc=async(e,t)=>(await Oc(e,K(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Pc=async(e,t)=>{await Oc(e,K(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await jc(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${yc(n)}`),i},Fc=e=>[K(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),K(`git clean -fd`,[`clean`,`-fd`],e)],Ic=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Fc(r)),a.push(K(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),K(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await Oc(e,t)},Lc=async(e,t)=>{await Tc(e,t.dir);let n=await Mc(e,t.dir),r=await Pc(e,t),i=await Nc(e,t.dir);await Ic(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await Mc(e,t.dir);return Sc(Cc(r,i,{newSha:a,oldSha:n}))},Rc=async(e,t,n=20)=>(await Oc(e,K(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
347
- `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),zc=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,Bc=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
348
- `),Vc=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=h(e.hooksDir,n);await Ys(r,Bc),await t(r,493)}))},Hc=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Uc=/\d+\.\d+\.\d+/gu,Wc=e=>ss.safeParse(e).success,Gc=e=>{let t=e.match(Uc);return t!==null&&t.length>1},Kc=e=>{let t=Hc.exec(e);if(!t||Gc(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Wc(r))return r},qc=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},Jc=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Kc(r);e&&qc(t,e,n)}return t},Yc=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Xc=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])=>Yc(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Zc=e=>{let t=Jc(e);return Xc(t)},Qc=(e,t)=>e.replaceAll(`{version}`,()=>t),$c=async(e,t,n,r)=>{let i=Qc(n,r);if(!await zc(e,t,i))throw y(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},el=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,q=e=>{let t=e.replace(el,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},tl=/\.git$/u,nl=e=>e.replace(tl,``),rl=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)},il=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,al=/^git\+/u,ol={"https:":`443`,"ssh:":`22`},sl=e=>e.split(`/`).some(e=>e===`.`||e===`..`),cl=e=>e.includes(`\\`),ll=e=>e.includes(`%`),ul=e=>{let t=z.safeParse(e);if(!t.success)throw x(`not a supported git url: derived key '${q(e)}' is invalid`);return t.data},dl=({host:e,port:t,protocol:n})=>{let r=ol[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},fl=e=>{let t=nl(rl(e.path));return ul(`${dl(e)}/${t}`)},pl=e=>{let t=decodeURIComponent(e).split(`/`).filter(e=>e!==``);if(t.length<2)throw x(`not a supported git url: file url path must have at least 2 segments`);let n=t.at(-2)??``,r=t.at(-1)??``;return ul(`local/${n}/${r}`)},ml=(e,t)=>{try{return new URL(e)}catch{throw x(`not a supported git url: ${q(t)}`)}},hl=e=>{if(e.password!==``)throw x(`not a supported git url: credentials embedded in url`);if(e.protocol===`https:`&&e.username!==``)throw x(`not a supported git url: credentials embedded in https url`)},gl=(e,t)=>{if(e.protocol===`file:`){if(!t)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return pl(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return hl(e),fl({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},_l=(e,t)=>{if(ll(e))throw x(`not a supported git url: percent-encoding not supported in ${q(t)}`);if(e.includes(`:`))throw x(`not a supported git url: ambiguous ':' in scp-style path ${q(t)}; use the ssh:// url form instead`);if(e.startsWith(`/`)||e.startsWith(`~`))throw x(`not a supported git url: ambiguous absolute/home-relative scp path in ${q(t)}; use the ssh:// url form instead`)},vl=(e,t)=>{let n=e.groups?.path??``;return _l(n,t),fl({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},yl=(e,t)=>{if(cl(e))throw x(`not a supported git url: backslash not allowed in ${q(t)}`)},bl=(e,t)=>{if(sl(e))throw x(`not a supported git url: path traversal segment in ${q(t)}`)},xl=(e,t,n)=>{if(e.protocol!==`file:`&&ll(t))throw x(`not a supported git url: percent-encoding not supported in ${q(n)}`)},Sl=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(al,``);yl(r,e),bl(r,e);let i=il.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:vl(i,e)};let a=ml(r,e);return xl(a,r,e),{cloneUrl:r,key:gl(a,n)}},Cl=`.git`,wl=e=>e.endsWith(Cl)?e:`${e}${Cl}`,Tl=(e,t)=>`https://${e.toLowerCase()}/${rl(t)}`,El=(e,t)=>`git@${e.toLowerCase()}:${wl(rl(t))}`,Dl=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw x(`not a supported git url: unsupported protocol ${e}`)},Ol=(e,t,n)=>{let r=ol[e.protocol];if(e.port!==``&&e.port!==r)throw x(`cannot apply git_transport=${t} to ${q(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},kl=(e,t)=>t===`https`?Tl(e.hostname,e.pathname):El(e.hostname,e.pathname),Al=(e,t,n)=>{let r=Sl(t).key;if(r!==n)throw x(`git_transport transform changed repo identity: '${q(e)}' → '${t}' (key '${n}' → '${r}')`);return t},jl=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Al(t.cloneUrl,Tl(n,r),t.originalKey)},Ml=e=>{let t=ml(e.cloneUrl,e.cloneUrl);return Dl(t.protocol)===e.transport?e.cloneUrl:(Ol(t,e.transport,e.cloneUrl),Al(e.cloneUrl,kl(t,e.transport),e.originalKey))},Nl=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:Sl(e).key,transport:t},r=il.exec(e);return r?.groups===void 0?Ml(n):jl(r,n)},Pl=`meta.json`,Fl=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},Il=e=>{try{return process.kill(e,0),!0}catch(e){return Fl(e)!==`ESRCH`}},Ll=e=>{try{return JSON.parse(e)}catch{return}},Rl=async e=>{try{return await o(e,`utf8`)}catch{return}},zl=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Bl=e=>{if(typeof e!=`object`||!e)return;let t=e,{pid:n}=t,r=zl(t.acquired_at);if(typeof n==`number`&&r!==void 0)return{acquiredAtMs:r,pid:n}},Vl=async e=>{let t=await Rl(h(e,Pl));if(t!==void 0)return Bl(Ll(t))},Hl=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Ul=async e=>{let t=await Rl(h(e,Pl));if(t!==void 0)return Hl(Ll(t))},Wl=async e=>{try{return(await f(e)).mtimeMs}catch{return}},Gl=async(e,t)=>{let n=h(e,Pl),r=`${n}.tmp-${se()}`;await p(r,t,`utf8`),await l(r,n)},Kl=async(e,t)=>{await Gl(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},ql=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),Jl=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),Yl=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Fl(e);if(t!==void 0&&ql.has(t))return!1;throw e}},Xl=async(e,t)=>{try{return await l(e,t),!0}catch(e){let t=Fl(e);if(t!==void 0&&Jl.has(t))return!1;throw e}},Zl=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,Ql=async e=>{let t=await Vl(e);if(t===void 0){let t=await Wl(e);return t!==void 0&&Date.now()-t>5e3}return Date.now()-t.acquiredAtMs>6e5||!Il(t.pid)},$l=async(e,t)=>{try{await Kl(e,t)}catch(e){if(Fl(e)===`ENOENT`)return`retry`;throw e}return t},eu=async(e,t)=>{if(!await Yl(e))return;let n=await $l(e,se());return n===`retry`?Date.now()>=t?void 0:eu(e,t):n},tu=e=>h(e.locksDir,`${e.name}.steal-claim`),nu=e=>h(e.locksDir,`${e.name}.steal.${se()}`),ru=async e=>{let t=await Wl(e);return t!==void 0&&Date.now()-t>2e3},iu=async e=>await Yl(e)?!0:await ru(e)?(await u(e,{force:!0,recursive:!0}),Yl(e)):!1,au=async e=>{let t=nu(e);return await Xl(e.lockPath,t)?t:void 0},ou=async e=>{if(!await Ql(e.lockPath))return!1;let t=await au(e);return t!==void 0&&(await u(t,{force:!0,recursive:!0}),!0)},su=async e=>{let t=tu(e);if(!await iu(t))return!1;try{return await ou(e)}finally{await u(t,{force:!0,recursive:!0})}},cu=async(e,t)=>{if(!(await Ql(e.lockPath)&&await su(e))){if(Date.now()>=t)throw ve(`lock ${e.name} is held — another refs process is running`);await fe(100)}},lu=async(e,t)=>{let n=await eu(e.lockPath,t);return n===void 0?(await cu(e,t),lu(e,t)):n},uu=async(e,t)=>{await Ul(e)===t&&await u(e,{force:!0,recursive:!0})},du=e=>{if(e===`.`||e===`..`||!Zl.test(e))throw x(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.-" are allowed, and it may not be "." or "..": ${e}`)},J=async(e,t,n,r)=>{du(t);let i={lockPath:h(e.locksDir,t),locksDir:e.locksDir,name:t};await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await lu(i,o);try{return await n()}finally{await uu(i.lockPath,s)}},fu=lo({directory:I().optional(),url:I().optional()}),pu=lo({repository:fo([I(),fu]).optional()}),mu=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,hu=new Set([`node_modules`,`favicon.ico`]),gu=e=>y(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),_u=e=>{let[t,n]=e.split(`/`);return n??t??e},vu=e=>{if(e.length>214)throw b(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!mu.test(e))throw b(`invalid package name: '${e}' does not match npm naming rules`);let t=_u(e);if(hu.has(t))throw b(`invalid package name: '${e}' uses a reserved name`)},yu=e=>e.replaceAll(`/`,`%2F`),bu=e=>typeof e==`string`?e:e?.url,xu=e=>{if(typeof e==`object`&&e?.directory){let t=cs.safeParse(e.directory);if(t.success)return t.data}},Su=async(e,t)=>{try{return await e.json()}catch{throw x(`invalid npm registry response for '${t}': not parseable JSON`)}},Cu=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${yu(t)}`);if(n.status===404)throw y(`npm package '${t}' not found`);if(n.status!==200)throw x(`failed to fetch npm package '${t}': status ${n.status}`);let r=await Su(n,t),i=pu.safeParse(r);if(!i.success)throw x(`invalid npm package response for '${t}'`);return i.data},wu=(e,t)=>{try{return Sl(e)}catch{throw gu(t)}},Tu=async(e,t)=>{vu(t);let n=await Cu(e,t),r=bu(n.repository);if(r===void 0||r===``)throw gu(t);let{cloneUrl:i,key:a}=wu(r,t),o=xu(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},Eu=new Set;let Du=!1;const Ou=()=>{for(let e of Eu)try{e.kill(`SIGKILL`)}catch{}},ku=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],Au=e=>{let t=()=>{Ou(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},ju=()=>{Du||(Du=!0,ku.forEach(e=>{Au(e)}),process.on(`exit`,Ou))},Mu=()=>{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}}},Nu=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
349
- `),Pu=(e,t,n)=>{let r=e;return t.truncated&&(r=Nu(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=Nu(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},Fu={clear:()=>{},markedTimedOut:()=>!1},Iu=(e,t)=>{if(t===void 0)return Fu;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}},Lu=e=>e===void 0?{}:{cwd:e},Ru=(e,t)=>Nu(e,`refs: command timed out after ${String(t)}ms`),zu=(e,t)=>({exitCode:124,stderr:Ru(e,t),stdout:``,timedOut:!0}),Bu=(e,t,n)=>{let r=ge(e,t,{...Lu(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});Eu.add(r);let i=Mu(),a=Mu();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:Iu(r,n?.timeoutMs)}},Vu=(e,t,n)=>{try{return Bu(e,t,n)}catch(e){return{exitCode:127,stderr:Uu(e),stdout:``}}},Hu=e=>!(`child`in e),Uu=e=>e instanceof Error?e.message:String(e),Wu=async e=>{try{let[t]=await me(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:Uu(e)}}},Gu=e=>e===null?1:e,Ku=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,qu=e=>e.timedOut?zu(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Ku({exitCode:Gu(e.code),stderr:Pu(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Ku({exitCode:127,stderr:Nu(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Ju=class{async run(e,t,n){ju();let r=Vu(e,t,n);if(Hu(r))return r;let i=await Wu(r.child);return Eu.delete(r.child),r.timeout.clear(),qu({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Yu=fs.partial({description:!0}),Xu=R({default_branch:I().min(1),key:z,tag_format_candidate:ss.nullable(),url:I().min(1)});Xu.extend({description:I().default(``),packages:qo(Yu)});const Zu=Xu.extend({description:I().min(1),packages:qo(fs)}),Qu=R({effective_clone_mode:as.optional(),head_sha:I().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:I().optional(),last_fetched_at:ca().optional(),pending_proposal_at:ca().optional()}),$u=R({refs:Go(e=>e.length>0&&!Wo.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,go(I(),Qu)).default({})}),Y=(e,t,n)=>t?.[e]??n[e],ed=async e=>{try{return await o(e.statePath,`utf8`)}catch(e){if(V(e))return;throw e}},td=e=>{try{return JSON.parse(e)}catch{return}},X=async e=>{let t=await ed(e);if(t===void 0)return $u.parse({});let n=td(t);if(n===void 0)return $u.parse({});let r=$u.safeParse(n);return r.success?r.data:$u.parse({})},nd=async(e,t)=>{let n=$u.safeParse(t);if(!n.success)throw x(O(n.error));await Ys(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},rd=/^\d+\.\d+\.\d+$/u,id=/^0+(?=\d)/u,ad=(e,t)=>{let n=e.replace(id,``),r=t.replace(id,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},od=(e,t)=>{if(!rd.test(e)||!rd.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>ad(e,r[t]??``)).find(e=>e!==0)??0},sd=lo({version:I().regex(rd)}),cd=R({checked_at:ca(),latest_version:I().regex(rd)}),ld=async e=>{try{let t=cd.safeParse(JSON.parse(await o(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},ud=async(e,t)=>{try{await f(e.root),await Ys(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},dd=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},fd=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=sd.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},pd=async e=>{let t=await ld(e.home);if(t!==void 0&&dd(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await fd(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await ud(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},md=(e,t)=>{let n=od(e,t);return n!==void 0&&n<0},hd=(e,t)=>`refs ${t} is available (this is ${e}) — update: npm i -g @kaisers-io/refs@latest`,gd=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},_d=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},vd={check:!0,notify:!0},yd=e=>{let t=gd(e.env);return t===void 0?(e.updates??vd).check?_d(e.env)?`ci`:`on`:`config`:t?`on`:`env`},bd=e=>yd(e)===`on`,xd=e=>bd(e)&&(e.updates??vd).notify,Sd=/[/\\]/u,Cd={kind:`ignore`},wd=e=>!ne(e)&&e.split(Sd).every(e=>e!==`.`&&e!==`..`),Td=e=>wd(e)&&!e.startsWith(`!`)&&!e.includes(`**`)&&(e.match(/\*/gu)??[]).length<=1,Ed=e=>Td(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`}:e===`*`?{baseDir:`.`,kind:`expand-children`}:e.includes(`*`)?Cd:{dir:e,kind:`probe-dir`}:Cd,Dd=(e,t)=>{if(t&&e===``)return!0;let n=e===`..`||e.startsWith(`..`+oe);return e!==``&&!n&&!ne(e)},Od=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>re.join(e,t)),kd=(e,t)=>t?.name?{description:t.description,name:t.name,path:e}:void 0,Ad=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},jd=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,Md=/^packages:\s*(?:#.*)?$/u,Nd=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Pd=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!Nd(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},Fd=Symbol(`end-of-section`),Id=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!Md.test(e))return Fd;if(!t.startsWith(`-`))return;let n=jd.exec(e)?.groups?.pattern?.trim();if(n)return n},Ld=e=>{let t=[];for(let n of e){let e=Id(n);if(e===Fd)break;e!==void 0&&t.push(e)}return t},Rd=e=>{let t=e.findIndex(e=>Md.test(e));return t===-1?[]:Ld(e.slice(t+1))},zd=e=>{let{name:t}=e;if(typeof t==`string`)return t},Bd=e=>{let{description:t}=e;if(typeof t==`string`)return t},Vd=async(e,t,n=!1)=>{try{let r=await c(e),i=await c(t);return Dd(ie(r,i),n)}catch{return!1}},Hd=async(e,t)=>{try{let n=h(t,`package.json`);return await Vd(e,n)?(await o(n,`utf8`),!0):!1}catch{return!1}},Ud=async(e,t)=>{try{let n=h(e,t);if(!await Vd(e,n,t===`.`))return[];let r=(await s(n,{withFileTypes:!0})).filter(e=>e.isDirectory()),i=await Promise.all(r.map(t=>Hd(e,h(n,t.name))));return Od(t,r.map(e=>e.name),i)}catch{return[]}},Wd=async(e,t)=>{let n=Ed(t);if(n.kind===`expand-children`)return Ud(e,n.baseDir);if(n.kind===`probe-dir`){let t=h(e,n.dir);if(await Vd(e,t)&&await Hd(e,t))return[n.dir]}return[]},Gd=async(e,t)=>{try{let n=h(t,`package.json`);if(!await Vd(e,n))return;let r=await o(n,`utf8`),i=JSON.parse(r);return{description:Bd(i),name:zd(i)}}catch{return}},Kd=async(e,t)=>{let n=new Set;try{if(!await Vd(e,t))return n;let r=await o(t,`utf8`),i=JSON.parse(r);Pd(i.workspaces).forEach(e=>n.add(e))}catch{}return n},qd=async(e,t)=>{let n=new Set;try{if(!await Vd(e,t))return n;let r=await o(t,`utf8`);Rd(r.split(`
350
- `)).forEach(e=>n.add(e))}catch{}return n},Jd=async(e,t)=>{let n=new Set,r=[...t].map(t=>Wd(e,t));return(await Promise.all(r)).forEach(e=>{e.forEach(e=>n.add(e))}),n},Yd=async(e,t)=>{let n=h(e,t);if(await Vd(e,n))return kd(t,await Gd(e,n))},Xd=async(e,t)=>{let n=[...t].map(t=>Yd(e,t));return(await Promise.all(n)).filter(e=>e!==void 0)},Zd=async e=>{let t=h(e,`package.json`),n=h(e,`pnpm-workspace.yaml`),r=await Kd(e,t),i=await qd(e,n),a=new Set([...r,...i]);if(a.size===0)return[];let o=await Jd(e,a),s=await Xd(e,o);return Ad(s)};var Qd=`0.9.0`;const $d=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},ef=()=>{try{return de()}catch{return``}},tf=()=>({cliVersion:Qd,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:ef(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:$d,runner:new Ju});var nf=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}},rf=class extends nf{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},af=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 rf(`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 of(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var sf=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=>of(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
351
- `)}displayWidth(e){return _e(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
317
+ `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),Ol=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:vl(t)&&vl(r)&&(n[e]=Ol(t,r))}return n},kl={meta:{},refs:{},settings:{}},Al=async e=>{try{return await bl(e)}catch(e){if(e instanceof _&&e.code===`not_found`)return;throw e}},jl=e=>{if(e!==void 0&&e>1)throw b(`config schema ${e} is newer than this CLI supports — upgrade refs`)},Ml=async(e,t,n)=>{let r=yl(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await fl(e.configPath,dl(i))},Nl=async(e,t,n)=>{await r(e.configPath,pl(e));let i=Ol(t,kl),a=yl(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=Nc.safeParse(o);if(!s.success)throw b(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${pl(e)}): ${D(s.error)}`);await fl(e.configPath,dl(o))},Pl=async(e,t,n)=>{let r=xl(t,e.configPath),i=Cl(r);return jl(i),i===1?(await Ml(e,r,n),`noop`):(await Nl(e,r,n),`migrated`)},Fl=async(e,t)=>{let n=await Al(e);return n===void 0?(await Dl(e,t),`seeded`):Pl(e,n,t)},Il=new Set([`ENOENT`,`ENOTDIR`]),Ll=e=>e.code??String(e),Rl=async e=>{try{return await i(e),!0}catch{return!1}},zl=(e,t)=>{let n=se(e,t);return n===``||n!==`..`&&!n.startsWith(`..`+le)&&!ae(n)},Bl=async e=>{try{return{real:await l(e)}}catch(e){return{code:Ll(e)}}},Vl=async(e,t)=>{let n=await Bl(e);if(`code`in n)return{code:n.code,kind:`unreadable`};let r=await Bl(t);return`code`in r?Il.has(r.code)?await Rl(t)?{code:r.code,kind:`unreadable`}:{kind:`missing`}:{code:r.code,kind:`unreadable`}:zl(n.real,r.real)?{kind:`inside`,real:r.real}:{kind:`outside`}},Hl=e=>{let t=e.stderr.trim()||e.stdout.trim()||`exit code ${e.exitCode}`,n=t.split(`
318
+ `)[0]??t;return n.length<=200?n:`${n.slice(0,200)}…`},Ul=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,Wl=(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(` | `)},Gl=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:Ul(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=Wl(n,r);return o!==void 0&&(a.warning=o),a},Kl=(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},W=e=>fe(m(e,`.git`)),ql=e=>`refusing to sync ${e}: not a refs-managed checkout`,Jl=async(e,t)=>{if(!W(t))throw b(ql(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw b(ql(t))},Yl=/filtering not recognized/iu,Xl=e=>e===void 0?{}:{cwd:e},G=(e,t,n)=>({action:e,args:t,cmd:`git`,...Xl(n)}),Zl=async(e,t)=>{let n=await e.run(t.cmd,t.args,Xl(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}`)},Ql=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await Zl(e,G(`git clone`,n));return await Zl(e,G(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&Yl.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}},$l=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},eu=async(e,t)=>{let n=await $l(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await $l(e,t);if(r!==void 0)return r;throw b(`could not detect the default branch for checkout: ${t}`)},tu=async(e,t)=>(await Zl(e,G(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),nu=async(e,t)=>(await Zl(e,G(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,ru=async(e,t)=>{await Zl(e,G(`git fetch`,[`fetch`,`--prune`,`--tags`,`origin`],t.dir));let n=await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t.dir}),r=await eu(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${Hl(n)}`),i},iu=e=>[G(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),G(`git clean -fd`,[`clean`,`-fd`],e)],au=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...iu(r)),a.push(G(`git checkout -B`,[`checkout`,`-B`,n,`origin/${n}`],r),G(`git reset --hard`,[`reset`,`--hard`,`origin/${n}`],r));for(let t of a)await Zl(e,t)},ou=async(e,t)=>{await Jl(e,t.dir);let n=await tu(e,t.dir),r=await ru(e,t),i=await nu(e,t.dir);await au(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await tu(e,t.dir);return Gl(Kl(r,i,{newSha:a,oldSha:n}))},su=async(e,t,n=20)=>(await Zl(e,G(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
319
+ `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),cu=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,lu=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
320
+ `),uu=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await fl(r,lu),await t(r,493)}))},du=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,fu=/\d+\.\d+\.\d+/gu,pu=e=>Cc.safeParse(e).success,mu=e=>{let t=e.match(fu);return t!==null&&t.length>1},hu=e=>{let t=du.exec(e);if(!t||mu(e))return;let[n]=t,r=e.replace(n,`{version}`);if(pu(r))return r},gu=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},_u=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=hu(r);e&&gu(t,e,n)}return t},vu=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,yu=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])=>vu(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},bu=e=>{let t=_u(e);return yu(t)},xu=(e,t)=>e.replaceAll(`{version}`,()=>t),Su=async(e,t,n,r)=>{let i=xu(n,r);if(!await cu(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Cu=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,K=e=>{let t=e.replace(Cu,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},wu=/\.git$/u,Tu=e=>e.replace(wu,``),Eu=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)},Du=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,Ou=/^git\+/u,ku={"https:":`443`,"ssh:":`22`},Au=e=>e.split(`/`).some(e=>e===`.`||e===`..`),ju=e=>e.includes(`\\`),Mu=e=>e.includes(`%`),Nu=e=>{let t=R.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${K(e)}' is invalid`);return t.data},Pu=({host:e,port:t,protocol:n})=>{let r=ku[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},Fu=e=>{let t=Tu(Eu(e.path));return Nu(`${Pu(e)}/${t}`)},Iu=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 Nu(`local/${n}/${r}`)},Lu=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${K(t)}`)}},Ru=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`)},zu=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return Iu(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return Ru(e),Fu({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},Bu=(e,t)=>{if(Mu(e))throw b(`not a supported git url: percent-encoding not supported in ${K(t)}`);if(e.includes(`:`))throw b(`not a supported git url: ambiguous ':' in scp-style path ${K(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 ${K(t)}; use the ssh:// url form instead`)},Vu=(e,t)=>{let n=e.groups?.path??``;return Bu(n,t),Fu({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},Hu=(e,t)=>{if(ju(e))throw b(`not a supported git url: backslash not allowed in ${K(t)}`)},Uu=(e,t)=>{if(Au(e))throw b(`not a supported git url: path traversal segment in ${K(t)}`)},Wu=(e,t,n)=>{if(e.protocol!==`file:`&&Mu(t))throw b(`not a supported git url: percent-encoding not supported in ${K(n)}`)},q=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(Ou,``);Hu(r,e),Uu(r,e);let i=Du.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:Vu(i,e)};let a=Lu(r,e);return Wu(a,r,e),{cloneUrl:r,key:zu(a,n)}},Gu=`.git`,Ku=e=>e.endsWith(Gu)?e:`${e}${Gu}`,qu=(e,t)=>`https://${e.toLowerCase()}/${Eu(t)}`,Ju=(e,t)=>`git@${e.toLowerCase()}:${Ku(Eu(t))}`,Yu=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},Xu=(e,t,n)=>{let r=ku[e.protocol];if(e.port!==``&&e.port!==r)throw b(`cannot apply git_transport=${t} to ${K(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},Zu=(e,t)=>t===`https`?qu(e.hostname,e.pathname):Ju(e.hostname,e.pathname),Qu=(e,t,n)=>{let r=q(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${K(e)}' → '${t}' (key '${n}' → '${r}')`);return t},$u=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return Qu(t.cloneUrl,qu(n,r),t.originalKey)},ed=e=>{let t=Lu(e.cloneUrl,e.cloneUrl);return Yu(t.protocol)===e.transport?e.cloneUrl:(Xu(t,e.transport,e.cloneUrl),Qu(e.cloneUrl,Zu(t,e.transport),e.originalKey))},td=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:q(e).key,transport:t},r=Du.exec(e);return r?.groups===void 0?ed(n):$u(r,n)},nd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,rd=(e,t)=>{if(nd.test(t))return m(e,`lease-${t}`)},id=async(e,t)=>{let n=rd(e,t);n!==void 0&&await(await o(n,`w`)).close()},ad=async(e,t)=>{let n=rd(e,t);if(n===void 0)return`gone`;let r=new Date;try{await ee(n,r,r)}catch(e){if(B(e))return`gone`;throw e}return`renewed`},od=async(e,t)=>{let n=rd(e,t);if(n===void 0)return{state:`absent`};try{return{mtimeMs:(await p(n)).mtimeMs,state:`ok`}}catch(e){return{state:B(e)?`absent`:`unreadable`}}},sd=`meta.json`,cd=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},ld=e=>{try{return process.kill(e,0),!0}catch(e){return cd(e)!==`ESRCH`}},ud=e=>{try{return JSON.parse(e)}catch{return}},dd=async e=>{try{return await s(e,`utf8`)}catch{return}},fd=new Set([`ENOENT`,`ENOTDIR`]),pd=async e=>{try{return{state:`read`,text:await s(e,`utf8`)}}catch(e){let t=cd(e);return{state:t!==void 0&&fd.has(t)?`missing`:`unreadable`}}},md=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},hd=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},gd=e=>{if(!(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>2147483647))return e},_d=e=>{if(typeof e!=`object`||!e)return;let t=e,n=gd(t.pid),r=md(t.acquired_at);if(n===void 0||r===void 0)return;let i=hd(e);return{acquiredAtMs:r,pid:n,...i===void 0?{}:{token:i}}},vd=async e=>{let t=await dd(m(e,sd));if(t!==void 0)return hd(ud(t))},yd=async e=>{let t=await pd(m(e,sd));if(t.state!==`read`)return{state:t.state};let n=_d(ud(t.text));return n===void 0?{state:`malformed`}:{meta:n,state:`valid`}},bd=async e=>{try{return{mtimeMs:(await p(e)).mtimeMs,state:`ok`}}catch(e){return{state:cd(e)===`ENOENT`?`gone`:`unreadable`}}},xd=async e=>{try{return(await p(e)).mtimeMs}catch{return}},Sd=async(e,t)=>{let n=m(e,sd),r=`${n}.tmp-${ue()}`;await te(r,t,`utf8`),await u(r,n)},Cd=()=>ue(),wd=async(e,t)=>{await id(e,t),await Sd(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Td=5e3,Ed=async(e,t,n)=>{if(t===`unreadable`)return{meta:t,observedAtMs:n,pidState:`unknown`,policy:`unknown`,stale:!1};let r=await bd(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:Td,meta:t,observedAtMs:n,pidState:`unknown`,policy:`grace`,stale:i>Td}},Dd=async(e,t,n)=>{let r=t.token===void 0?{state:`absent`}:await od(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`}},Od=async(e,t)=>{let n=await yd(e);if(n.state!==`valid`)return Ed(e,n.state,t);let{meta:r}=n,i=await Dd(e,r,t),a=!ld(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}},kd=async e=>(await Od(e,Date.now())).stale,Ad=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`},jd=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)`,Md={grace:`created`,lease:`lease renewed`,legacy:`acquired`,none:`observed`,unknown:`observed`},Nd={grace:`from creation, while its metadata has not been published`,lease:`from the last renewal`,legacy:`from acquisition (no renewable lease)`,none:``,unknown:``},Pd=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`:`, ${Md[r]} ${Ad(t)} ago; reclaimable ${Ad(n)} ${Nd[r]}`},Fd=(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: ${jd(t)}`;return t.stale?`${n}, and the lock is already reclaimable — refs could not reclaim it before the timeout. Retry; if it persists, run refs doctor.`:`${n}${Pd(t)}. Retry once the other refs command finishes.`},Id=async(e,t)=>await vd(e)===t?await ad(e,t)===`gone`?`lost`:`renewed`:`lost`,Ld=/\.steal\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,Rd=async e=>{try{return(await c(e)).length===0}catch{return!1}},zd=async(e,t)=>Ld.test(t)?!0:t.endsWith(`.steal-claim`)?await Rd(m(e,t)):!1,Bd=async e=>{try{let t=await c(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>({artifact:await zd(e,t.name),isDir:t.isDirectory(),name:t.name})))).filter(e=>!e.artifact).map(e=>({isDir:e.isDir,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}catch(e){if(B(e))return[];throw e}},Vd=async(e,t,n)=>{let r=await Od(m(e,t.name),n);if(r.policy!==`none`)return{diagnosis:r,isDirectory:t.isDir,name:t.name}},Hd=async e=>{let t=Date.now(),n=await Bd(e.locksDir);return(await Promise.all(n.map(n=>Vd(e.locksDir,n,t)))).filter(e=>e!==void 0)},Ud=(e,t)=>{if(t.stopped)return;let n=setTimeout(()=>{t.stopped||(t.inFlight=Wd(e,t))},e.intervalMs);n.unref(),t.timer=n},Wd=async(e,t)=>{try{if(await e.renew()===`lost`){t.lost=!0,t.stopped=!0;return}}catch{}Ud(e,t)},Gd=e=>{let t={inFlight:Promise.resolve(),lost:!1,stopped:!1};return Ud(e,t),{ownershipLost:()=>t.lost,stop:async()=>{t.stopped=!0,t.timer!==void 0&&clearTimeout(t.timer),await t.inFlight}}},Kd=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),qd=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),Jd=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=cd(e);if(t!==void 0&&Kd.has(t))return!1;throw e}},Yd=async(e,t)=>{try{return await u(e,t),!0}catch(e){let t=cd(e);if(t!==void 0&&qd.has(t))return!1;throw e}},Xd=e=>m(e.locksDir,`${e.name}.steal-claim`),Zd=e=>m(e.locksDir,`${e.name}.steal.${ue()}`),Qd=async e=>{let t=await xd(e);return t!==void 0&&Date.now()-t>2e3},$d=async e=>await Jd(e)?!0:await Qd(e)?(await d(e,{force:!0,recursive:!0}),Jd(e)):!1,ef=async e=>{let t=Zd(e);return await Yd(e.lockPath,t)?t:void 0},tf=async e=>{if(!await kd(e.lockPath))return!1;let t=await ef(e);return t!==void 0&&(await d(t,{force:!0,recursive:!0}),!0)},nf=async e=>{let t=Xd(e);if(!await $d(t))return!1;try{return await tf(e)}finally{await d(t,{force:!0,recursive:!0})}},rf=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,af=async(e,t)=>{try{await wd(e,t)}catch(e){if(cd(e)===`ENOENT`)return`retry`;throw e}return t},of=async(e,t)=>{if(!await Jd(e))return;let n=await af(e,Cd());return n===`retry`?Date.now()>=t?void 0:of(e,t):n},sf=async(e,t)=>{if(!(await kd(e.lockPath)&&await nf(e))){if(Date.now()>=t){let t=await Od(e.lockPath,Date.now());throw xe(Fd(e.name,t))}await he(100)}},cf=async(e,t)=>{let n=await of(e.lockPath,t);return n===void 0?(await sf(e,t),cf(e,t)):n},lf=async(e,t)=>await vd(e)===t&&(await d(e,{force:!0,recursive:!0}),!0),uf=async e=>{try{return{ok:!0,value:await e()}}catch(e){return{error:e,ok:!1}}},df=async(e,t,n,r)=>{await n.stop();let i=await uf(()=>lf(e.lockPath,t));if(!r.ok)throw r.error;if(!i.ok)throw i.error;if(n.ownershipLost()||!i.value)throw xe(`lock ${e.name} was lost while the operation was running`);return r.value},ff=e=>{if(e===`.`||e===`..`||!rf.test(e))throw b(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.-" are allowed, and it may not be "." or "..": ${e}`)},J=async(e,t,n,r)=>{ff(t);let i={lockPath:m(e.locksDir,t),locksDir:e.locksDir,name:t};await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await cf(i,o),c=Gd({intervalMs:3e4,renew:()=>Id(i.lockPath,s)});return df(i,s,c,await uf(n))},pf=Ts({directory:F().optional(),url:F().optional()}),mf=Ts({repository:Ds([F(),pf]).optional()}),hf=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,gf=new Set([`node_modules`,`favicon.ico`]),_f=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),vf=e=>{let[t,n]=e.split(`/`);return n??t??e},yf=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!hf.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=vf(e);if(gf.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},bf=e=>e.replaceAll(`/`,`%2F`),xf=e=>typeof e==`string`?e:e?.url,Sf=e=>{if(typeof e==`object`&&e?.directory){let t=wc.safeParse(e.directory);if(t.success)return t.data}},Cf=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},wf=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${bf(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 Cf(n,t),i=mf.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},Tf=(e,t)=>{try{return q(e)}catch{throw _f(t)}},Ef=async(e,t)=>{yf(t);let n=await wf(e,t),r=xf(n.repository);if(r===void 0||r===``)throw _f(t);let{cloneUrl:i,key:a}=Tf(r,t),o=Sf(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},Df=new Set([`candidate_not_inspected`,`manifest_unreadable`,`unsupported_pattern`,`workspace_declaration_unparsed`,`workspace_dir_unreadable`,`workspace_file_unreadable`]),Of=/[/\\]/u,kf={kind:`ignore`},Af=e=>!ae(e)&&e.split(Of).every(e=>e!==`.`&&e!==`..`),jf=e=>Af(e)&&!e.startsWith(`!`)&&!e.includes(`**`)&&(e.match(/\*/gu)??[]).length<=1,Mf=e=>jf(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`}:e===`*`?{baseDir:`.`,kind:`expand-children`}:e.includes(`*`)?kf:{dir:e,kind:`probe-dir`}:kf,Nf=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>oe.join(e,t)),Pf=(e,t)=>t?.name?{description:t.description,name:t.name,path:e}:void 0,Ff=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},If=e=>!e.diagnostics.some(e=>Df.has(e.kind)),Lf=e=>!e.diagnostics.some(e=>e.kind===`no_workspace_declaration`),Rf=(e,t)=>e<t?-1:+(e>t),zf=e=>`path`in e?`${e.kind} ${e.path}`:`file`in e?`${e.kind} ${e.file}`:`pattern`in e?`${e.kind} ${e.pattern}`:e.kind,Bf=e=>e.toSorted((e,t)=>Rf(zf(e),zf(t))),Vf=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,Hf=/^packages:\s*(?:#.*)?$/u,Uf=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Wf=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!Uf(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},Gf=Symbol(`end-of-section`),Kf=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!Hf.test(e))return Gf;if(!t.startsWith(`-`))return;let n=Vf.exec(e)?.groups?.pattern?.trim();if(n)return n},qf=e=>{let t=[];for(let n of e){let e=Kf(n);if(e===Gf)break;e!==void 0&&t.push(e)}return t},Jf=e=>{let t=e.findIndex(e=>Hf.test(e));return t===-1?[]:qf(e.slice(t+1))},Yf=e=>{let{name:t}=e;if(typeof t==`string`)return t},Xf=e=>{let{description:t}=e;if(typeof t==`string`)return t},Zf=e=>!ae(e)&&!e.split(/[/\\]/u).includes(`..`),Qf=(e,t)=>e.kind===`missing`?{kind:`absent`}:e.kind===`outside`?{kind:`unreadable`,reason:`${t} escapes the checkout`}:{kind:`unreadable`,reason:e.code},$f=async(e,t,n)=>{if(!Zf(t))return{kind:`unreadable`,reason:`path escapes the checkout`};let r=await ep(e,t);if(`probe`in r)return r.probe;let i=await tp(r.real);return`reason`in i?{kind:`unreadable`,reason:i.reason}:i.found===n?{kind:`match`}:{found:i.found,kind:`mismatch`}},ep=async(e,t)=>{let n=await Vl(e,m(e,t));if(n.kind!==`inside`)return{probe:Qf(n,`path`)};let r=await Vl(e,m(n.real,`package.json`));return r.kind===`inside`?{real:r.real}:{probe:Qf(r,`manifest`)}},tp=async e=>{try{let t=JSON.parse(await s(e,`utf8`));return{found:Yf(t)}}catch(e){return{reason:e.code??String(e)}}},np=(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(Rf)}},rp=new Set;let ip=!1;const ap=()=>{for(let e of rp)try{e.kill(`SIGKILL`)}catch{}},op=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],sp=e=>{let t=()=>{ap(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},cp=()=>{ip||(ip=!0,op.forEach(e=>{sp(e)}),process.on(`exit`,ap))},lp=()=>{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}}},up=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
321
+ `),dp=(e,t,n)=>{let r=e;return t.truncated&&(r=up(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=up(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},fp={clear:()=>{},markedTimedOut:()=>!1},pp=(e,t)=>{if(t===void 0)return fp;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}},mp=e=>e===void 0?{}:{cwd:e},hp=(e,t)=>up(e,`refs: command timed out after ${String(t)}ms`),gp=(e,t)=>({exitCode:124,stderr:hp(e,t),stdout:``,timedOut:!0}),_p=(e,t,n)=>{let r=ye(e,t,{...mp(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});rp.add(r);let i=lp(),a=lp();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:pp(r,n?.timeoutMs)}},vp=(e,t,n)=>{try{return _p(e,t,n)}catch(e){return{exitCode:127,stderr:bp(e),stdout:``}}},yp=e=>!(`child`in e),bp=e=>e instanceof Error?e.message:String(e),xp=async e=>{try{let[t]=await _e(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:bp(e)}}},Sp=e=>e===null?1:e,Cp=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,wp=e=>e.timedOut?gp(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Cp({exitCode:Sp(e.code),stderr:dp(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Cp({exitCode:127,stderr:up(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Tp=class{async run(e,t,n){cp();let r=vp(e,t,n);if(yp(r))return r;let i=await xp(r.child);return rp.delete(r.child),r.timeout.clear(),wp({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Ep=Oc.partial({description:!0}),Dp=L({default_branch:F().min(1),key:R,tag_format_candidate:Cc.nullable(),url:F().min(1)});Dp.extend({description:F().default(``),packages:lc(Ep)});const Op=Dp.extend({description:F().min(1),packages:lc(Oc)}),kp=L({effective_clone_mode:xc.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:ac().optional(),pending_proposal_at:ac().optional()}),Ap=L({refs:sc(e=>e.length>0&&!oc.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,js(F(),kp)).default({})}),jp=(e,t,n)=>t?.[e]??n[e],Mp=async e=>{try{return await s(e.statePath,`utf8`)}catch(e){if(B(e))return;throw e}},Np=e=>{try{return JSON.parse(e)}catch{return}},Y=async e=>{let t=await Mp(e);if(t===void 0)return Ap.parse({});let n=Np(t);if(n===void 0)return Ap.parse({});let r=Ap.safeParse(n);return r.success?r.data:Ap.parse({})},Pp=async(e,t)=>{let n=Ap.safeParse(t);if(!n.success)throw b(D(n.error));await fl(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Fp=/^\d+\.\d+\.\d+$/u,Ip=/^0+(?=\d)/u,Lp=(e,t)=>{let n=e.replace(Ip,``),r=t.replace(Ip,``);return n.length===r.length?n===r?0:n<r?-1:1:n.length<r.length?-1:1},Rp=(e,t)=>{if(!Fp.test(e)||!Fp.test(t))return;let n=e.split(`.`),r=t.split(`.`);return n.map((e,t)=>Lp(e,r[t]??``)).find(e=>e!==0)??0},zp=Ts({version:F().regex(Fp)}),Bp=L({checked_at:ac(),latest_version:F().regex(Fp)}),Vp=async e=>{try{let t=Bp.safeParse(JSON.parse(await s(e.updateCachePath,`utf8`)));return t.success?t.data:void 0}catch{return}},Hp=async(e,t)=>{try{await p(e.root),await fl(e.updateCachePath,`${JSON.stringify(t,void 0,2)}\n`)}catch{}},Up=(e,t)=>{let n=t-Date.parse(e.checked_at);return n>=0&&n<864e5},Wp=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=zp.safeParse(await t.json());return n.success?n.data.version:void 0}catch{return}},Gp=async e=>{let t=await Vp(e.home);if(t!==void 0&&Up(t,e.nowMs))return{latest:t.latest_version,refreshed:!1,stale:!1};let n=await Wp(e.fetch);return n===void 0?{latest:t?.latest_version,refreshed:!1,stale:!0}:(await Hp(e.home,{checked_at:new Date(e.nowMs).toISOString(),latest_version:n}),{latest:n,refreshed:!0,stale:!1})},Kp=(e,t)=>{let n=Rp(e,t);return n!==void 0&&n<0},qp=(e,t)=>`refs ${t} is available (this is ${e}) — update: npm i -g @kaisers-io/refs@latest`,Jp=e=>{let t=e.REFS_UPDATE_CHECK?.trim();if(t===`0`)return!1;if(t===`1`)return!0},Yp=e=>{let t=e.CI?.trim().toLowerCase();return t!==void 0&&t!==``&&t!==`false`&&t!==`0`},Xp={check:!0,notify:!0},Zp=e=>{let t=Jp(e.env);return t===void 0?(e.updates??Xp).check?Yp(e.env)?`ci`:`on`:`config`:t?`on`:`env`},Qp=e=>Zp(e)===`on`,$p=e=>Qp(e)&&(e.updates??Xp).notify,em=async(e,t)=>{let n=await Vl(e,m(t,`package.json`));if(n.kind===`inside`)try{let e=JSON.parse(await s(n.real,`utf8`));return{description:Xf(e),name:Yf(e)}}catch{return}},tm=async(e,t)=>{let n=await em(e,m(e,t));if(n===void 0)return{diagnostic:{kind:`manifest_unreadable`,path:t}};let r=Pf(t,n);return r===void 0?{diagnostic:{kind:`manifest_missing_name`,path:t}}:{pkg:r}},nm=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}},rm=async(e,t)=>{let n=await Vl(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}}},im=async(e,t)=>{let n=await rm(e,t);return n.ok?n.content===void 0?{ok:!0,patterns:new Set}:am(n.content):{ok:!1,patterns:new Set}},am=e=>{let t=new Set;try{let n=JSON.parse(e);Wf(n.workspaces).forEach(e=>t.add(e))}catch{return{ok:!1,patterns:t}}return{ok:!0,patterns:t}},om=/^packages:/mu,sm=async(e,t)=>{let n=new Set,r=await rm(e,t);return r.ok?r.content===void 0?{ok:!0,patterns:n}:(Jf(r.content.split(`
322
+ `)).forEach(e=>n.add(e)),{ok:!0,patterns:n,unparsed:n.size===0&&om.test(r.content)}):{ok:!1,patterns:n}},cm=async e=>{let[t,n]=await Promise.all([im(e,m(e,`package.json`)),sm(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,patterns:new Set([...t.patterns,...n.patterns])}},lm=new Set([`ENOENT`,`ENOTDIR`]),um=async(e,t)=>{let n=await Vl(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`}},dm=async e=>{try{return{entries:await c(e,{withFileTypes:!0})}}catch(e){return{code:e.code??``}}},fm=(e,t,n)=>Promise.all(n.map(n=>um(e,m(t,n.name)))),pm=(e,t,n)=>e.filter((e,r)=>n(t[r])).map(e=>e.name),mm=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([fm(i,r,n),fm(i,r,a)]);return{diagnostics:[...pm(n,s,e=>e===`rejected`).map(e=>({kind:`manifest_unreadable`,path:o(e)})),...pm(a,c,e=>e!==`none`).map(e=>({kind:`candidate_not_inspected`,path:o(e)}))],dirs:Nf(t,n.map(e=>e.name),s.map(e=>e===`manifest`))}},hm=async(e,t)=>{let n=m(e,t),r=await Vl(e,n);if(r.kind===`missing`)return{diagnostics:[],dirs:[]};if(r.kind!==`inside`)return{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]};let i=await dm(n);return`code`in i?lm.has(i.code)?{diagnostics:[],dirs:[]}:{diagnostics:[{kind:`workspace_dir_unreadable`,path:t}],dirs:[]}:mm({baseDir:t,dirs:i.entries.filter(e=>e.isDirectory()),fullPath:n,repoDir:e,symlinks:i.entries.filter(e=>e.isSymbolicLink())})},gm=(e,t)=>{let n=Mf(t);return n.kind===`expand-children`?hm(e,n.baseDir):n.kind===`probe-dir`?_m(e,n.dir):Promise.resolve({diagnostics:[{kind:`unsupported_pattern`,pattern:t}],dirs:[]})},_m=async(e,t)=>{let n=await um(e,m(e,t));return n===`manifest`?{diagnostics:[],dirs:[t]}:n===`rejected`?{diagnostics:[{kind:`manifest_unreadable`,path:t}],dirs:[]}:{diagnostics:[],dirs:[]}},vm=async(e,t)=>{let n=await Promise.all([...t].map(t=>gm(e,t))),r=new Set,i=[];for(let e of n)e.dirs.forEach(e=>r.add(e)),i.push(...e.diagnostics);return{diagnostics:i,dirs:[...r]}},ym=async e=>{let t=await cm(e);if(t.patterns.size===0)return{diagnostics:Bf([...t.diagnostics,{kind:`no_workspace_declaration`}]),packages:[]};let n=await vm(e,t.patterns),r=await Promise.all(n.dirs.map(t=>tm(e,t))),i=nm(r);return{diagnostics:Bf([...t.diagnostics,...n.diagnostics,...i.diagnostics]),packages:Ff(i.packages)}},bm=async e=>(await ym(e)).packages;var xm=`0.11.0`;const Sm=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Cm=()=>{try{return me()}catch{return``}},wm=()=>({cliVersion:xm,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:(e,t)=>fetch(e,t),homedir:Cm(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:Sm,runner:new Tp});var Tm=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}},Em=class extends Tm{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},Dm=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 Em(`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 Om(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var km=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=>Om(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(`
323
+ `)}displayWidth(e){return be(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
352
324
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
353
- `)}},cf=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=df(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 rf(`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?uf(this.name().replace(/^no-/,``)):uf(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}},lf=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 uf(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function df(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}
325
+ `)}},Am=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=Nm(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 Em(`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?Mm(this.name().replace(/^no-/,``)):Mm(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}},jm=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 Mm(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Nm(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
354
326
  - a short flag is a single dash and a single character
355
327
  - either use a single dash and a single character (for a short flag)
356
328
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
357
329
  - too many short flags`):i.test(t)?Error(`${n}
358
330
  - too many long flags`):Error(`${n}
359
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function ff(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function pf(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=ff(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var mf=class e extends pe{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>g.stdout.write(e),writeErr:e=>g.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>g.stdout.isTTY?g.stdout.columns:void 0,getErrHelpWidth:()=>g.stderr.isTTY?g.stderr.columns:void 0,getOutHasColors:()=>gf()??(g.stdout.isTTY&&g.stdout.hasColors?.()),getErrHasColors:()=>gf()??(g.stderr.isTTY&&g.stderr.hasColors?.()),stripColor:e=>_e(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new sf,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
360
- - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new af(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
361
- Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new nf(e,t,n)),g.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new cf(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
362
- - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof cf)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){g.versions?.electron&&(t.from=`electron`);let e=g.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=g.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:g.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
363
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(ce.existsSync(e))return;let r=`'${e}' does not exist
331
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function Pm(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function Fm(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=Pm(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var Im=class e extends ge{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>h.stdout.write(e),writeErr:e=>h.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>Rm()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>Rm()??(h.stderr.isTTY&&h.stderr.hasColors?.()),stripColor:e=>be(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new km,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
332
+ - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Dm(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
333
+ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Tm(e,t,n)),h.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new Am(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
334
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof Am)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){h.versions?.electron&&(t.from=`electron`);let e=h.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=h.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:h.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
335
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(de.existsSync(e))return;let r=`'${e}' does not exist
364
336
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
365
337
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
366
- - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=m.resolve(e,t);if(ce.existsSync(r))return r;if(n.includes(m.extname(t)))return;let i=n.find(e=>ce.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||``;if(this._scriptPath){let e;try{e=ce.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=m.resolve(m.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=m.basename(this._scriptPath,m.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(m.extname(i)),s;g.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=hf(g.execArgv).concat(t),s=he.spawn(g.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=hf(g.execArgv).concat(t),s=he.spawn(g.argv[0],t,{stdio:`inherit`})):s=he.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{g.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new nf(e,`commander.executeSubCommandAsync`,`(close)`)):g.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)g.exit(1);else{let e=new nf(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(`
367
- `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in g.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()}`,g.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new lf(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=pf(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=pf(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=>of(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=m.basename(e,m.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(g.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
368
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function hf(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 gf(){if(g.env.NO_COLOR||g.env.FORCE_COLOR===`0`||g.env.FORCE_COLOR===`false`)return!1;if(g.env.FORCE_COLOR||g.env.CLICOLOR_FORCE!==void 0)return!0}new mf;const _f=[],vf=e=>Array.isArray(e)?e:[e],yf=e=>e===void 0?_f:[e],bf=e=>e instanceof Error?e.message:String(e),Z=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},Q=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??_f};e.out(JSON.stringify(t));return}for(let t of vf(n))e.out(t);for(let t of i??_f)e.errLine(`refs: warning: ${t}`)},xf=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},Sf=(e,t)=>{e.errLine(`refs: ${t}`)},$=(e,t,n)=>async()=>{try{await n()}catch(n){let r=be(n,{verbose:t.verbose});xf(e,t,r),process.exitCode=r.exitCode}},Cf=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`}},wf=/^v(?<major>\d+)\.(?<minor>\d+)/u,Tf=e=>{let t=wf.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},Ef=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,Df=e=>{let{nodeVersion:t}=e;return Ef(Tf(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},Of=()=>_s.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),kf=async e=>{try{return{config:await W(e)}}catch(e){return{config:Of(),errorMessage:bf(e)}}},Af=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},jf={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)`},Mf=(e,t,n)=>{if(md(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${hd(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`}},Nf=async(e,t)=>{let n=yd({env:e.env,updates:t.updates});if(n!==`on`)return{detail:jf[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await pd({fetch:e.fetcher,home:H(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`}:Mf(e.cliVersion,r,i)},Pf=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),Ff=[`pre-commit`,`pre-push`],If=async(t,r)=>{try{return await e(h(t.hooksDir,r),n.X_OK),!0}catch{return!1}},Lf=async e=>{let t=await Promise.all(Ff.map(t=>If(e,t)));return Ff.filter((e,n)=>!t[n])},Rf=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},zf=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:`${Ff.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},Bf=async(e,t,n)=>{let r=Pf(t,n),[i,a]=await Promise.all([Lf(t),Promise.all(r.map(n=>Rf(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return zf({badKeys:o,checkoutCount:r.length,missingHooks:i})},Vf=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}},Hf=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`}},Uf=async(e,t,n)=>{let r=Pf(t,n),i=await Promise.all(r.map(t=>Vf(e,t)));return Hf(i)},Wf=async e=>{try{return await X(e)}catch{return $u.parse({})}},Gf=async e=>{try{return(await s(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(V(e))return[];throw e}},Kf=async(e,t)=>{if(G(e))return[[...t]];let n=await Gf(e);return(await Promise.all(n.map(n=>Kf(h(e,n),[...t,n])))).flat()},qf=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},Jf=(e,t,n)=>qf(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,Yf=(e,t)=>({dest:h(e.sourcesDir,...t),key:t.join(`/`)}),Xf=async(e,t,n)=>{let r=(await Kf(e.sourcesDir,[])).map(t=>Yf(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=>Jf(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},Zf=[`.agents`,`skills`,`refs`,`SKILL.md`],Qf=[`skills`,`refs`,`SKILL.md`],$f=[`.claude`,`skills`,`refs`,`SKILL.md`],ep=`npx skills add kaisers-io/refs`,tp=`npm i -g @kaisers-io/refs@latest`,np=(e,t)=>e===void 0?void 0:{display:t,path:e},rp=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}:np(r===void 0?void 0:h(r,t),`~/${t}`)},ip=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:np(t,`~/.agents`),segments:Zf},{label:`Claude Code`,root:rp({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:Qf},{label:`Codex`,root:rp({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:Qf},{label:`project ./.agents`,root:np(e.cwd,`./.agents`),segments:Zf},{label:`project ./.claude`,root:np(e.cwd,`./.claude`),segments:$f}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:h(t.path,...n)}])},ap=async(e,t)=>{try{let n=await c(e);return{label:t,realPath:n,source:await o(n,`utf8`)}}catch{return}},op=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},sp=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,cp=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,lp=e=>{let t=sp.exec(e)?.groups?.body;if(t!==void 0)return cp.exec(t)?.groups?.version},up=(e,t)=>{if(e===t)return`match`;let n=od(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},dp={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${tp}`,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: ${ep}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${tp} and ${ep}`},fp=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: ${ep}`,name:`skill`,status:`warn`};let i=up(r,t);return{detail:`${n}: ${dp[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},pp=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: ${ep}`,name:`skill`,status:`warn`}),mp=async e=>{let t=ip(e),n=await Promise.all(t.map(e=>ap(e.path,e.label))),r=op(n.filter(e=>e!==void 0)).map(t=>fp({cliVersion:e.cliVersion,label:t.label,skillVersion:lp(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??pp(t)},hp=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,gp=e=>e===``?{}:{user:e},_p=e=>e===``?{}:{port:e},vp=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...gp(t.username),..._p(t.port)}:void 0}catch{return}},yp=e=>{let t=hp.exec(e),n=t?.groups?.host;return n===void 0?vp(e):{host:n,user:t?.groups?.user??`git`}},bp=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,xp=e=>e.user===void 0?bp(e):`${e.user}@${bp(e)}`,Sp=e=>{let t=Object.values(e.refs).map(e=>yp(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(xp(e),e);return[...n.values()].toSorted((e,t)=>xp(e).localeCompare(xp(t)))},Cp=/Permission denied/u,wp=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Tp=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,Ep=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Tp(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},Dp=async(e,t,n)=>{let r=xp(t),i=await e.runner.run(`ssh`,Ep(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:Cp.test(i.stderr)?{host:r,outcome:`denied`}:wp.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},Op=(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`}},kp=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`}},Ap=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`}},jp=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),Mp=(e,t)=>Op(e,t)??kp(e)??Ap(e)??jp(e),Np=async(e,t,n)=>{let r=Sp(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>Dp(e,t,i)));return Mp(a,i)},Pp=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${bf(t)}`,name:e.name,status:`fail`}}},Fp=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await Pp(t),i=await Fp(n);return r===void 0?i:[r,...i]},Ip=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Cf(n)},{name:`node`,run:()=>Promise.resolve(Df(n))},{name:`config`,run:()=>Promise.resolve(Af(t.errorMessage))},{name:`hooks-guard`,run:()=>Bf(n,r,t.config)},{name:`dirty-checkouts`,run:()=>Uf(n,r,t.config)},{name:`orphans`,run:()=>Xf(r,t.config,i)},{name:`skill`,run:()=>mp(n)},{name:`cli-update`,run:()=>Nf(n,t.config)},{name:`ssh-auth`,run:()=>Np(n,t.config)}]},Lp=async e=>{let t=H(e.env),n=await kf(t),r=await Wf(t);return Fp(Ip({configLoad:n,ctx:e,home:t,state:r}))},Rp={fail:`FAIL`,ok:`OK`,warn:`WARN`},zp=e=>e.map(e=>`[${Rp[e.status]}] ${e.name}: ${e.detail}`),Bp=e=>e.some(e=>e.status===`fail`),Vp=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, ssh).`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await Lp(t);Q(t,r,zp(e),{checks:e}),Bp(e)&&(process.exitCode=_.UNEXPECTED)})()})},Hp=async e=>{let t=H(e.env),n=await J(t,`home`,()=>vc(t,Qd));return n===`migrated`?{backup:Xs(t),result:n}:{backup:null,result:n}},Up=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${ee(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,Wp=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await Hp(t);Q(t,r,Up(e),e)})()})},Gp=`never`,Kp=(e,t,n)=>e===void 0||n-Date.parse(e)>t,qp=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,Jp=(e,t)=>{if(e===void 0)return Gp;let n=t-Date.parse(e);if(Number.isNaN(n))return Gp;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return qp(i,`minute`);let a=Math.floor(i/60);if(a<24)return qp(a,`hour`);let o=Math.floor(a/24);return o<365?qp(o,`day`):qp(Math.floor(o/365),`year`)},Yp=e=>{let t=Jp(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==Gp&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},Xp=(e,t,n)=>{let r=e.state.refs[t],i=is(Y(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:Y(`clone_mode`,n,e.settings),description:n.description,key:t,...r?.last_fetched_at===void 0?{}:{last_fetched_at:r.last_fetched_at},missing:!G(U(e.home,z.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:Kp(r?.last_fetched_at,i,e.now)}},Zp=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])=>Xp(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},Qp=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=await X(r);return Zp({config:i,home:r,includePackages:t,now:n,state:a})},$p=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...Yp({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],em=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...$p(n,t)),e),[]),tm=e=>e.split(`/`),nm=(e,t)=>{let n=tm(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},rm=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=tm(t),r=Object.keys(e.refs).filter(e=>nm(e,n)).toSorted(),[i]=r;if(i===void 0)throw y(`no ref matches '${t}'`);if(r.length>1)throw b(`'${t}' matches more than one ref: ${r.join(`, `)}`);return z.parse(i)},im=(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=Z(n);return $(t,r,async()=>{let n=Date.now(),i=await Qp(t,e.packages===!0,n);Q(t,r,em(i,n),i)})()})},am=e=>`ref.${e.replaceAll(`/`,`_`)}`,om=e=>e.REFS_ALLOW_FILE_URLS===`1`,sm=(e,t)=>{let n=Sl(t,{allowFileUrls:om(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},cm=async(e,t)=>{if(t===``)throw b(`refs add npm: requires a package name, e.g. npm:left-pad`);Sf(e,`resolving npm package '${t}'…`);let n=await Tu(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},lm=(e,t)=>t.startsWith(`npm:`)?cm(e,t.slice(4)):Promise.resolve(sm(e,t)),um=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Y(`git_transport`,void 0,t);return{...e,cloneUrl:Nl(e.cloneUrl,n)}},dm=e=>`ref '${e}' already exists — use refs edit or refs remove`,fm=(e,t)=>{if(e.refs[t]!==void 0)throw ve(dm(t))},pm=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},mm=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),hm=async(e,t)=>{let n=await pm(e);if(n===void 0)return{kind:`stop`};let r=mm(n);if(r.includes(t))return{kind:`continue`,nextDir:h(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},gm=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await hm(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):gm(a.nextDir,i,[...n,r])},_m=[],vm=async(e,t)=>{let n=await gm(e.sourcesDir,t.split(`/`),_m);if(n!==void 0)throw ve(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},ym=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},bm=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},xm=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},Sm=async e=>{let t=await bm(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await d(e)}catch(e){if(!V(e))throw e}return!0},Cm=async e=>{let t=await xm(e);return t===void 0?!0:t?Sm(e):!1},wm=async(e,t)=>{t!==e.sourcesDir&&await Cm(t)&&await wm(e,te(t))},Tm=async(e,t)=>await ym(t)?(ec(e,t),await u(t,{force:!0,recursive:!0}),await wm(e,te(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},Em=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),Dm=async(e,t)=>{let n=await W(e),r={...n,refs:Em(n.refs,t)};await cc(e,r);let i=await X(e),a={...i,refs:Em(i.refs,t)};await nd(e,a)},Om=async(e,t)=>{let n=H(e.env),r=await W(n),i=rm(r,t),a=U(n,i),{removedCheckout:o,warning:s}=await J(n,am(i),()=>Tm(n,a));return await J(n,`home`,()=>Dm(n,i)),{data:{key:i,removed_checkout:o},warnings:yf(s)}},km=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],Am=(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=Z(r);return $(t,i,async()=>{let{data:n,warnings:r}=await Om(t,e);Q(t,i,km(n),n,r)})()})},jm=(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},Mm=(e,t)=>{if(!G(e))throw y(`checkout for '${t}' is missing — run: refs sync ${t}`)},Nm=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw y(`no package '${n}' registered on ref '${t}'`);return r},Pm=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,Fm=/^[a-z][a-z0-9+.-]*:\/\//iu,Im=/^git@[^:/\s]+:[^\s]+$/u,Lm=e=>Fm.test(e)||Im.test(e),Rm=(e,t)=>{try{return Sl(e,t)}catch{if(Lm(e))throw x(`query looks like a git url but is not a supported form — check the url (credentials are never accepted) or run: refs resolve <package|ref-suffix>`);return}},zm=(e,t,n)=>{let r=Rm(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw y(Pm(t))}},Bm=(e,t)=>{let n=[];for(let r of Object.keys(e.refs).toSorted()){let i=e.refs[r]?.packages?.[t];i!==void 0&&n.push({entry:i,key:z.parse(r)})}return n},Vm=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,Hm=(e,t)=>{let n=Bm(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw b(Vm(t,n.map(e=>e.key)));return r}},Um=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=Hm(e,r);if(i!==void 0)return{...i,name:r}}},Wm=(e,t)=>{try{return rm(e,t)}catch(e){throw e instanceof v&&e.code===`not_found`?y(Pm(t)):e}},Gm=(e,t,n)=>{let r=zm(e,t,n);if(r!==void 0)return r;let i=Hm(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=Um(e,t);return a===void 0?{key:Wm(e,t)}:{key:a.key,packageMatch:a}},Km=(e,t)=>{if(e.packageMatch===void 0)return null;let{entry:n,name:r}=e.packageMatch;return{local_path:h(t,n.path),name:r,path:n.path}},qm=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=Gm(i,t,{allowFileUrls:om(e.env)}),o=jm(i,a.key),s=await X(r),c=U(r,a.key),l=is(Y(`sync_ttl`,o,i.settings)),u=s.refs[a.key]?.last_fetched_at;return{key:a.key,...u===void 0?{}:{last_fetched_at:u},local_path:c,missing:!G(c),package:Km(a,c),stale:Kp(u,l,n)}},Jm=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...Yp({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})];return e.package!==null&&n.push(`package: ${e.package.name}`,`package path: ${e.package.local_path}`),n},Ym=(e,t)=>{e.command(`resolve`).description(`Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.`).argument(`<query>`,`git url, npm package name, import path, or unique ref-key suffix`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let n=Date.now(),r=await qm(t,e,n);Q(t,i,Jm(r,n),r)})()})},Xm={},Zm=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await Rc(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${bf(e)}`}}},Qm=async(e,t,n,r)=>{let i=H(e.env),a=await W(i),o=rm(a,t),s=jm(a,o),c=await X(i),l=U(i,o),{packages:u,...d}=s,f=n.tags?await Zm(e,l):void 0,p=c.refs[o]??Xm;return{data:{...d,key:o,local_path:l,missing:!G(l),...n.packages?{packages:u??{}}:{},packages_count:Object.keys(u??{}).length,...f===void 0?{}:{sample_tags:f.tags},stale:Kp(p.last_fetched_at,is(Y(`sync_ttl`,s,a.settings)),r),state:p},warnings:yf(f?.warning)}},$m=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...Yp({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},eh=(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=Z(r);return $(t,i,async()=>{let r={packages:n.packages===!0,tags:!i.json||n.tags===!0},a=Date.now(),{data:o,warnings:s}=await Qm(t,e,r,a);Q(t,i,$m(o,a),o,s)})()})},th=(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},nh=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await cc(e,r))},rh=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await nh(e,t,n.branchRenamedTo);let r=await X(e);r.refs[t]=th(r.refs[t],n),await nd(e,r)}),ih=async(e,t,n)=>{try{await J(e,`home`,async()=>{let r=await X(e);r.refs[t]={...r.refs[t],last_error:n},await nd(e,r)})}catch{}},ah=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()}}},oh=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},sh=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,ch=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,lh=(e,t)=>{try{return Sl(e,{allowFileUrls:t}).key}catch{return}},uh=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=ch(n),i=lh(t.expectedUrl,t.allowFileUrls),a=lh(r,t.allowFileUrls);if(i===void 0||a!==i)throw ve(sh(t.dest,r,t.expectedUrl))},dh=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,fh=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw ve(dh(t.dest))},ph=async(e,t)=>{await a(te(t.dest),{recursive:!0}),Sf(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await kc(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},mh=async(e,t)=>(ec(t.home,t.dest),G(t.dest)?(await uh(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await fh(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):ph(e,t)),hh=(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`,gh=(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`,_h=async(e,t)=>{await uh(e,t),await fh(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw x(hh(t.key,t.dest));let r=n.stdout.trim();if(!Qu.shape.head_sha.safeParse(r).success)throw x(gh(t.key,t.dest,r));return r},vh=(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`,yh=(e,t,n)=>{if(!Qu.shape.head_sha.safeParse(n).success)throw x(vh(e,t,n));return n},bh=(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},xh=async(e,t,n)=>{await a(te(n),{recursive:!0});let r=Y(`clone_mode`,t.ref,t.settings),i=await kc(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await jc(e.runner,n),s=await _h(e.runner,{allowFileUrls:om(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return bh(t,i,{actualBranch:o,headSha:s})},Sh=async(e,t,n)=>{await fh(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await uh(e.runner,{allowFileUrls:om(e.env),dest:n,expectedUrl:t.ref.url});let r=await Lc(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:yh(t.key,n,r.newSha),status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Ch=(e,t)=>J(t.home,am(t.key),()=>{let n=U(t.home,t.key);return ec(t.home,n),G(n)?Sh(e,t,n):xh(e,t,n)}),wh=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(` | `)},Th=(e,t)=>{let n={key:e,status:t.status},r=wh(t);return r!==void 0&&(n.warning=r),n},Eh=async(e,t)=>{try{let n=await Ch(e,t);return await rh(t.home,t.key,n),Th(t.key,n)}catch(e){let n=bf(e);return await ih(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},Dh=(e,t)=>e.status===`rejected`?{error:bf(e.reason),key:t,status:`failed`}:e.value,Oh=async(e,t)=>{let n=ah(4);return(await Promise.allSettled(t.map(t=>oh(n,()=>Eh(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return Dh(e,r.key)})},kh=(e,t,n)=>({home:e,key:n,ref:jm(t,n),settings:t.settings}),Ah=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>kh(e,t,z.parse(n))):n.map(n=>kh(e,t,rm(t,n))),jh=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=is(Y(`sync_ttl`,t.ref,t.settings)),a=Kp(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},Mh=async(e,t,n)=>{if(!xd({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await pd({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!md(e.cliVersion,r)?[]:[hd(e.cliVersion,r)]},Nh=async(e,t,n)=>{if(!n)return t;let r=await X(e);return jh(e,t,r)},Ph=async(e,t)=>{let n=H(e.env),r=await W(n),i=Ah(n,r,t.refs),a=await Nh(n,i,t.staleOnly),[o,s]=await Promise.all([Oh(e,a),a.length>0?Mh(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},Fh=[`updated`,`fresh`,`cloned`,`restored`,`failed`],Ih={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},Lh=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},Rh=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,zh=e=>{let t=Lh(e),n=[Fh.map(e=>`${Ih[e]} (${t[e].length})`).join(` / `)];for(let e of Fh)for(let r of t[e])n.push(Rh(r));return n},Bh=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),Vh=(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=Z(r);return $(t,i,async()=>{let r=await Ph(t,Bh(e,n));Q(t,i,zh(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=_.UNEXPECTED)})()})},Hh=(e,t,n)=>n===void 0?e.tag_format:Nm(e,t,n).tag_format??e.tag_format,Uh=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,Wh=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?``:` --package ${Uh(n)}`;throw x(`${r} has no tag_format configured — inspect the repository's real tags and set one with: refs edit ${Uh(t)} tag_format '<format>'${i}`)},Gh=async(e,t)=>{let n=H(e.env),r=await W(n),i=rm(r,t.query),a=jm(r,i),o=Wh(Hh(a,i,t.opts.packageName),i,t.opts.packageName),s=U(n,i);Mm(s,i);let c=await $c(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},Kh=e=>[`${e.key}@${e.version} -> ${e.tag}`],qh=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Jh=[Vp,Wp,Am,Ym,eh,Vh,(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=Z(i);return $(t,a,async()=>{let i=await Gh(t,{opts:qh(r),query:e,version:n});Q(t,a,Kh(i),i)})()})}],Yh=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},Xh=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,Yh(e)])):n===void 0?{}:{[n]:{path:t??`.`}},Zh=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}},Qh=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,Zh(t)]))},$h=e=>e.description===void 0||e.description===``,eg=e=>Object.entries(e).filter(([,e])=>$h(e)).map(([e])=>e).toSorted(),tg=e=>{let t=eg(e);if(t.length!==0)throw x(`packages without a detected description: ${t.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},ng=e=>{if(Object.keys(e).length!==0)return e},rg=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},ig=async(e,t,n)=>{let r=await jc(e.runner,t),i=await Rc(e.runner,t),a=Zc(i);Sf(e,`detecting workspace packages…`);let o=await Zd(t);return{defaultBranch:r,packages:Xh(o,n.npmDirectory,n.npmPkgName),tagFormatCandidate:a}},ag=(e,t)=>J(t.home,am(t.resolved.key),async()=>{let n=await mh(e,{allowFileUrls:om(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await ig(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),og=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},sg=async(e,t)=>{let n=H(e.env),r=await W(n),i=um(await lm(e,t),r.settings);fm(r,i.key),await vm(n,i.key);let a=U(n,i.key),o=Y(`clone_mode`,void 0,r.settings),s=await ag(e,{cloneMode:o,dest:a,home:n,resolved:i});return og({cloneResult:s,dest:a,resolved:i})},cg=(e,t,n)=>J(e,`home`,async()=>{let r=await W(e);fm(r,t);let i=await X(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 nd(e,i)}),lg=(e,t)=>{let n=_s.safeParse(e);if(!n.success)throw x(O(n.error));let r=$u.safeParse(t);if(!r.success)throw x(O(r.error));return{config:n.data,state:r.data}},ug=async(e,t)=>{let n=await W(e.home);fm(n,e.ref.key);let r=rg(e.ref);n.refs[e.ref.key]=r;let i=await X(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Y(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...lg(n,i),entry:r}},dg=async(e,t)=>{let n=om(e.env),r=await J(t.home,am(t.ref.key),()=>(ec(t.home,t.dest),_h(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return J(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await ug(t,r);return await nd(t.home,i),await cc(t.home,e),{entry:n,key:t.ref.key}})},fg=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),pg=e=>{try{return JSON.parse(e)}catch(e){throw x(`invalid JSON in proposal: ${bf(e)}`)}},mg=e=>typeof e==`object`&&!!e&&!Array.isArray(e),hg=e=>mg(e)&&`ok`in e&&!(`key`in e),gg=e=>{if(!hg(e))return e;if(e.ok===!1)throw x(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(mg(e.data))return e.data;throw x(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},_g=e=>e.code===`unrecognized_keys`,vg=e=>e.path.length===0,yg=(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}`},bg=e=>{let t=new Map;for(let n of e){let e=lt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>yg(e,t))},xg=e=>`✖ invalid proposal: ${e.message}`,Sg=e=>{let t=e.issues.filter(e=>_g(e)),n=e.issues.filter(e=>!_g(e)),r=n.filter(e=>vg(e));if(t.length===0&&r.length===0)return O(e);let i=n.filter(e=>!vg(e)),a=[...bg(t),...r.map(e=>xg(e))];return i.length>0&&a.push(O({issues:i})),a.join(`
369
- `)},Cg=e=>{let t=Zu.safeParse(e);if(!t.success)throw x(Sg(t.error));return t.data},wg=async(e,t)=>{let n=await fg(e,t);return Cg(gg(pg(n)))},Tg=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],Eg=async(e,t)=>{let n=await sg(e,t),r=H(e.env);await cg(r,n.proposal.key,n.effectiveCloneMode);let i=yf(n.warning);return{data:n.proposal,human:Tg(n.proposal.key,n.dest),warnings:i}},Dg=e=>[`refs add: '${e}' added to config`],Og=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=ng(e.packages);return n!==void 0&&(t.packages=n),t},kg=async(e,t)=>{let n=await wg(e,t),r=H(e.env),i=U(r,n.key);if(!G(i))throw y(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=Og(n),{entry:o,key:s}=await dg(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:Dg(s),warnings:[]}},Ag=(e,t)=>{tg(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(n.tag_format=e.proposal.tag_format_candidate);let r=Qh(e.proposal.packages);return r!==void 0&&(n.packages=r),n},jg=async(e,t,n)=>{let r=await sg(e,t),i=H(e.env),a=Ag(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await dg(e,o),l=yf(r.warning);return{data:{entry:s,key:c},human:Dg(c),warnings:l}},Mg=e=>{let t=[e.dryRun,e.proposal!==void 0,e.description!==void 0].filter(Boolean).length;if(t>1)throw b(`refs add: use only one of --dry-run, --proposal, or --description`);if(t===0)throw b(`refs add needs --dry-run, --proposal, or --description`)},Ng=e=>{if(e===void 0||e===``)throw b(`refs add requires <source> (a git url or npm:<package>)`);return e},Pg=(e,t)=>(Mg(t),t.proposal===void 0?t.description===void 0?Eg(e,Ng(t.source)):jg(e,Ng(t.source),t.description):kg(e,t.proposal)),Fg=(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},Ig=(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=Z(r);return $(t,i,async()=>{let r=await Pg(t,Fg(e,n));Q(t,i,r.human,r.data,r.warnings)})()})},Lg=e=>e===void 0?null:e,Rg=()=>Object.keys(fs.shape).toSorted().join(`, `),zg=e=>`unknown package field '${e}' — valid fields: ${Rg()}`,Bg=e=>Object.hasOwn(fs.shape,e),Vg=(e,t,n)=>{if(!Bg(t))throw b(zg(t));let r=e[t],i=fs.safeParse({...e,[t]:n});if(!i.success)throw x(O(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},Hg=async e=>{let t=Nm(e.entry,e.key,e.packageName),n=Vg(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await cc(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:Lg(n.newValue),old:Lg(n.oldValue)}},Ug=`packages`,Wg=()=>Object.keys(ps.shape).filter(e=>e!==Ug).toSorted().join(`, `),Gg=e=>`unknown ref field '${e}' — valid fields: ${Wg()}`,Kg=e=>Object.hasOwn(ps.shape,e),qg=(e,t,n)=>`failed to rewrite git remote at ${e} to '${q(t)}': ${n.trim()}`,Jg=async(e,t)=>{if(ec(t.home,t.dest),!G(t.dest))return;let n=await e.runner.run(`git`,[`remote`,`set-url`,`--`,`origin`,t.cloneUrl],{cwd:t.dest});if(n.exitCode!==0)throw x(qg(t.dest,t.cloneUrl,n.stderr))},Yg=async(e,t)=>{let n=Sl(t.value,{allowFileUrls:om(e.env)});if(n.key!==t.key)throw x(`new url derives a different key — remove and re-add instead`);let r=U(t.home,t.key);return await Jg(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},Xg=(e,t,n)=>{let r={...e,[t]:n},i=ps.safeParse(r);if(!i.success)throw x(O(i.error));return i.data},Zg=(e,t)=>t.field===`url`?Yg(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(Xg(t.entry,t.field,t.value)),Qg=async(e,t)=>{let{field:n}=t;if(n===Ug)throw b(`use --package <name> <field> <value>`);if(!Kg(n))throw b(Gg(n));let r=t.entry[n],i=await Zg(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},$g=(e,t)=>{let n=H(e.env),{field:r,opts:i,query:a,value:o}=t;return J(n,`home`,async()=>{let t=await W(n),s=rm(t,a),c=jm(t,s);if(i.packageName!==void 0)return Hg({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await Qg(e,{entry:c,field:r,home:n,key:s,value:o});return await cc(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:Lg(l.new),old:Lg(l.old)}})},e_=`settings`,t_=[],n_=()=>Object.keys(us.shape).toSorted().join(`, `),r_=e=>`unknown setting '${e}' — valid settings: ${n_()}`,i_=e=>Object.hasOwn(us.shape,e),a_=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,o_=e=>{try{let t=rm(e,e_);return[a_(`ref '${t}'`)]}catch(e){if(e instanceof v&&e.code===`usage`)return[a_("one of several matching refs — see `refs list`")];if(e instanceof v&&e.code===`not_found`)return t_;throw e}},s_=e=>({data:{field:e.key,key:e_,new:Lg(e.parsed[e.key]),old:Lg(e.old)},warnings:o_(e.config)}),c_=(e,t)=>{let n=H(e.env);return J(n,`home`,async()=>{let e=await W(n);if(!i_(t.key))throw b(r_(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=us.safeParse(i);if(!a.success)throw x(O(a.error));return await cc(n,{...e,settings:a.data}),s_({config:e,key:t.key,old:r,parsed:a.data})})},l_=[],u_=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},d_=async(e,t)=>{if(t.first===`settings`){if(t.opts.packageName!==void 0)throw b(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return c_(e,{key:t.second,value:t.value})}return{data:await $g(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:l_}},f_=e=>e==null?`(unset)`:String(e),p_=e=>[`${e.key}: ${e.field} '${f_(e.old)}' -> '${f_(e.new)}'`],m_=(e,t)=>{e.command(`edit`).description(`Edit one field: 'refs edit settings <key> <value>' for a global setting, or 'refs edit <ref> <field> <value> [--package <name>]' for a ref or package field.`).argument(`<ref-or-settings>`,`a ref key/unique suffix, or the literal 'settings'`).argument(`<field-or-key>`,`field to edit (or, in settings mode, the setting key)`).argument(`<value>`,`the new value`).option(`--package <name>`,`edit this package's field instead of a top-level ref field`).action((e,n,r,i,a)=>{let o=Z(a);return $(t,o,async()=>{let{data:a,warnings:s}=await d_(t,{first:e,opts:u_(i),second:n,value:r});Q(t,o,p_(a),a,s)})()})},h_=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,g_={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},__=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})},v_=async e=>{let t=H(e.env);return await __(t),{config:await J(t,`home`,async()=>{let e=await vc(t,Qd);return await Vc(t),e}),home:t.root,skill_hint:h_}},y_=[(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=Z(n);return $(t,r,async()=>{let e=await v_(t);Q(t,r,[`home: ${e.home}`,`config: ${g_[e.config]}`,``,h_],e)})()})},Ig,m_,im,...Jh],b_=(e,t)=>{for(let n of y_)n(e,t)},x_=[``,`Examples:`,` $ refs list --json`,` $ refs sync --stale-only --json`,` $ refs resolve zod/mini --json`,``,`Every command accepts --json for structured output and --verbose for stack traces on error.`].join(`
370
- `),S_=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),C_=`--json`,w_=`--verbose`,T_=/\n$/u,E_=/^error: /u,D_=e=>e.replace(E_,``),O_=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},k_=e=>O_(e,C_),A_=e=>O_(e,w_),j_=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,M_=e=>{let t=new mf().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(Qd).option(C_,`emit machine-readable JSON on stdout instead of human-readable text`).option(w_,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(T_,``))},writeOut:t=>{e.out(t.replace(T_,``))}});return t.addHelpText(`after`,x_),b_(t,e),t},N_=()=>{process.exitCode=_.OK},P_=(e,t,n)=>{let r={code:`usage`,message:j_(D_(n.message),n.stack,t.verbose)};xf(e,t,r),process.exitCode=_.USAGE},F_=(e,t,n)=>{if(S_.has(n.code)){N_();return}P_(e,t,n)},I_=(e,t,n)=>{let r=be(n,{verbose:t.verbose});xf(e,t,r),process.exitCode=r.exitCode},L_=async(e,t,n)=>{let r={json:k_(n),verbose:A_(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof nf){F_(e,r,t);return}I_(e,r,t)}},R_=(e,t)=>L_(e,M_(e),t);import.meta.main&&await R_(tf(),process.argv);export{M_ as buildProgram,Z as cliOptsOf,Q as emit,xf as emitError,bf as errorMessageOf,Sf as progress,tf as realContext,b_ as registerCommands,R_ as run,L_ as runProgram,yf as warningsFor,$ as wrapAction};
338
+ - ${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(de.existsSync(r))return r;if(n.includes(ne.extname(t)))return;let i=n.find(e=>de.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=de.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=Lm(h.execArgv).concat(t),s=ve.spawn(h.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=Lm(h.execArgv).concat(t),s=ve.spawn(h.argv[0],t,{stdio:`inherit`})):s=ve.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 Tm(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 Tm(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(`
339
+ `),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 jm(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=Fm(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=Fm(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=>Om(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.
340
+ 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 Lm(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 Rm(){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 Im;const zm=[],Bm=e=>Array.isArray(e)?e:[e],Vm=e=>e===void 0?zm:[e],Hm=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??zm};e.out(JSON.stringify(t));return}for(let t of Bm(n))e.out(t);for(let t of i??zm)e.errLine(`refs: warning: ${t}`)},Um=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},Wm=(e,t)=>{e.errLine(`refs: ${t}`)},Q=(e,t,n)=>async()=>{try{await n()}catch(n){let r=Ce(n,{verbose:t.verbose});Um(e,t,r),process.exitCode=r.exitCode}},Gm=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},Km=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,Gm(e)])):n===void 0?{}:{[n]:{path:t??`.`}},qm=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}},Jm=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,qm(t)]))},Ym=e=>e.description===void 0||e.description===``,Xm=e=>Object.entries(e).filter(([,e])=>Ym(e)).map(([e])=>e).toSorted(),Zm=e=>{let t=Xm(e);if(t.length!==0)throw b(`packages without a detected description: ${t.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},Qm=e=>{if(Object.keys(e).length!==0)return e},$m=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},eh=e=>`ref.${e.replaceAll(`/`,`_`)}`,th=e=>e.REFS_ALLOW_FILE_URLS===`1`,nh=(e,t)=>{let n=q(t,{allowFileUrls:th(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},rh=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);Wm(e,`resolving npm package '${t}'…`);let n=await Ef(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},ih=(e,t)=>t.startsWith(`npm:`)?rh(e,t.slice(4)):Promise.resolve(nh(e,t)),ah=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=jp(`git_transport`,void 0,t);return{...e,cloneUrl:td(e.cloneUrl,n)}},oh=e=>`ref '${e}' already exists — use refs edit or refs remove`,sh=(e,t)=>{if(e.refs[t]!==void 0)throw xe(oh(t))},ch=async e=>{try{return await c(e,{withFileTypes:!0})}catch(e){if(B(e))return;throw e}},lh=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),uh=async(e,t)=>{let n=await ch(e);if(n===void 0)return{kind:`stop`};let r=lh(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}},dh=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await uh(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):dh(a.nextDir,i,[...n,r])},fh=[],ph=async(e,t)=>{let n=await dh(e.sourcesDir,t.split(`/`),fh);if(n!==void 0)throw xe(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},mh=e=>`'${e.replaceAll(`'`,String.raw`'\''`)}'`,hh=e=>`rm -rf -- ${mh(e)}`,gh=(e,t,n)=>`checkout at ${e} points at '${K(t)}' — expected '${K(n)}'; remove the checkout directory or run refs remove before retrying`,_h=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,vh=(e,t)=>{try{return q(e,{allowFileUrls:t}).key}catch{return}},yh=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=_h(n),i=vh(t.expectedUrl,t.allowFileUrls),a=vh(r,t.allowFileUrls);if(i===void 0||a!==i)throw xe(gh(t.dest,r,t.expectedUrl))},bh=e=>`checkout at ${e} exists but is not refs-managed — remove it (${hh(e)}) and retry`,xh=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 xe(bh(t.dest))},Sh=async(e,t)=>{await a(ie(t.dest),{recursive:!0}),Wm(e,`cloning ${K(t.cloneUrl)} into ${t.dest}…`);let n=await Ql(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},Ch=async(e,t)=>(_l(t.home,t.dest),W(t.dest)?(await yh(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await xh(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Sh(e,t)),wh=(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`,Th=(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`,Eh=async(e,t)=>{await yh(e,t),await xh(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(wh(t.key,t.dest));let r=n.stdout.trim();if(!kp.shape.head_sha.safeParse(r).success)throw b(Th(t.key,t.dest,r));return r},Dh=async(e,t,n)=>{let r=await eu(e.runner,t),i=await su(e.runner,t),a=bu(i);Wm(e,`detecting workspace packages…`);let o=await bm(t);return{defaultBranch:r,packages:Km(o,n.npmDirectory,n.npmPkgName),tagFormatCandidate:a}},Oh=(e,t)=>J(t.home,eh(t.resolved.key),async()=>{let n=await Ch(e,{allowFileUrls:th(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await Dh(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),kh=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},Ah=async(e,t)=>{let n=V(e.env),r=await U(n),i=ah(await ih(e,t),r.settings);sh(r,i.key),await ph(n,i.key);let a=H(n,i.key),o=jp(`clone_mode`,void 0,r.settings),s=await Oh(e,{cloneMode:o,dest:a,home:n,resolved:i});return kh({cloneResult:s,dest:a,resolved:i})},jh=(e,t,n)=>J(e,`home`,async()=>{let r=await U(e);sh(r,t);let i=await Y(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 Pp(e,i)}),Mh=(e,t)=>{let n=Nc.safeParse(e);if(!n.success)throw b(D(n.error));let r=Ap.safeParse(t);if(!r.success)throw b(D(r.error));return{config:n.data,state:r.data}},Nh=async(e,t)=>{let n=await U(e.home);sh(n,e.ref.key);let r=$m(e.ref);n.refs[e.ref.key]=r;let i=await Y(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??jp(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...Mh(n,i),entry:r}},Ph=async(e,t)=>{let n=th(e.env),r=await J(t.home,eh(t.ref.key),()=>(_l(t.home,t.dest),Eh(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return J(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await Nh(t,r);return await Pp(t.home,i),await Tl(t.home,e),{entry:n,key:t.ref.key}})},Fh=(e,t)=>t===`-`?e.readStdin():s(t,`utf8`),Ih=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${Hm(e)}`)}},Lh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Rh=e=>Lh(e)&&`ok`in e&&!(`key`in e),zh=e=>{if(!Rh(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(Lh(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},Bh=e=>e.code===`unrecognized_keys`,Vh=e=>e.path.length===0,Hh=(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}`},Uh=e=>{let t=new Map;for(let n of e){let e=Lt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Hh(e,t))},Wh=e=>`✖ invalid proposal: ${e.message}`,Gh=e=>{let t=e.issues.filter(e=>Bh(e)),n=e.issues.filter(e=>!Bh(e)),r=n.filter(e=>Vh(e));if(t.length===0&&r.length===0)return D(e);let i=n.filter(e=>!Vh(e)),a=[...Uh(t),...r.map(e=>Wh(e))];return i.length>0&&a.push(D({issues:i})),a.join(`
341
+ `)},Kh=e=>{let t=Op.safeParse(e);if(!t.success)throw b(Gh(t.error));return t.data},qh=async(e,t)=>{let n=await Fh(e,t);return Kh(zh(Ih(n)))},Jh=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],Yh=async(e,t)=>{let n=await Ah(e,t),r=V(e.env);await jh(r,n.proposal.key,n.effectiveCloneMode);let i=Vm(n.warning);return{data:n.proposal,human:Jh(n.proposal.key,n.dest),warnings:i}},Xh=e=>[`refs add: '${e}' added to config`],Zh=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=Qm(e.packages);return n!==void 0&&(t.packages=n),t},Qh=async(e,t)=>{let n=await qh(e,t),r=V(e.env),i=H(r,n.key);if(!W(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let a=Zh(n),{entry:o,key:s}=await Ph(e,{dest:i,home:r,ref:a});return{data:{entry:o,key:s},human:Xh(s),warnings:[]}},$h=(e,t)=>{Zm(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,url:e.proposal.url};e.proposal.tag_format_candidate!==null&&(n.tag_format=e.proposal.tag_format_candidate);let r=Jm(e.proposal.packages);return r!==void 0&&(n.packages=r),n},eg=async(e,t,n)=>{let r=await Ah(e,t),i=V(e.env),a=$h(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await Ph(e,o),l=Vm(r.warning);return{data:{entry:s,key:c},human:Xh(c),warnings:l}},tg=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`)},ng=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},rg=(e,t)=>(tg(t),t.proposal===void 0?t.description===void 0?Yh(e,ng(t.source)):eg(e,ng(t.source),t.description):Qh(e,t.proposal)),ig=(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},ag=(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 rg(t,ig(e,n));Z(t,i,r.human,r.data,r.warnings)})()})},og=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`}},sg=/^v(?<major>\d+)\.(?<minor>\d+)/u,cg=e=>{let t=sg.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},lg=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,ug=e=>{let{nodeVersion:t}=e;return lg(cg(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},dg=()=>Nc.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),fg=async e=>{try{return{config:await U(e)}}catch(e){return{config:dg(),errorMessage:Hm(e)}}},pg=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},mg={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)`},hg=(e,t,n)=>{if(Kp(e,t)){let r=n?` (npm was unreachable just now; this was its last answer)`:``;return{detail:`${qp(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`}},gg=async(e,t)=>{let n=Zp({env:e.env,updates:t.updates});if(n!==`on`)return{detail:mg[n],name:`cli-update`,status:`ok`};let{latest:r,stale:i}=await Gp({fetch:e.fetcher,home:V(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`}:hg(e.cliVersion,r,i)},_g=(e,t)=>Object.keys(t.refs).map(e=>R.parse(e)).map(t=>({dest:H(e,t),key:t})).filter(e=>W(e.dest)),vg=[`pre-commit`,`pre-push`],yg=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},bg=async e=>{let t=await Promise.all(vg.map(t=>yg(e,t)));return vg.filter((e,n)=>!t[n])},xg=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},Sg=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:`${vg.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},Cg=async(e,t,n)=>{let r=_g(t,n),[i,a]=await Promise.all([bg(t),Promise.all(r.map(n=>xg(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return Sg({badKeys:o,checkoutCount:r.length,missingHooks:i})},wg=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}},Tg=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`}},Eg=async(e,t,n)=>{let r=_g(t,n),i=await Promise.all(r.map(t=>wg(e,t)));return Tg(i)},Dg=async e=>{try{return await Y(e)}catch{return Ap.parse({})}},Og=async e=>{try{return(await c(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(B(e))return[];throw e}},kg=async(e,t)=>{if(W(e))return[[...t]];let n=await Og(e);return(await Promise.all(n.map(n=>kg(m(e,n),[...t,n])))).flat()},Ag=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},jg=(e,t,n)=>Ag(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: ${hh(e.dest)}`,Mg=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),Ng=async(e,t,n)=>{let r=(await kg(e.sourcesDir,[])).map(t=>Mg(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=>jg(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},Pg=(e,t)=>({path:e.configuredPath,reason:t,status:`unverifiable`}),Fg=(e,t)=>Lf(t)?{configuredPath:e.configuredPath,path:null,status:`missing`}:Pg(e,`this repo declares no workspaces, so there was nowhere to search`),Ig=(e,t)=>t===e.configuredPath,Lg=(e,t)=>{let n=np(t.packages,e.packageName);return n.kind===`ambiguous`?{candidates:n.paths,configuredPath:e.configuredPath,path:null,status:`ambiguous`}:If(t)?n.kind===`absent`?Fg(e,t):Ig(e,n.path)?Pg(e,`the checkout changed while it was being inspected`):{configuredPath:e.configuredPath,path:n.path,status:`relocated`}:Pg(e,n.kind===`found`?`workspace detection was incomplete, so the new location is not confirmed unique`:`workspace detection was incomplete`)},Rg=e=>e!==`unmaterialized`&&e!==`verified`,zg=new Set([`ambiguous`,`missing`,`relocated`]),Bg=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}]})},Vg=async(e,t)=>{let n=await $f(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`}},Hg=e=>e.flatMap(e=>e.settled===void 0?[]:[{outcome:e.settled,query:e.query}]),Ug=async(e,t)=>{let n=await Promise.all(t.map(async t=>({query:t,settled:await Vg(e,t)})));if(n.every(e=>e.settled!==void 0))return Hg(n);let r=await ym(e);return n.map(e=>({outcome:e.settled??Lg(e.query,r),query:e.query}))},Wg=e=>{let{outcome:t,query:n}=e;return Rg(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}]:[]},Gg=e=>{let[t]=e;return t===void 0?{status:`ok`}:{packages:[...e],status:e.some(e=>zg.has(e.status))?`drift`:`unknown`}},Kg=async(e,t)=>{let n=Bg(t),[r]=n;if(r===void 0)return{status:`ok`};try{let t=await Ug(e,n);return Gg(t.flatMap(e=>Wg(e)))}catch(e){return{reason:Hm(e),status:`unknown`}}},qg=e=>{let t=`configured: ${e.configured_path}`;if(e.status===`relocated`)return`${e.name}: moved to ${e.path??`(unknown)`} — 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})`},Jg=e=>e.reason===void 0?(e.packages??[]).map(e=>qg(e)):[`could not be checked — ${e.reason}`],Yg=async(e,t,n)=>{try{return await J(e,eh(n.key),()=>Kg(n.dest,t.refs[n.key]?.packages),{timeoutMs:100})}catch(e){if(e instanceof _&&e.code===`conflict`)return{reason:`another refs process is holding this ref`,status:`unknown`};throw e}},Xg=`config-drift`,Zg=(e,t)=>{let[n]=e;return n===void 0?{detail:`every configured package path resolves in ${t} checkout(s)`,name:Xg,status:`ok`}:{detail:e.join(`; `),name:Xg,status:`warn`}},Qg=async(e,t,n)=>{let[r,...i]=n;if(r===void 0)return[];let a=await Yg(e,t,r),o=await Qg(e,t,i);return[...Jg(a).map(e=>`${r.key}: ${e}`),...o]},$g=async(e,t)=>{let n=_g(e,t);return Zg(await Qg(e,t,n),n.length)},e_=e=>{let{diagnosis:t}=e;return!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},t_=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`:`, ${Ad(t)} into a ${Ad(n)} window`},n_=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`,r_=e=>{let{diagnosis:t}=e,n=e.isDirectory?``:`not a directory, `,r=t.stale?`, reclaimable now`:``;return`${e.name}: ${n}${n_(t)}${t_(t)}${r}`},i_=async e=>{let t=await Hd(e),[n]=t;return n===void 0?{detail:`no locks held`,name:`locks`,status:`ok`}:{detail:t.map(e=>r_(e)).join(`; `),name:`locks`,status:t.every(e=>e_(e))?`ok`:`warn`}},a_=[`.agents`,`skills`,`refs`,`SKILL.md`],o_=[`skills`,`refs`,`SKILL.md`],s_=[`.claude`,`skills`,`refs`,`SKILL.md`],c_=`npx skills add kaisers-io/refs`,l_=`npm i -g @kaisers-io/refs@latest`,u_=(e,t)=>e===void 0?void 0:{display:t,path:e},d_=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}:u_(r===void 0?void 0:m(r,t),`~/${t}`)},f_=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:u_(t,`~/.agents`),segments:a_},{label:`Claude Code`,root:d_({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:o_},{label:`Codex`,root:d_({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:o_},{label:`project ./.agents`,root:u_(e.cwd,`./.agents`),segments:a_},{label:`project ./.claude`,root:u_(e.cwd,`./.claude`),segments:s_}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:m(t.path,...n)}])},p_=async(e,t)=>{try{let n=await l(e);return{label:t,realPath:n,source:await s(n,`utf8`)}}catch{return}},m_=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},h_=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,g_=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,__=e=>{let t=h_.exec(e)?.groups?.body;if(t!==void 0)return g_.exec(t)?.groups?.version},v_=(e,t)=>{if(e===t)return`match`;let n=Rp(e,t);return n===void 0?`unknown`:n===0?`match`:n>0?`cli-older`:`skill-older`},y_={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${l_}`,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: ${c_}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${l_} and ${c_}`},b_=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: ${c_}`,name:`skill`,status:`warn`};let i=v_(r,t);return{detail:`${n}: ${y_[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},x_=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: ${c_}`,name:`skill`,status:`warn`}),S_=async e=>{let t=f_(e),n=await Promise.all(t.map(e=>p_(e.path,e.label))),r=m_(n.filter(e=>e!==void 0)).map(t=>b_({cliVersion:e.cliVersion,label:t.label,skillVersion:__(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??x_(t)},C_=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,w_=e=>e===``?{}:{user:e},T_=e=>e===``?{}:{port:e},E_=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...w_(t.username),...T_(t.port)}:void 0}catch{return}},D_=e=>{let t=C_.exec(e),n=t?.groups?.host;return n===void 0?E_(e):{host:n,user:t?.groups?.user??`git`}},O_=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,k_=e=>e.user===void 0?O_(e):`${e.user}@${O_(e)}`,A_=e=>{let t=Object.values(e.refs).map(e=>D_(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(k_(e),e);return[...n.values()].toSorted((e,t)=>k_(e).localeCompare(k_(t)))},j_=/Permission denied/u,M_=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],N_=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,P_=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=N_(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},F_=async(e,t,n)=>{let r=k_(t),i=await e.runner.run(`ssh`,P_(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:j_.test(i.stderr)?{host:r,outcome:`denied`}:M_.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},I_=(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`}},L_=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`}},R_=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`}},z_=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),B_=(e,t)=>I_(e,t)??L_(e)??R_(e)??z_(e),V_=async(e,t,n)=>{let r=A_(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>F_(e,t,i)));return B_(a,i)},H_=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${Hm(t)}`,name:e.name,status:`fail`}}},U_=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await H_(t),i=await U_(n);return r===void 0?i:[r,...i]},W_=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>og(n)},{name:`node`,run:()=>Promise.resolve(ug(n))},{name:`config`,run:()=>Promise.resolve(pg(t.errorMessage))},{name:`hooks-guard`,run:()=>Cg(n,r,t.config)},{name:`dirty-checkouts`,run:()=>Eg(n,r,t.config)},{name:`config-drift`,run:()=>$g(r,t.config)},{name:`orphans`,run:()=>Ng(r,t.config,i)},{name:`locks`,run:()=>i_(r)},{name:`skill`,run:()=>S_(n)},{name:`cli-update`,run:()=>gg(n,t.config)},{name:`ssh-auth`,run:()=>V_(n,t.config)}]},G_=async e=>{let t=V(e.env),n=await fg(t),r=await Dg(t);return U_(W_({configLoad:n,ctx:e,home:t,state:r}))},K_={fail:`FAIL`,ok:`OK`,warn:`WARN`},q_=e=>e.map(e=>`[${K_[e.status]}] ${e.name}: ${e.detail}`),J_=e=>e.some(e=>e.status===`fail`),Y_=(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 G_(t);Z(t,r,q_(e),{checks:e}),J_(e)&&(process.exitCode=g.UNEXPECTED)})()})},X_=e=>e===void 0?null:e,Z_=(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},Q_=(e,t)=>{if(!W(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},$_=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},ev=()=>Object.keys(Oc.shape).toSorted().join(`, `),tv=e=>`unknown package field '${e}' — valid fields: ${ev()}`,nv=e=>Object.hasOwn(Oc.shape,e),rv=(e,t,n)=>{if(!nv(t))throw y(tv(t));let r=e[t],i=Oc.safeParse({...e,[t]:n});if(!i.success)throw b(D(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},iv=async e=>{let t=$_(e.entry,e.key,e.packageName),n=rv(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await Tl(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:X_(n.newValue),old:X_(n.oldValue)}},av=`never`,ov=(e,t,n)=>e===void 0||n-Date.parse(e)>t,sv=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,cv=(e,t)=>{if(e===void 0)return av;let n=t-Date.parse(e);if(Number.isNaN(n))return av;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return sv(i,`minute`);let a=Math.floor(i/60);if(a<24)return sv(a,`hour`);let o=Math.floor(a/24);return o<365?sv(o,`day`):sv(Math.floor(o/365),`year`)},lv=e=>{let t=cv(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==av&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},uv=(e,t,n)=>{let r=e.state.refs[t],i=bc(jp(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:jp(`clone_mode`,n,e.settings),description:n.description,key:t,...r?.last_fetched_at===void 0?{}:{last_fetched_at:r.last_fetched_at},missing:!W(H(e.home,R.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:ov(r?.last_fetched_at,i,e.now)}},dv=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])=>uv(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},fv=async(e,t,n)=>{let r=V(e.env),i=await U(r),a=await Y(r);return dv({config:i,home:r,includePackages:t,now:n,state:a})},pv=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...lv({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],mv=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...pv(n,t)),e),[]),hv=e=>e.split(`/`),gv=(e,t)=>{let n=hv(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},_v=(e,t)=>{if(Object.hasOwn(e.refs,t))return R.parse(t);let n=hv(t),r=Object.keys(e.refs).filter(e=>gv(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 R.parse(i)},vv=(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 fv(t,e.packages===!0,n);Z(t,r,mv(i,n),i)})()})},yv=`packages`,bv=()=>Object.keys(kc.shape).filter(e=>e!==yv).toSorted().join(`, `),xv=e=>`unknown ref field '${e}' — valid fields: ${bv()}`,Sv=e=>Object.hasOwn(kc.shape,e),Cv=(e,t,n)=>`failed to rewrite git remote at ${e} to '${K(t)}': ${n.trim()}`,wv=async(e,t)=>{if(_l(t.home,t.dest),!W(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(Cv(t.dest,t.cloneUrl,n.stderr))},Tv=async(e,t)=>{let n=q(t.value,{allowFileUrls:th(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=H(t.home,t.key);return await wv(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},Ev=(e,t,n)=>{let r={...e,[t]:n},i=kc.safeParse(r);if(!i.success)throw b(D(i.error));return i.data},Dv=(e,t)=>t.field===`url`?Tv(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(Ev(t.entry,t.field,t.value)),Ov=async(e,t)=>{let{field:n}=t;if(n===yv)throw y(`use --package <name> <field> <value>`);if(!Sv(n))throw y(xv(n));let r=t.entry[n],i=await Dv(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},kv=(e,t)=>{let n=V(e.env),{field:r,opts:i,query:a,value:o}=t;return J(n,`home`,async()=>{let t=await U(n),s=_v(t,a),c=Z_(t,s);if(i.packageName!==void 0)return iv({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await Ov(e,{entry:c,field:r,home:n,key:s,value:o});return await Tl(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:X_(l.new),old:X_(l.old)}})},Av=`settings`,jv=[],Mv=()=>Object.keys(Ec.shape).toSorted().join(`, `),Nv=e=>`unknown setting '${e}' — valid settings: ${Mv()}`,Pv=e=>Object.hasOwn(Ec.shape,e),Fv=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,Iv=e=>{try{let t=_v(e,Av);return[Fv(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[Fv("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return jv;throw e}},Lv=e=>({data:{field:e.key,key:Av,new:X_(e.parsed[e.key]),old:X_(e.old)},warnings:Iv(e.config)}),Rv=(e,t)=>{let n=V(e.env);return J(n,`home`,async()=>{let e=await U(n);if(!Pv(t.key))throw y(Nv(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=Ec.safeParse(i);if(!a.success)throw b(D(a.error));return await Tl(n,{...e,settings:a.data}),Lv({config:e,key:t.key,old:r,parsed:a.data})})},zv=[],Bv=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Vv=async(e,t)=>{if(t.first===`settings`){if(t.opts.packageName!==void 0)throw y(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return Rv(e,{key:t.second,value:t.value})}return{data:await kv(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:zv}},Hv=e=>e==null?`(unset)`:String(e),Uv=e=>[`${e.key}: ${e.field} '${Hv(e.old)}' -> '${Hv(e.new)}'`],Wv=(e,t)=>{e.command(`edit`).description(`Edit one field: 'refs edit settings <key> <value>' for a global setting, or 'refs edit <ref> <field> <value> [--package <name>]' for a ref or package field.`).argument(`<ref-or-settings>`,`a ref key/unique suffix, or the literal 'settings'`).argument(`<field-or-key>`,`field to edit (or, in settings mode, the setting key)`).argument(`<value>`,`the new value`).option(`--package <name>`,`edit this package's field instead of a top-level ref field`).action((e,n,r,i,a)=>{let o=X(a);return Q(t,o,async()=>{let{data:a,warnings:s}=await Vv(t,{first:e,opts:Bv(i),second:n,value:r});Z(t,o,Uv(a),a,s)})()})},Gv=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,Kv={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},qv=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})},Jv=async e=>{let t=V(e.env);return await qv(t),{config:await J(t,`home`,async()=>{let e=await Fl(t,xm);return await uu(t),e}),home:t.root,skill_hint:Gv}},Yv=(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 Jv(t);Z(t,r,[`home: ${e.home}`,`config: ${Kv[e.config]}`,``,Gv],e)})()})},Xv=async e=>{let t=V(e.env),n=await J(t,`home`,()=>Fl(t,xm));return n===`migrated`?{backup:pl(t),result:n}:{backup:null,result:n}},Zv=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${re(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,Qv=(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 Xv(t);Z(t,r,Zv(e),e)})()})},$v=async e=>{try{return await i(e),!0}catch(e){if(B(e))return!1;throw e}},ey=async e=>{try{return await c(e)}catch(e){if(B(e))return;throw e}},ty=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(B(e))return;throw e}},ny=async e=>{let t=await ey(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await f(e)}catch(e){if(!B(e))throw e}return!0},ry=async e=>{let t=await ty(e);return t===void 0?!0:t?ny(e):!1},iy=async(e,t)=>{t!==e.sourcesDir&&await ry(t)&&await iy(e,ie(t))},ay=async(e,t)=>await $v(t)?(_l(e,t),await d(t,{force:!0,recursive:!0}),await iy(e,ie(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},oy=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),sy=async(e,t)=>{let n=await U(e),r={...n,refs:oy(n.refs,t)};await Tl(e,r);let i=await Y(e),a={...i,refs:oy(i.refs,t)};await Pp(e,a)},cy=async(e,t)=>{let n=V(e.env),r=await U(n),i=_v(r,t),a=H(n,i),{removedCheckout:o,warning:s}=await J(n,eh(i),()=>ay(n,a));return await J(n,`home`,()=>sy(n,i)),{data:{key:i,removed_checkout:o},warnings:Vm(s)}},ly=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],uy=(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 cy(t,e);Z(t,i,ly(n),n,r)})()})},dy=async e=>{let t=await $f(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`}:fy(e)},fy=async e=>Lg(e,await ym(e.checkoutDir)),py=async e=>{try{return await J(e.home,eh(e.key),()=>dy(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}},my=async e=>{if(!W(e.checkoutDir))return{path:e.configuredPath,status:`unmaterialized`};let t=await $f(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?.(),py(e))},hy=(e,t)=>({local_path:null,name:e,path:null,reason:t,status:`unverifiable`}),gy=async e=>{if(!e.checkoutManaged)return hy(e.packageName,e.checkoutReason);let t=await my(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}},_y=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}`]],vy=`node_modules`,yy=[`.pnp.cjs`,`.pnp.js`],by=new Set([``,`.`,`..`]),xy=e=>!ae(e)&&!e.includes(`\\`)&&e.split(`/`).every(e=>!by.has(e)),Sy=function*(e){let t=ce(e);for(;;){re(t)!==vy&&(yield m(t,vy));let e=ie(t);if(e===t)return;t=e}},Cy=async e=>{if(await Ey(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`}}},wy=new Set([`ENOENT`,`ENOTDIR`]),Ty=async e=>{try{return(await c(e)).length===0}catch{return!1}},Ey=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&&wy.has(t)?`absent`:`unreadable`}},Dy=async e=>{for(let t of Sy(e)){let e=ie(t);if((await Promise.all(yy.map(t=>Ey(m(e,t))))).includes(`present`))return!0}return!1},Oy=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}`)}},ky=async e=>{let t=await Ey(e);if(t===`unreadable`)return{reason:`slot_unreadable`,status:`unverifiable`};if(t===`absent`)return;let n=await Cy(m(e,`package.json`));return n===void 0?await Ty(e)?void 0:{reason:`installed_without_manifest`,status:`unverifiable`}:n},Ay=async(e,t)=>{if(!xy(t))return{reason:`unsupported_package_name`,status:`unverifiable`};for(let n of Sy(e)){let e=await ky(m(n,...t.split(`/`)));if(e!==void 0)return e}return await Dy(e)?{reason:`yarn_pnp`,status:`unsupported_layout`}:{status:`not_materialized`}},jy={'"':`"`,"\\":`\\`,b:`\b`,n:`
342
+ `,t:` `},My={'"':`"`,"\\":`\\`},Ny=new Set([` `,` `]),$=Symbol(`malformed git config`),Py=e=>e!==void 0&&!e.quoted&&Ny.has(e.char),Fy=e=>{let t=0,n=e.length;for(;t<n&&Py(e[t]);)t+=1;for(;n>t&&Py(e[n-1]);)--n;return e.slice(t,n).map(e=>e.char).join(``)},Iy=e=>{let t=[],n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`\\`){r+=1;let n=jy[e[r]??``];if(n===void 0)return $;t.push({char:n,quoted:!0})}else if(i===`"`)n=!n;else if(!n&&(i===`#`||i===`;`))return Fy(t);else t.push({char:i??``,quoted:n})}return n?$:Fy(t)},Ly=e=>{let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`\\`){n+=1;let r=My[e[n]??``];if(r===void 0)return $;t+=r}else t+=r??``}return t},Ry=/^[ \t]+|[ \t]+$/gu,zy=e=>e.replace(Ry,``),By=/^\[[ \t]*(?<section>[A-Za-z0-9.-]+)[ \t]*(?:"(?<subsection>(?:[^"\\]|\\.)*)")?[ \t]*\]/u,Vy=/^(?<name>[A-Za-z][A-Za-z0-9-]*)[ \t]*(?:=[ \t]*(?<value>.*))?$/u,Hy=function*(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(a===`
343
+ `)yield t,t=``,n=!1,r=!1;else if(a!==`\r`||e[i+1]!==`
344
+ `){if(r)t+=a;else if(a===`\\`){let n=e[i+1];n===`
345
+ `||n===`\r`&&e[i+2]===`
346
+ `?i+=n===`\r`?2:1:(t+=a+(n??``),i+=1)}else a===`"`?n=!n:!n&&(a===`#`||a===`;`)&&(r=!0),t+=a}}t!==``&&(yield t)},Uy=(e,t)=>e.subsection===void 0?`${e.name}.${t.toLowerCase()}`:`${e.name}.${e.subsection}.${t.toLowerCase()}`,Wy=(e,t)=>{let n=e.toLowerCase();if(t===void 0)return{name:n};let r=Ly(t);return r===$?$:{name:n,subsection:r}},Gy=e=>{let t=By.exec(e),n=t?.groups?.section;if(n===void 0)return;let r=zy(e.slice(t?.[0].length??0)),i=Wy(n,t?.groups?.subsection);return i===$?$:{rest:r,section:i}},Ky=e=>e===``||e.startsWith(`#`)||e.startsWith(`;`),qy=e=>{let t=Vy.exec(e),n=t?.groups?.name;if(n===void 0)return $;let r=Iy(t?.groups?.value??``);return r===$?$:{name:n,value:r}},Jy=(e,t)=>{let n=qy(t.line);if(n===$)return`malformed`;let r=Uy(t.section,n.name);return t.wanted.includes(r)&&e.set(r,[...e.get(r)??[],n.value]),`ok`},Yy=(e,t,n)=>t.rest===``||Ky(t.rest)?t.section:Jy(e,{line:t.rest,section:t.section,wanted:n})===`malformed`?$:t.section,Xy=(e,t)=>{let n=Gy(t.line);return n===$?$:n===void 0?t.section===Zy||Jy(e,t)===`malformed`?$:t.section:Yy(e,n,t.wanted)},Zy={name:``},Qy=(e,t)=>{let n=new Map,r=Zy;for(let i of Hy(e)){let e=zy(i),a=Ky(e)?r:Xy(n,{line:e,section:r,wanted:t});if(a===$)return;r=a}return n},$y=`core.hookspath`,eb=`remote.origin.url`,tb=[$y,eb],nb={status:`managed`},rb={status:`missing`},ib=e=>({reason:e,status:`unmanaged`}),ab=e=>({reason:e,status:`unverifiable`}),ob=new Set([`ENOENT`,`ENOTDIR`]),sb=e=>typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?e.code:void 0,cb=async e=>{try{return await i(e),`present`}catch(e){let t=sb(e);return t!==void 0&&ob.has(t)?`absent`:`unreadable`}},lb=async e=>{try{let t=await i(m(e,`.git`));return t.isSymbolicLink()?ib(`git_is_symlink`):t.isDirectory()?void 0:ib(`git_is_file`)}catch(e){let t=sb(e);return t!==void 0&&ob.has(t)?ib(`no_git`):ab(`git_unreadable`)}},ub=(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},db=(e,t,n)=>{try{return q(e,{allowFileUrls:n}).key===q(t,{allowFileUrls:n}).key}catch{return!1}},fb=e=>(e.get($y)?.length??0)>1||(e.get(eb)?.length??0)>1,pb=(e,t)=>{let n=Qy(e,tb);return n===void 0?ab(`config_malformed`):fb(n)?ab(`duplicate_config_values`):mb(n,t)},mb=(e,t)=>{if(ub(e,$y)!==t.hooksDir)return ib(`no_refs_marker`);let n=ub(e,eb);return n===void 0?ib(`no_origin`):db(n,t.expectedUrl,t.allowFileUrls)?nb:ib(`origin_mismatch`)},hb={missing:rb,outside:ib(`outside_sources`),unreadable:ab(`path_unreadable`)},gb=async e=>{let t=await Vl(e.sourcesDir,e.dest);if(t.kind!==`inside`)return t.kind===`unreadable`?await cb(e.sourcesDir)===`absent`?rb:hb.unreadable:hb[t.kind]},_b=async e=>{let t=await gb(e);if(t!==void 0)return t;let n=await lb(e.dest);if(n!==void 0)return n;try{return pb(await s(m(e.dest,`.git`,`config`),`utf8`),e)}catch{return ab(`config_unreadable`)}},vb=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,yb=/^[a-z][a-z0-9+.-]*:\/\//iu,bb=/^git@[^:/\s]+:[^\s]+$/u,xb=e=>yb.test(e)||bb.test(e),Sb=(e,t)=>{try{return q(e,t)}catch{if(xb(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}},Cb=(e,t,n)=>{let r=Sb(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(vb(t))}},wb=(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:R.parse(r)})}return n},Tb=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — pick one with: refs resolve ${e} --ref <ref>`,Eb=(e,t)=>{let n=wb(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(Tb(t,n.map(e=>e.key)));return r}},Db=function*(e){let t=e.split(`/`);for(let e=t.length-1;e>=1;--e)yield t.slice(0,e).join(`/`)},Ob=(e,t)=>{for(let n of Db(t)){let t=Eb(e,n);if(t!==void 0)return{...t,name:n}}},kb=(e,t)=>{try{return _v(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(vb(t)):e}},Ab=(e,t)=>{let n=e[t];if(n!==void 0)return{entry:n,name:t};for(let n of Db(t)){let t=e[n];if(t!==void 0)return{entry:t,name:n}}},jb=(e,t,n)=>{let r=kb(e,n),i=Ab(e.refs[r]?.packages??{},t);if(i===void 0)throw v(xb(t)?`ref '${r}' registers no package matching that query — run: refs show ${r} --json`:`ref '${r}' registers no package matching '${t}' — run: refs show ${r} --json`);return{key:r,packageMatch:{...i,key:r}}},Mb=(e,t,n)=>{let r=Cb(e,t,n);if(r!==void 0)return r;let i=Eb(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=Ob(e,t);return a===void 0?{key:kb(e,t)}:{key:a.key,packageMatch:a}},Nb=(e,t,n)=>n.ref===void 0?Mb(e,t,n):jb(e,t,n.ref),Pb=(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},Fb=async(e,t,n)=>{let r=await U(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await Tl(e,r))},Ib=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Fb(e,t,n.branchRenamedTo);let r=await Y(e);r.refs[t]=Pb(r.refs[t],n),await Pp(e,r)}),Lb=async(e,t,n)=>{try{await J(e,`home`,async()=>{let r=await Y(e);r.refs[t]={...r.refs[t],last_error:n},await Pp(e,r)})}catch{}},Rb=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()}}},zb=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Bb=(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`,Vb=(e,t,n)=>{if(!kp.shape.head_sha.safeParse(n).success)throw b(Bb(e,t,n));return n},Hb=(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},Ub=async(e,t,n)=>{await a(ie(n),{recursive:!0});let r=jp(`clone_mode`,t.ref,t.settings),i=await Ql(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await eu(e.runner,n),s=await Eh(e.runner,{allowFileUrls:th(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return Hb(t,i,{actualBranch:o,headSha:s})},Wb=async(e,t,n)=>{await xh(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await yh(e.runner,{allowFileUrls:th(e.env),dest:n,expectedUrl:t.ref.url});let r=await ou(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Vb(t.key,n,r.newSha),status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Gb=(e,t,n)=>(_l(t.home,n),W(n)?Wb(e,t,n):Ub(e,t,n)),Kb=(e,t)=>J(t.home,eh(t.key),async()=>{let n=H(t.home,t.key);return{...await Gb(e,t,n),structure:await Kg(n,t.ref.packages)}}),qb=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(` | `)},Jb=(e,t)=>{let n={key:e,status:t.status},r=qb(t);return r!==void 0&&(n.warning=r),t.structure!==void 0&&(n.structure=t.structure),n},Yb=async(e,t)=>{try{let n=await Kb(e,t);return await Ib(t.home,t.key,n),n}catch(e){throw await Lb(t.home,t.key,Hm(e)),e}},Xb=async(e,t)=>{try{return Jb(t.key,await Yb(e,t))}catch(e){return{error:Hm(e),key:t.key,status:`failed`}}},Zb=(e,t)=>e.status===`rejected`?{error:Hm(e.reason),key:t,status:`failed`}:e.value,Qb=async(e,t)=>{let n=Rb(4);return(await Promise.allSettled(t.map(t=>zb(n,()=>Xb(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return Zb(e,r.key)})},$b=async e=>{let{packageMatch:t}=e.match;return t===void 0?null:await gy({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})},ex=(e,t,n)=>Nb(t,n.query,{allowFileUrls:th(e.env),...n.ref===void 0?{}:{ref:n.ref}}),tx=async(e,t)=>{let n=V(e.env),r=await U(n);return{config:r,home:n,match:ex(e,r,t),state:await Y(n)}},nx=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 Ay(t,n.name)},rx=(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`)},ix=async(e,t)=>(await Yb(e,{home:t.home,key:t.match.key,ref:Z_(t.config,t.match.key),settings:t.config.settings})).status,ax=async(e,t)=>{t.project!==void 0&&await Oy(t.project);let n=await tx(e,t),r=await sx(e,n,t);return t.syncIfStale!==!0||!(r.stale||r.missing)?r:(rx(r.checkout,r.key),await ox(e,{key:r.key,opts:t,target:n}))},ox=async(e,t)=>{let{key:n,opts:r}=t,i=await ix(e,t.target),a=await tx(e,r);if(a.match.key!==n)throw xe(`configuration changed while resolving '${r.query}' — retry`);return{...await sx(e,a,r),sync:{status:i}}},sx=async(e,t,n)=>{let{config:r,home:i,match:a,state:o}=t,{now:s}=n,c=Z_(r,a.key),l=H(i,a.key),u=bc(jp(`sync_ttl`,c,r.settings)),d=o.refs[a.key]?.last_fetched_at,f=await _b({allowFileUrls:th(e.env),dest:l,expectedUrl:c.url,hooksDir:i.hooksDir,sourcesDir:i.sourcesDir}),p=await nx(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 $b({checkout:f,dest:l,home:i,match:a}),stale:ov(d,u,s)}},cx=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...lv({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(..._y(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},lx=(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}:{}}),ux=(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 ax(t,lx(e,r,n));Z(t,i,cx(a,r),a)})()})},dx={},fx=async(e,t)=>{if(!W(t))return{tags:[]};try{return{tags:await su(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${Hm(e)}`}}},px=async(e,t,n,r)=>{let i=V(e.env),a=await U(i),o=_v(a,t),s=Z_(a,o),c=await Y(i),l=H(i,o),{packages:u,...d}=s,f=n.tags?await fx(e,l):void 0,p=c.refs[o]??dx;return{data:{...d,key:o,local_path:l,missing:!W(l),...n.packages?{packages:u??{}}:{},packages_count:Object.keys(u??{}).length,...f===void 0?{}:{sample_tags:f.tags},stale:ov(p.last_fetched_at,bc(jp(`sync_ttl`,s,a.settings)),r),state:p},warnings:Vm(f?.warning)}},mx=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...lv({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},hx=(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 px(t,e,r,a);Z(t,i,mx(o,a),o,s)})()})},gx=(e,t,n)=>({home:e,key:n,ref:Z_(t,n),settings:t.settings}),_x=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>gx(e,t,R.parse(n))):n.map(n=>gx(e,t,_v(t,n))),vx=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=bc(jp(`sync_ttl`,t.ref,t.settings)),a=ov(n.refs[t.key]?.last_fetched_at,i,r),o=!W(H(e,t.key));return a||o})},yx=async(e,t,n)=>{if(!$p({env:e.env,updates:n.updates}))return[];let{latest:r,refreshed:i}=await Gp({fetch:e.fetcher,home:t,nowMs:Date.now()});return!i||r===void 0||!Kp(e.cliVersion,r)?[]:[qp(e.cliVersion,r)]},bx=async(e,t,n)=>{if(!n)return t;let r=await Y(e);return vx(e,t,r)},xx=async(e,t)=>{let n=V(e.env),r=await U(n),i=_x(n,r,t.refs),a=await bx(n,i,t.staleOnly),[o,s]=await Promise.all([Qb(e,a),a.length>0?yx(e,n,r):Promise.resolve([])]);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o,warnings:s}},Sx=[`updated`,`fresh`,`cloned`,`restored`,`failed`],Cx={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},wx=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},Tx=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,...Jg(e.structure).map(e=>` ${e}`)]},Ex=e=>{let t=wx(e),n=[Sx.map(e=>`${Cx[e]} (${t[e].length})`).join(` / `)];for(let e of Sx)for(let r of t[e])n.push(...Tx(r));return n},Dx=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),Ox=(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 xx(t,Dx(e,n));Z(t,i,Ex(r.results),{results:r.results},r.warnings),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},kx=(e,t,n)=>n===void 0?e.tag_format:$_(e,t,n).tag_format??e.tag_format,Ax=(e,t,n)=>{if(e!==void 0)return e;let r=n===void 0?`ref '${t}'`:`package '${n}'`,i=n===void 0?``:` --package ${mh(n)}`;throw b(`${r} has no tag_format configured — inspect the repository's real tags and set one with: refs edit ${mh(t)} tag_format '<format>'${i}`)},jx=async(e,t)=>{let n=V(e.env),r=await U(n),i=_v(r,t.query),a=Z_(r,i),o=Ax(kx(a,i,t.opts.packageName),i,t.opts.packageName),s=H(n,i);Q_(s,i);let c=await Su(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},Mx=e=>[`${e.key}@${e.version} -> ${e.tag}`],Nx=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Px=[Yv,ag,Wv,vv,Y_,Qv,uy,ux,hx,Ox,(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 jx(t,{opts:Nx(r),query:e,version:n});Z(t,a,Mx(i),i)})()})}],Fx=(e,t)=>{for(let n of Px)n(e,t)},Ix=[``,`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(`
347
+ `),Lx=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),Rx=`--json`,zx=`--verbose`,Bx=/\n$/u,Vx=/^error: /u,Hx=e=>e.replace(Vx,``),Ux=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},Wx=e=>Ux(e,Rx),Gx=e=>Ux(e,zx),Kx=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,qx=e=>{let t=new Im().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(xm).option(Rx,`emit machine-readable JSON on stdout instead of human-readable text`).option(zx,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(Bx,``))},writeOut:t=>{e.out(t.replace(Bx,``))}});return t.addHelpText(`after`,Ix),Fx(t,e),t},Jx=()=>{process.exitCode=g.OK},Yx=(e,t,n)=>{let r={code:`usage`,message:Kx(Hx(n.message),n.stack,t.verbose)};Um(e,t,r),process.exitCode=g.USAGE},Xx=(e,t,n)=>{if(Lx.has(n.code)){Jx();return}Yx(e,t,n)},Zx=(e,t,n)=>{let r=Ce(n,{verbose:t.verbose});Um(e,t,r),process.exitCode=r.exitCode},Qx=async(e,t,n)=>{let r={json:Wx(n),verbose:Gx(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof Tm){Xx(e,r,t);return}Zx(e,r,t)}},$x=(e,t)=>Qx(e,qx(e),t);import.meta.main&&await $x(wm(),process.argv);export{qx as buildProgram,X as cliOptsOf,Z as emit,Um as emitError,Hm as errorMessageOf,Wm as progress,wm as realContext,Fx as registerCommands,$x as run,Qx as runProgram,Vm as warningsFor,Q as wrapAction};