@kaisers-io/refs 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/refs.mjs CHANGED
@@ -1,8 +1,8 @@
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 E(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function D(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 Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Ue={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function We(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 E(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 Ge(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 E(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 Ke(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 E(e,T(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function qe(e,t){if(!Re(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return E(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(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return E(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 Ye(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 E(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 Xe(e,t,n){return E(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 Ze(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 Qe(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 $e(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function et(e){return typeof e==`string`?e:e?.message}function O(e,t,n){let r=e.message?e.message:et(e.inst?._zod.def?.error?.(e))??et(t?.error?.(e))??et(n.customError?.(e))??et(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 tt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function nt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const rt=(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})},it=S(`$ZodError`,rt),at=S(`$ZodError`,rt,{Parent:Error});function ot(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 st(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 ct(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 k(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 ${ct(e.path)}`);return t.join(`
3
- `)}const lt=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=>O(e,a,C())));throw Fe(t,i?.callee),t}return o.value},ut=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=>O(e,a,C())));throw Fe(t,i?.callee),t}return o.value},dt=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??it)(a.issues.map(e=>O(e,i,C())))}:{success:!0,data:a.value}},ft=dt(at),pt=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=>O(e,i,C())))}:{success:!0,data:a.value}},mt=pt(at),ht=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return lt(e)(t,n,i)},gt=e=>(t,n,r)=>lt(e)(t,n,r),_t=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ut(e)(t,n,i)},vt=e=>async(t,n,r)=>ut(e)(t,n,r),yt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return dt(e)(t,n,i)},bt=e=>(t,n,r)=>dt(e)(t,n,r),xt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return pt(e)(t,n,i)},St=e=>async(t,n,r)=>pt(e)(t,n,r),Ct=/^[cC][0-9a-z]{6,}$/,wt=/^[0-9a-z]+$/,Tt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Et=/^[0-9a-vA-V]{20}$/,Dt=/^[A-Za-z0-9]{27}$/,Ot=/^[a-zA-Z0-9_-]{21}$/,kt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,At=/^([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})$/,jt=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)$/,Mt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Nt(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const Pt=/^(?:(?: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])$/,Ft=/^(([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}|:))$/,It=/^((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])$/,Lt=/^(([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])$/,Rt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zt=/^[A-Za-z0-9_-]*$/,Bt=/^https?$/,Vt=/^\+[1-9]\d{6,14}$/,Ht=`(?:(?:\\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])))`,Ut=RegExp(`^${Ht}$`);function Wt(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 Gt(e){return RegExp(`^${Wt(e)}$`)}function Kt(e){let t=Wt({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(`^${Ht}T(?:${r})$`)}const qt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Jt=/^-?\d+$/,Yt=/^-?\d+(?:\.\d+)?$/,Xt=/^[^A-Z]*$/,Zt=/^[^a-z]*$/,A=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Qt={number:`number`,bigint:`bigint`,object:`date`},$t=S(`$ZodCheckLessThan`,(e,t)=>{A.init(e,t);let n=Qt[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})}}),en=S(`$ZodCheckGreaterThan`,(e,t)=>{A.init(e,t);let n=Qt[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})}}),tn=S(`$ZodCheckMultipleOf`,(e,t)=>{A.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})}}),nn=S(`$ZodCheckNumberFormat`,(e,t)=>{A.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ue[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=Jt)}),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=S(`$ZodCheckMaxLength`,(e,t)=>{var n;A.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=tt(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),an=S(`$ZodCheckMinLength`,(e,t)=>{var n;A.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=tt(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),on=S(`$ZodCheckLengthEquals`,(e,t)=>{var n;A.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=tt(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})}}),sn=S(`$ZodCheckStringFormat`,(e,t)=>{var n,r;A.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=()=>{})}),cn=S(`$ZodCheckRegex`,(e,t)=>{sn.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})}}),ln=S(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Xt,sn.init(e,t)}),un=S(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Zt,sn.init(e,t)}),dn=S(`$ZodCheckIncludes`,(e,t)=>{A.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})}}),fn=S(`$ZodCheckStartsWith`,(e,t)=>{A.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})}}),pn=S(`$ZodCheckEndsWith`,(e,t)=>{A.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})}}),mn=S(`$ZodCheckOverwrite`,(e,t)=>{A.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var hn=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(`
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 Ne(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Pe(e){return JSON.stringify(e)}function Fe(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Ie=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Le(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Re=De(()=>{if(we.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function ze(e){if(Le(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Le(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Be(e){return ze(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Ve=new Set([`string`,`number`,`symbol`]);function He(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function T(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 T(e,Ne(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 T(e,Ne(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(!ze(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 T(e,Ne(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function Je(e,t){if(!ze(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return T(e,Ne(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 T(e,Ne(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 T(t,Ne(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 T(t,Ne(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 Ie(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 Ie(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=/^[^A-Z]*$/,Qt=/^[^a-z]*$/,k=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),$t={number:`number`,bigint:`bigint`,object:`date`},en=S(`$ZodCheckLessThan`,(e,t)=>{k.init(e,t);let n=$t[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})}}),tn=S(`$ZodCheckGreaterThan`,(e,t)=>{k.init(e,t);let n=$t[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})}}),nn=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})}}),rn=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})}}),an=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})}}),on=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})}}),sn=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})}}),cn=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=()=>{})}),ln=S(`$ZodCheckRegex`,(e,t)=>{cn.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=S(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Zt,cn.init(e,t)}),dn=S(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Qt,cn.init(e,t)}),fn=S(`$ZodCheckIncludes`,(e,t)=>{k.init(e,t);let n=He(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})}}),pn=S(`$ZodCheckStartsWith`,(e,t)=>{k.init(e,t);let n=RegExp(`^${He(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})}}),mn=S(`$ZodCheckEndsWith`,(e,t)=>{k.init(e,t);let n=RegExp(`.*${He(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})}}),hn=S(`$ZodCheckOverwrite`,(e,t)=>{k.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var gn=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
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 gn={major:4,minor:4,patch:3},j=S(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=gn;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=Ze(e),i;for(let a of t){if(a._zod.def.when){if(Qe(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||=Ze(e,t))});else{if(e.issues.length===t)continue;r||=Ze(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Ze(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=ft(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return mt(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),_n=S(`$ZodString`,(e,t)=>{j.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??qt(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}}),M=S(`$ZodStringFormat`,(e,t)=>{sn.init(e,t),_n.init(e,t)}),vn=S(`$ZodGUID`,(e,t)=>{t.pattern??=At,M.init(e,t)}),yn=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??=jt(e)}else t.pattern??=jt();M.init(e,t)}),bn=S(`$ZodEmail`,(e,t)=>{t.pattern??=Mt,M.init(e,t)}),xn=S(`$ZodURL`,(e,t)=>{M.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Bt.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})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Sn=S(`$ZodEmoji`,(e,t)=>{t.pattern??=Nt(),M.init(e,t)}),Cn=S(`$ZodNanoID`,(e,t)=>{t.pattern??=Ot,M.init(e,t)}),wn=S(`$ZodCUID`,(e,t)=>{t.pattern??=Ct,M.init(e,t)}),Tn=S(`$ZodCUID2`,(e,t)=>{t.pattern??=wt,M.init(e,t)}),En=S(`$ZodULID`,(e,t)=>{t.pattern??=Tt,M.init(e,t)}),Dn=S(`$ZodXID`,(e,t)=>{t.pattern??=Et,M.init(e,t)}),On=S(`$ZodKSUID`,(e,t)=>{t.pattern??=Dt,M.init(e,t)}),kn=S(`$ZodISODateTime`,(e,t)=>{t.pattern??=Kt(t),M.init(e,t)}),An=S(`$ZodISODate`,(e,t)=>{t.pattern??=Ut,M.init(e,t)}),jn=S(`$ZodISOTime`,(e,t)=>{t.pattern??=Gt(t),M.init(e,t)}),Mn=S(`$ZodISODuration`,(e,t)=>{t.pattern??=kt,M.init(e,t)}),Nn=S(`$ZodIPv4`,(e,t)=>{t.pattern??=Pt,M.init(e,t),e._zod.bag.format=`ipv4`}),Pn=S(`$ZodIPv6`,(e,t)=>{t.pattern??=Ft,M.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})}}}),Fn=S(`$ZodCIDRv4`,(e,t)=>{t.pattern??=It,M.init(e,t)}),In=S(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Lt,M.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 Ln(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Rn=S(`$ZodBase64`,(e,t)=>{t.pattern??=Rt,M.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Ln(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function zn(e){if(!zt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Ln(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Bn=S(`$ZodBase64URL`,(e,t)=>{t.pattern??=zt,M.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{zn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Vn=S(`$ZodE164`,(e,t)=>{t.pattern??=Vt,M.init(e,t)});function Hn(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 Un=S(`$ZodJWT`,(e,t)=>{M.init(e,t),e._zod.check=n=>{Hn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Wn=S(`$ZodNumber`,(e,t)=>{j.init(e,t),e._zod.pattern=e._zod.bag.pattern??Yt,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}}),Gn=S(`$ZodNumberFormat`,(e,t)=>{nn.init(e,t),Wn.init(e,t)}),Kn=S(`$ZodUnknown`,(e,t)=>{j.init(e,t),e._zod.parse=e=>e}),qn=S(`$ZodNever`,(e,t)=>{j.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Jn(e,t,n){e.issues.length&&t.issues.push(...$e(n,e.issues)),t.value[n]=e.value}const Yn=S(`$ZodArray`,(e,t)=>{j.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=>Jn(t,n,e))):Jn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Xn(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...$e(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 Zn(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=He(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Qn(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=>Xn(e,n,i,t,u,d))):Xn(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 $n=S(`$ZodObject`,(e,t)=>{if(j.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(()=>Zn(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=>Xn(n,t,e,s,r,i))):Xn(a,t,e,s,r,i)}return i?Qn(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),er=S(`$ZodObjectJIT`,(e,t)=>{$n.init(e,t);let n=e._zod.parse,r=De(()=>Zn(t)),i=e=>{let t=new hn([`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(`
5
+ `))}};const _n={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=_n;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}))}),vn=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)=>{cn.init(e,t),vn.init(e,t)}),yn=S(`$ZodGUID`,(e,t)=>{t.pattern??=jt,j.init(e,t)}),bn=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)}),xn=S(`$ZodEmail`,(e,t)=>{t.pattern??=Nt,j.init(e,t)}),Sn=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})}}}),Cn=S(`$ZodEmoji`,(e,t)=>{t.pattern??=Pt(),j.init(e,t)}),wn=S(`$ZodNanoID`,(e,t)=>{t.pattern??=kt,j.init(e,t)}),Tn=S(`$ZodCUID`,(e,t)=>{t.pattern??=wt,j.init(e,t)}),En=S(`$ZodCUID2`,(e,t)=>{t.pattern??=Tt,j.init(e,t)}),Dn=S(`$ZodULID`,(e,t)=>{t.pattern??=Et,j.init(e,t)}),On=S(`$ZodXID`,(e,t)=>{t.pattern??=Dt,j.init(e,t)}),kn=S(`$ZodKSUID`,(e,t)=>{t.pattern??=Ot,j.init(e,t)}),An=S(`$ZodISODateTime`,(e,t)=>{t.pattern??=qt(t),j.init(e,t)}),jn=S(`$ZodISODate`,(e,t)=>{t.pattern??=Wt,j.init(e,t)}),Mn=S(`$ZodISOTime`,(e,t)=>{t.pattern??=Kt(t),j.init(e,t)}),Nn=S(`$ZodISODuration`,(e,t)=>{t.pattern??=At,j.init(e,t)}),Pn=S(`$ZodIPv4`,(e,t)=>{t.pattern??=Ft,j.init(e,t),e._zod.bag.format=`ipv4`}),Fn=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})}}}),In=S(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Lt,j.init(e,t)}),Ln=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 Rn(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const zn=S(`$ZodBase64`,(e,t)=>{t.pattern??=zt,j.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Rn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Bn(e){if(!Bt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Rn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Vn=S(`$ZodBase64URL`,(e,t)=>{t.pattern??=Bt,j.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Bn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Hn=S(`$ZodE164`,(e,t)=>{t.pattern??=Ht,j.init(e,t)});function Un(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 Wn=S(`$ZodJWT`,(e,t)=>{j.init(e,t),e._zod.check=n=>{Un(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Gn=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}}),Kn=S(`$ZodNumberFormat`,(e,t)=>{rn.init(e,t),Gn.init(e,t)}),qn=S(`$ZodUnknown`,(e,t)=>{A.init(e,t),e._zod.parse=e=>e}),Jn=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 Yn(e,t,n){e.issues.length&&t.issues.push(...et(n,e.issues)),t.value[n]=e.value}const Xn=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=>Yn(t,n,e))):Yn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Zn(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 Qn(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 $n(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=>Zn(e,n,i,t,u,d))):Zn(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 er=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(()=>Qn(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=Le,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=>Zn(n,t,e,s,r,i))):Zn(a,t,e,s,r,i)}return i?$n(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),tr=S(`$ZodObjectJIT`,(e,t)=>{er.init(e,t);let n=e._zod.parse,r=De(()=>Qn(t)),i=e=>{let t=new gn([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Pe(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=Pe(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
6
  if (${n}.issues.length) {
7
7
  if (${o} in input) {
8
8
  payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
@@ -61,9 +61,9 @@ import{access as e,chmod as t,constants as n,copyFile as r,lstat as i,mkdir as a
61
61
  }
62
62
  }
63
63
 
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?Qn([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function tr(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=>!Ze(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=>O(e,r,C())))}),t)}const nr=S(`$ZodUnion`,(e,t)=>{j.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=>tr(t,r,e,i)):tr(o,r,e,i)}}),rr=S(`$ZodIntersection`,(e,t)=>{j.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])=>ar(e,t,n)):ar(e,i,a)}});function ir(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=ir(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=ir(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 ar(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}),Ze(e))return e;let o=ir(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const or=S(`$ZodRecord`,(e,t)=>{j.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=>O(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(...$e(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...$e(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`&&Yt.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=>O(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(...$e(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...$e(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),sr=S(`$ZodEnum`,(e,t)=>{j.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}}),cr=S(`$ZodTransform`,(e,t)=>{j.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 lr(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const ur=S(`$ZodOptional`,(e,t)=>{j.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=>lr(e,r)):lr(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),dr=S(`$ZodExactOptional`,(e,t)=>{ur.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)}),fr=S(`$ZodNullable`,(e,t)=>{j.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)}),pr=S(`$ZodDefault`,(e,t)=>{j.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=>mr(e,t)):mr(r,t)}});function mr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const hr=S(`$ZodPrefault`,(e,t)=>{j.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))}),gr=S(`$ZodNonOptional`,(e,t)=>{j.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=>_r(t,e)):_r(i,e)}});function _r(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 vr=S(`$ZodCatch`,(e,t)=>{j.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=>O(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=>O(e,n,C()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),yr=S(`$ZodPipe`,(e,t)=>{j.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=>br(e,t.in,n)):br(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>br(e,t.out,n)):br(r,t.out,n)}});function br(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 xr=S(`$ZodPreprocess`,(e,t)=>{yr.init(e,t)}),Sr=S(`$ZodReadonly`,(e,t)=>{j.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(Cr):Cr(r)}});function Cr(e){return e.value=Object.freeze(e.value),e}const wr=S(`$ZodCustom`,(e,t)=>{A.init(e,t),j.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=>Tr(t,n,r,e));Tr(i,n,r,e)}});function Tr(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(nt(e))}}var Er,Dr=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 Or(){return new Dr}(Er=globalThis).__zod_globalRegistry??(Er.__zod_globalRegistry=Or());const kr=globalThis.__zod_globalRegistry;function Ar(e,t){return new e({type:`string`,...D(t)})}function jr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...D(t)})}function Mr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...D(t)})}function Nr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...D(t)})}function Pr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...D(t)})}function Fr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...D(t)})}function Ir(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...D(t)})}function Lr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...D(t)})}function Rr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...D(t)})}function zr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...D(t)})}function Br(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...D(t)})}function Vr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...D(t)})}function Hr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...D(t)})}function Ur(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...D(t)})}function Wr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...D(t)})}function Gr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...D(t)})}function Kr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...D(t)})}function qr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...D(t)})}function Jr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...D(t)})}function Yr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...D(t)})}function Xr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...D(t)})}function Zr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...D(t)})}function Qr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...D(t)})}function $r(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...D(t)})}function ei(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...D(t)})}function ti(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...D(t)})}function ni(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...D(t)})}function ri(e,t){return new e({type:`number`,checks:[],...D(t)})}function ii(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...D(t)})}function ai(e){return new e({type:`unknown`})}function oi(e,t){return new e({type:`never`,...D(t)})}function si(e,t){return new $t({check:`less_than`,...D(t),value:e,inclusive:!1})}function ci(e,t){return new $t({check:`less_than`,...D(t),value:e,inclusive:!0})}function li(e,t){return new en({check:`greater_than`,...D(t),value:e,inclusive:!1})}function ui(e,t){return new en({check:`greater_than`,...D(t),value:e,inclusive:!0})}function di(e,t){return new tn({check:`multiple_of`,...D(t),value:e})}function fi(e,t){return new rn({check:`max_length`,...D(t),maximum:e})}function pi(e,t){return new an({check:`min_length`,...D(t),minimum:e})}function mi(e,t){return new on({check:`length_equals`,...D(t),length:e})}function hi(e,t){return new cn({check:`string_format`,format:`regex`,...D(t),pattern:e})}function gi(e){return new ln({check:`string_format`,format:`lowercase`,...D(e)})}function _i(e){return new un({check:`string_format`,format:`uppercase`,...D(e)})}function vi(e,t){return new dn({check:`string_format`,format:`includes`,...D(t),includes:e})}function yi(e,t){return new fn({check:`string_format`,format:`starts_with`,...D(t),prefix:e})}function bi(e,t){return new pn({check:`string_format`,format:`ends_with`,...D(t),suffix:e})}function xi(e){return new mn({check:`overwrite`,tx:e})}function Si(e){return xi(t=>t.normalize(e))}function Ci(){return xi(e=>e.trim())}function wi(){return xi(e=>e.toLowerCase())}function Ti(){return xi(e=>e.toUpperCase())}function Ei(){return xi(e=>Pe(e))}function Di(e,t,n){return new e({type:`array`,element:t,...D(n)})}function Oi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...D(n)})}function ki(e,t){let n=Ai(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(nt(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(nt(r))}},e(t.value,t)),t);return n}function Ai(e,t){let n=new A({check:`custom`,...D(t)});return n._zod.check=e,n}function ji(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??kr,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 N(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,N(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`&&P(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 Mi(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>
64
+ `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Le,s=!we.jitless,c=s&&Re.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?$n([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function nr(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 rr=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=>nr(t,r,e,i)):nr(o,r,e,i)}}),ir=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])=>or(e,t,n)):or(e,i,a)}});function ar(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ze(e)&&ze(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=ar(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=ar(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 or(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=ar(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const sr=S(`$ZodRecord`,(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!ze(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}}),cr=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=>Ve.has(typeof e)).map(e=>typeof e==`string`?He(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}}),lr=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 ur(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const dr=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=>ur(e,r)):ur(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),fr=S(`$ZodExactOptional`,(e,t)=>{dr.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)}),pr=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)}),mr=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=>hr(e,t)):hr(r,t)}});function hr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const gr=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))}),_r=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=>vr(t,e)):vr(i,e)}});function vr(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 yr=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)}}),br=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=>xr(e,t.in,n)):xr(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>xr(e,t.out,n)):xr(r,t.out,n)}});function xr(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 Sr=S(`$ZodPreprocess`,(e,t)=>{br.init(e,t)}),Cr=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(wr):wr(r)}});function wr(e){return e.value=Object.freeze(e.value),e}const Tr=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=>Er(t,n,r,e));Er(i,n,r,e)}});function Er(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 Dr,Or=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 kr(){return new Or}(Dr=globalThis).__zod_globalRegistry??(Dr.__zod_globalRegistry=kr());const Ar=globalThis.__zod_globalRegistry;function jr(e,t){return new e({type:`string`,...E(t)})}function Mr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...E(t)})}function Nr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...E(t)})}function Pr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...E(t)})}function Fr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...E(t)})}function Ir(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...E(t)})}function Lr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...E(t)})}function Rr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...E(t)})}function zr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...E(t)})}function Br(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...E(t)})}function Vr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...E(t)})}function Hr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...E(t)})}function Ur(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...E(t)})}function Wr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...E(t)})}function Gr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...E(t)})}function Kr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...E(t)})}function qr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...E(t)})}function Jr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...E(t)})}function Yr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...E(t)})}function Xr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...E(t)})}function Zr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...E(t)})}function Qr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...E(t)})}function $r(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...E(t)})}function ei(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...E(t)})}function ti(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...E(t)})}function ni(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...E(t)})}function ri(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...E(t)})}function ii(e,t){return new e({type:`number`,checks:[],...E(t)})}function ai(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...E(t)})}function oi(e){return new e({type:`unknown`})}function si(e,t){return new e({type:`never`,...E(t)})}function ci(e,t){return new en({check:`less_than`,...E(t),value:e,inclusive:!1})}function li(e,t){return new en({check:`less_than`,...E(t),value:e,inclusive:!0})}function ui(e,t){return new tn({check:`greater_than`,...E(t),value:e,inclusive:!1})}function di(e,t){return new tn({check:`greater_than`,...E(t),value:e,inclusive:!0})}function fi(e,t){return new nn({check:`multiple_of`,...E(t),value:e})}function pi(e,t){return new an({check:`max_length`,...E(t),maximum:e})}function mi(e,t){return new on({check:`min_length`,...E(t),minimum:e})}function hi(e,t){return new sn({check:`length_equals`,...E(t),length:e})}function gi(e,t){return new ln({check:`string_format`,format:`regex`,...E(t),pattern:e})}function _i(e){return new un({check:`string_format`,format:`lowercase`,...E(e)})}function vi(e){return new dn({check:`string_format`,format:`uppercase`,...E(e)})}function yi(e,t){return new fn({check:`string_format`,format:`includes`,...E(t),includes:e})}function bi(e,t){return new pn({check:`string_format`,format:`starts_with`,...E(t),prefix:e})}function xi(e,t){return new mn({check:`string_format`,format:`ends_with`,...E(t),suffix:e})}function Si(e){return new hn({check:`overwrite`,tx:e})}function Ci(e){return Si(t=>t.normalize(e))}function wi(){return Si(e=>e.trim())}function Ti(){return Si(e=>e.toLowerCase())}function Ei(){return Si(e=>e.toUpperCase())}function Di(){return Si(e=>Fe(e))}function Oi(e,t,n){return new e({type:`array`,element:t,...E(n)})}function ki(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...E(n)})}function Ai(e,t){let n=ji(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 ji(e,t){let n=new k({check:`custom`,...E(t)});return n._zod.check=e,n}function Mi(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??Ar,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 Ni(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>
65
65
 
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 Ni(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:Fi(t,`input`,e.processors),output:Fi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function P(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 P(r.element,n);if(r.type===`set`)return P(r.valueType,n);if(r.type===`lazy`)return P(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 P(r.innerType,n);if(r.type===`intersection`)return P(r.left,n)||P(r.right,n);if(r.type===`record`||r.type===`map`)return P(r.keyType,n)||P(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:P(r.in,n)||P(r.out,n);if(r.type===`object`){for(let e in r.shape)if(P(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(P(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(P(e,n))return!0;return!!(r.rest&&P(r.rest,n))}return!1}const Pi=(e,t={})=>n=>{let r=ji({...n,processors:t});return N(e,r),Mi(r,e),Ni(r,e)},Fi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ji({...i??{},target:a,io:t,processors:n});return N(e,o),Mi(o,e),Ni(o,e)},Ii={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Li=(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=Ii[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}))])}},Ri=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`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)},zi=(e,t,n,r)=>{n.not={}},Bi=(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},Vi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Hi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ui=(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=N(a.element,t,{...r,path:[...r.path,`items`]})},Wi=(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]=N(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=N(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Gi=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>N(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ki=(e,t,n,r)=>{let i=e._zod.def,a=N(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=N(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=N(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=N(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=N(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)}},Ji=(e,t,n,r)=>{let i=e._zod.def,a=N(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`}]},Yi=(e,t,n,r)=>{let i=e._zod.def;N(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xi=(e,t,n,r)=>{let i=e._zod.def;N(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Zi=(e,t,n,r)=>{let i=e._zod.def;N(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)))},Qi=(e,t,n,r)=>{let i=e._zod.def;N(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},$i=(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;N(o,t,r);let s=t.seen.get(e);s.ref=o},ea=(e,t,n,r)=>{let i=e._zod.def;N(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ta=(e,t,n,r)=>{let i=e._zod.def;N(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},na=S(`ZodISODateTime`,(e,t)=>{kn.init(e,t),R.init(e,t)});function ra(e){return $r(na,e)}const ia=S(`ZodISODate`,(e,t)=>{An.init(e,t),R.init(e,t)});function aa(e){return ei(ia,e)}const oa=S(`ZodISOTime`,(e,t)=>{jn.init(e,t),R.init(e,t)});function sa(e){return ti(oa,e)}const ca=S(`ZodISODuration`,(e,t)=>{Mn.init(e,t),R.init(e,t)});function la(e){return ni(ca,e)}const F=S(`ZodError`,(e,t)=>{it.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>st(e,t)},flatten:{value:t=>ot(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}),ua=lt(F),da=ut(F),fa=dt(F),pa=pt(F),ma=ht(F),ha=gt(F),ga=_t(F),_a=vt(F),va=yt(F),ya=bt(F),ba=xt(F),xa=St(F),Sa=new WeakMap;function Ca(e,t,n){let r=Object.getPrototypeOf(e),i=Sa.get(r);if(i||(i=new Set,Sa.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 I=S(`ZodType`,(e,t)=>(j.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Fi(e,`input`),output:Fi(e,`output`)}}),e.toJSONSchema=Pi(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>ua(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>fa(e,t,n),e.parseAsync=async(t,n)=>da(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>pa(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ma(e,t,n),e.decode=(t,n)=>ha(e,t,n),e.encodeAsync=async(t,n)=>ga(e,t,n),e.decodeAsync=async(t,n)=>_a(e,t,n),e.safeEncode=(t,n)=>va(e,t,n),e.safeDecode=(t,n)=>ya(e,t,n),e.safeEncodeAsync=async(t,n)=>ba(e,t,n),e.safeDecodeAsync=async(t,n)=>xa(e,t,n),Ca(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 E(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Fo(e,t))},superRefine(e,t){return this.check(Io(e,t))},overwrite(e){return this.check(xi(e))},optional(){return go(this)},exactOptional(){return vo(this)},nullable(){return bo(this)},nullish(){return go(bo(this))},nonoptional(e){return Eo(this,e)},array(){return eo(this)},or(e){return ao([this,e])},and(e){return so(this,e)},transform(e){return Ao(this,mo(e))},default(e){return So(this,e)},prefault(e){return wo(this,e)},catch(e){return Oo(this,e)},pipe(e){return Ao(this,e)},readonly(){return No(this)},describe(e){let t=this.clone();return kr.add(t,{description:e}),t},meta(...e){if(e.length===0)return kr.get(this);let t=this.clone();return kr.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 kr.get(e)?.description},configurable:!0}),e)),wa=S(`_ZodString`,(e,t)=>{_n.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Li(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ca(e,`_ZodString`,{regex(...e){return this.check(hi(...e))},includes(...e){return this.check(vi(...e))},startsWith(...e){return this.check(yi(...e))},endsWith(...e){return this.check(bi(...e))},min(...e){return this.check(pi(...e))},max(...e){return this.check(fi(...e))},length(...e){return this.check(mi(...e))},nonempty(...e){return this.check(pi(1,...e))},lowercase(e){return this.check(gi(e))},uppercase(e){return this.check(_i(e))},trim(){return this.check(Ci())},normalize(...e){return this.check(Si(...e))},toLowerCase(){return this.check(wi())},toUpperCase(){return this.check(Ti())},slugify(){return this.check(Ei())}})}),Ta=S(`ZodString`,(e,t)=>{_n.init(e,t),wa.init(e,t),e.email=t=>e.check(jr(Ea,t)),e.url=t=>e.check(Lr(ka,t)),e.jwt=t=>e.check(Qr(Wa,t)),e.emoji=t=>e.check(Rr(Aa,t)),e.guid=t=>e.check(Mr(Da,t)),e.uuid=t=>e.check(Nr(Oa,t)),e.uuidv4=t=>e.check(Pr(Oa,t)),e.uuidv6=t=>e.check(Fr(Oa,t)),e.uuidv7=t=>e.check(Ir(Oa,t)),e.nanoid=t=>e.check(zr(ja,t)),e.guid=t=>e.check(Mr(Da,t)),e.cuid=t=>e.check(Br(Ma,t)),e.cuid2=t=>e.check(Vr(Na,t)),e.ulid=t=>e.check(Hr(Pa,t)),e.base64=t=>e.check(Yr(Va,t)),e.base64url=t=>e.check(Xr(Ha,t)),e.xid=t=>e.check(Ur(Fa,t)),e.ksuid=t=>e.check(Wr(Ia,t)),e.ipv4=t=>e.check(Gr(La,t)),e.ipv6=t=>e.check(Kr(Ra,t)),e.cidrv4=t=>e.check(qr(za,t)),e.cidrv6=t=>e.check(Jr(Ba,t)),e.e164=t=>e.check(Zr(Ua,t)),e.datetime=t=>e.check(ra(t)),e.date=t=>e.check(aa(t)),e.time=t=>e.check(sa(t)),e.duration=t=>e.check(la(t))});function L(e){return Ar(Ta,e)}const R=S(`ZodStringFormat`,(e,t)=>{M.init(e,t),wa.init(e,t)}),Ea=S(`ZodEmail`,(e,t)=>{bn.init(e,t),R.init(e,t)}),Da=S(`ZodGUID`,(e,t)=>{vn.init(e,t),R.init(e,t)}),Oa=S(`ZodUUID`,(e,t)=>{yn.init(e,t),R.init(e,t)}),ka=S(`ZodURL`,(e,t)=>{xn.init(e,t),R.init(e,t)}),Aa=S(`ZodEmoji`,(e,t)=>{Sn.init(e,t),R.init(e,t)}),ja=S(`ZodNanoID`,(e,t)=>{Cn.init(e,t),R.init(e,t)}),Ma=S(`ZodCUID`,(e,t)=>{wn.init(e,t),R.init(e,t)}),Na=S(`ZodCUID2`,(e,t)=>{Tn.init(e,t),R.init(e,t)}),Pa=S(`ZodULID`,(e,t)=>{En.init(e,t),R.init(e,t)}),Fa=S(`ZodXID`,(e,t)=>{Dn.init(e,t),R.init(e,t)}),Ia=S(`ZodKSUID`,(e,t)=>{On.init(e,t),R.init(e,t)}),La=S(`ZodIPv4`,(e,t)=>{Nn.init(e,t),R.init(e,t)}),Ra=S(`ZodIPv6`,(e,t)=>{Pn.init(e,t),R.init(e,t)}),za=S(`ZodCIDRv4`,(e,t)=>{Fn.init(e,t),R.init(e,t)}),Ba=S(`ZodCIDRv6`,(e,t)=>{In.init(e,t),R.init(e,t)}),Va=S(`ZodBase64`,(e,t)=>{Rn.init(e,t),R.init(e,t)}),Ha=S(`ZodBase64URL`,(e,t)=>{Bn.init(e,t),R.init(e,t)}),Ua=S(`ZodE164`,(e,t)=>{Vn.init(e,t),R.init(e,t)}),Wa=S(`ZodJWT`,(e,t)=>{Un.init(e,t),R.init(e,t)}),Ga=S(`ZodNumber`,(e,t)=>{Wn.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ri(e,t,n,r),Ca(e,`ZodNumber`,{gt(e,t){return this.check(li(e,t))},gte(e,t){return this.check(ui(e,t))},min(e,t){return this.check(ui(e,t))},lt(e,t){return this.check(si(e,t))},lte(e,t){return this.check(ci(e,t))},max(e,t){return this.check(ci(e,t))},int(e){return this.check(Ja(e))},safe(e){return this.check(Ja(e))},positive(e){return this.check(li(0,e))},nonnegative(e){return this.check(ui(0,e))},negative(e){return this.check(si(0,e))},nonpositive(e){return this.check(ci(0,e))},multipleOf(e,t){return this.check(di(e,t))},step(e,t){return this.check(di(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 Ka(e){return ri(Ga,e)}const qa=S(`ZodNumberFormat`,(e,t)=>{Gn.init(e,t),Ga.init(e,t)});function Ja(e){return ii(qa,e)}const Ya=S(`ZodUnknown`,(e,t)=>{Kn.init(e,t),I.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Xa(){return ai(Ya)}const Za=S(`ZodNever`,(e,t)=>{qn.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zi(e,t,n,r)});function Qa(e){return oi(Za,e)}const $a=S(`ZodArray`,(e,t)=>{Yn.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(e,t,n,r),e.element=t.element,Ca(e,`ZodArray`,{min(e,t){return this.check(pi(e,t))},nonempty(e){return this.check(pi(1,e))},max(e,t){return this.check(fi(e,t))},length(e,t){return this.check(mi(e,t))},unwrap(){return this.element}})});function eo(e,t){return Di($a,e,t)}const to=S(`ZodObject`,(e,t)=>{er.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r),w(e,`shape`,()=>t.shape),Ca(e,`ZodObject`,{keyof(){return fo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Xa()})},loose(){return this.clone({...this._zod.def,catchall:Xa()})},strict(){return this.clone({...this._zod.def,catchall:Qa()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Ke(this,e)},safeExtend(e){return qe(this,e)},merge(e){return Je(this,e)},pick(e){return We(this,e)},omit(e){return Ge(this,e)},partial(...e){return Ye(ho,this,e[0])},required(...e){return Xe(To,this,e[0])}})});function no(e,t){return new to({type:`object`,shape:e,catchall:Qa(),...D(t)})}function ro(e,t){return new to({type:`object`,shape:e,catchall:Xa(),...D(t)})}const io=S(`ZodUnion`,(e,t)=>{nr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.options=t.options});function ao(e,t){return new io({type:`union`,options:e,...D(t)})}const oo=S(`ZodIntersection`,(e,t)=>{rr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r)});function so(e,t){return new oo({type:`intersection`,left:e,right:t})}const co=S(`ZodRecord`,(e,t)=>{or.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qi(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function lo(e,t,n){return!t||!t._zod?new co({type:`record`,keyType:L(),valueType:e,...D(t)}):new co({type:`record`,keyType:e,valueType:t,...D(n)})}const uo=S(`ZodEnum`,(e,t)=>{sr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bi(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 uo({...t,checks:[],...D(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 uo({...t,checks:[],...D(r),entries:i})}});function fo(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new uo({type:`enum`,entries:n,...D(t)})}const po=S(`ZodTransform`,(e,t)=>{cr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(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(nt(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(nt(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 mo(e){return new po({type:`transform`,transform:e})}const ho=S(`ZodOptional`,(e,t)=>{ur.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function go(e){return new ho({type:`optional`,innerType:e})}const _o=S(`ZodExactOptional`,(e,t)=>{dr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vo(e){return new _o({type:`optional`,innerType:e})}const yo=S(`ZodNullable`,(e,t)=>{fr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ji(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bo(e){return new yo({type:`nullable`,innerType:e})}const xo=S(`ZodDefault`,(e,t)=>{pr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function So(e,t){return new xo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}const Co=S(`ZodPrefault`,(e,t)=>{hr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wo(e,t){return new Co({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}const To=S(`ZodNonOptional`,(e,t)=>{gr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Eo(e,t){return new To({type:`nonoptional`,innerType:e,...D(t)})}const Do=S(`ZodCatch`,(e,t)=>{vr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Oo(e,t){return new Do({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ko=S(`ZodPipe`,(e,t)=>{yr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r),e.in=t.in,e.out=t.out});function Ao(e,t){return new ko({type:`pipe`,in:e,out:t})}const jo=S(`ZodPreprocess`,(e,t)=>{ko.init(e,t),xr.init(e,t)}),Mo=S(`ZodReadonly`,(e,t)=>{Sr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function No(e){return new Mo({type:`readonly`,innerType:e})}const Po=S(`ZodCustom`,(e,t)=>{wr.init(e,t),I.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(e,t,n,r)});function Fo(e,t={}){return Oi(Po,e,t)}function Io(e,t){return ki(e,t)}function Lo(e,t){return new jo({type:`pipe`,in:mo(e),out:t})}const Ro=new Set([`__proto__`,`constructor`,`prototype`]),zo=(e,t,n)=>Lo((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),Bo=e=>e.length>0&&!Ro.has(e),Vo=e=>zo(Bo,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,lo(L().min(1),e)),Ho=[`blobless`,`full`],Uo=[`ssh`,`https`],Wo=/^(?!\.{1,2}$)[^/\\%:]+$/u,Go=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,Ko=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,qo={d:864e5,h:36e5,m:6e4},Jo=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),Yo=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},Xo=e=>{let[t=``,n]=e.split(`_`);return Yo(n)?t.split(`.`).every(e=>Jo(e)):!1},z=L().refine(e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!Go.test(t)||!Xo(t)?!1:n.every(e=>Wo.test(e))},`ref key must be host/path…/repo with safe, non-empty segments`).brand(),Zo=L().regex(Ko,`duration must be <n>m, <n>h, or <n>d`).brand(),Qo=e=>{let t=Ko.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)*qo[r]},$o=fo(Ho),es=fo(Uo),ts=L().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),ns=L().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>Wo.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),rs={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},is=no({clone_mode:$o.default(rs.clone_mode),git_transport:es.default(rs.git_transport),sync_ttl:Zo.default(Zo.parse(rs.sync_ttl))}),as=no((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(is.shape)),os=no({description:L().min(1),path:ns,tag_format:ts.optional()}),ss=no({default_branch:L().min(1),description:L().min(1),packages:Vo(os).optional(),tag_format:ts,url:L().min(1),...as.shape}),cs=no({meta:ro({cli_version:L().min(1),schema_version:Ka().int().positive()}),refs:zo(e=>z.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,lo(L(),ss)).default({}),settings:is});
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 Pi(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:Ii(t,`input`,e.processors),output:Ii(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 Fi=(e,t={})=>n=>{let r=Mi({...n,processors:t});return M(e,r),Ni(r,e),Pi(r,e)},Ii=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Mi({...i??{},target:a,io:t,processors:n});return M(e,o),Ni(o,e),Pi(o,e)},Li={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Ri=(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=Li[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}))])}},zi=(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)},Bi=(e,t,n,r)=>{n.not={}},Vi=(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},Hi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Ui=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Wi=(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`]})},Gi=(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)},Ki=(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},qi=(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]]},Ji=(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)}},Yi=(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`}]},Xi=(e,t,n,r)=>{let i=e._zod.def;M(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zi=(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))},Qi=(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)))},$i=(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},ea=(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},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.readOnly=!0},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},ra=S(`ZodISODateTime`,(e,t)=>{An.init(e,t),L.init(e,t)});function ia(e){return ei(ra,e)}const aa=S(`ZodISODate`,(e,t)=>{jn.init(e,t),L.init(e,t)});function oa(e){return ti(aa,e)}const sa=S(`ZodISOTime`,(e,t)=>{Mn.init(e,t),L.init(e,t)});function ca(e){return ni(sa,e)}const la=S(`ZodISODuration`,(e,t)=>{Nn.init(e,t),L.init(e,t)});function ua(e){return ri(la,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}),da=ut(P),fa=dt(P),pa=ft(P),ma=mt(P),ha=gt(P),ga=_t(P),_a=vt(P),va=yt(P),ya=bt(P),ba=xt(P),xa=St(P),Sa=Ct(P),Ca=new WeakMap;function wa(e,t,n){let r=Object.getPrototypeOf(e),i=Ca.get(r);if(i||(i=new Set,Ca.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:Ii(e,`input`),output:Ii(e,`output`)}}),e.toJSONSchema=Fi(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>da(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>pa(e,t,n),e.parseAsync=async(t,n)=>fa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ma(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ha(e,t,n),e.decode=(t,n)=>ga(e,t,n),e.encodeAsync=async(t,n)=>_a(e,t,n),e.decodeAsync=async(t,n)=>va(e,t,n),e.safeEncode=(t,n)=>ya(e,t,n),e.safeDecode=(t,n)=>ba(e,t,n),e.safeEncodeAsync=async(t,n)=>xa(e,t,n),e.safeDecodeAsync=async(t,n)=>Sa(e,t,n),wa(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Ne(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 T(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Fo(e,t))},superRefine(e,t){return this.check(Io(e,t))},overwrite(e){return this.check(Si(e))},optional(){return go(this)},exactOptional(){return vo(this)},nullable(){return bo(this)},nullish(){return go(bo(this))},nonoptional(e){return Eo(this,e)},array(){return to(this)},or(e){return ao([this,e])},and(e){return so(this,e)},transform(e){return Ao(this,mo(e))},default(e){return So(this,e)},prefault(e){return wo(this,e)},catch(e){return Oo(this,e)},pipe(e){return Ao(this,e)},readonly(){return No(this)},describe(e){let t=this.clone();return Ar.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ar.get(this);let t=this.clone();return Ar.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 Ar.get(e)?.description},configurable:!0}),e)),Ta=S(`_ZodString`,(e,t)=>{vn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ri(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,wa(e,`_ZodString`,{regex(...e){return this.check(gi(...e))},includes(...e){return this.check(yi(...e))},startsWith(...e){return this.check(bi(...e))},endsWith(...e){return this.check(xi(...e))},min(...e){return this.check(mi(...e))},max(...e){return this.check(pi(...e))},length(...e){return this.check(hi(...e))},nonempty(...e){return this.check(mi(1,...e))},lowercase(e){return this.check(_i(e))},uppercase(e){return this.check(vi(e))},trim(){return this.check(wi())},normalize(...e){return this.check(Ci(...e))},toLowerCase(){return this.check(Ti())},toUpperCase(){return this.check(Ei())},slugify(){return this.check(Di())}})}),Ea=S(`ZodString`,(e,t)=>{vn.init(e,t),Ta.init(e,t),e.email=t=>e.check(Mr(Da,t)),e.url=t=>e.check(Rr(Aa,t)),e.jwt=t=>e.check($r(Ga,t)),e.emoji=t=>e.check(zr(ja,t)),e.guid=t=>e.check(Nr(Oa,t)),e.uuid=t=>e.check(Pr(ka,t)),e.uuidv4=t=>e.check(Fr(ka,t)),e.uuidv6=t=>e.check(Ir(ka,t)),e.uuidv7=t=>e.check(Lr(ka,t)),e.nanoid=t=>e.check(Br(Ma,t)),e.guid=t=>e.check(Nr(Oa,t)),e.cuid=t=>e.check(Vr(Na,t)),e.cuid2=t=>e.check(Hr(Pa,t)),e.ulid=t=>e.check(Ur(Fa,t)),e.base64=t=>e.check(Xr(Ha,t)),e.base64url=t=>e.check(Zr(Ua,t)),e.xid=t=>e.check(Wr(Ia,t)),e.ksuid=t=>e.check(Gr(La,t)),e.ipv4=t=>e.check(Kr(Ra,t)),e.ipv6=t=>e.check(qr(za,t)),e.cidrv4=t=>e.check(Jr(Ba,t)),e.cidrv6=t=>e.check(Yr(Va,t)),e.e164=t=>e.check(Qr(Wa,t)),e.datetime=t=>e.check(ia(t)),e.date=t=>e.check(oa(t)),e.time=t=>e.check(ca(t)),e.duration=t=>e.check(ua(t))});function I(e){return jr(Ea,e)}const L=S(`ZodStringFormat`,(e,t)=>{j.init(e,t),Ta.init(e,t)}),Da=S(`ZodEmail`,(e,t)=>{xn.init(e,t),L.init(e,t)}),Oa=S(`ZodGUID`,(e,t)=>{yn.init(e,t),L.init(e,t)}),ka=S(`ZodUUID`,(e,t)=>{bn.init(e,t),L.init(e,t)}),Aa=S(`ZodURL`,(e,t)=>{Sn.init(e,t),L.init(e,t)}),ja=S(`ZodEmoji`,(e,t)=>{Cn.init(e,t),L.init(e,t)}),Ma=S(`ZodNanoID`,(e,t)=>{wn.init(e,t),L.init(e,t)}),Na=S(`ZodCUID`,(e,t)=>{Tn.init(e,t),L.init(e,t)}),Pa=S(`ZodCUID2`,(e,t)=>{En.init(e,t),L.init(e,t)}),Fa=S(`ZodULID`,(e,t)=>{Dn.init(e,t),L.init(e,t)}),Ia=S(`ZodXID`,(e,t)=>{On.init(e,t),L.init(e,t)}),La=S(`ZodKSUID`,(e,t)=>{kn.init(e,t),L.init(e,t)}),Ra=S(`ZodIPv4`,(e,t)=>{Pn.init(e,t),L.init(e,t)}),za=S(`ZodIPv6`,(e,t)=>{Fn.init(e,t),L.init(e,t)}),Ba=S(`ZodCIDRv4`,(e,t)=>{In.init(e,t),L.init(e,t)}),Va=S(`ZodCIDRv6`,(e,t)=>{Ln.init(e,t),L.init(e,t)}),Ha=S(`ZodBase64`,(e,t)=>{zn.init(e,t),L.init(e,t)}),Ua=S(`ZodBase64URL`,(e,t)=>{Vn.init(e,t),L.init(e,t)}),Wa=S(`ZodE164`,(e,t)=>{Hn.init(e,t),L.init(e,t)}),Ga=S(`ZodJWT`,(e,t)=>{Wn.init(e,t),L.init(e,t)}),Ka=S(`ZodNumber`,(e,t)=>{Gn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zi(e,t,n,r),wa(e,`ZodNumber`,{gt(e,t){return this.check(ui(e,t))},gte(e,t){return this.check(di(e,t))},min(e,t){return this.check(di(e,t))},lt(e,t){return this.check(ci(e,t))},lte(e,t){return this.check(li(e,t))},max(e,t){return this.check(li(e,t))},int(e){return this.check(Ya(e))},safe(e){return this.check(Ya(e))},positive(e){return this.check(ui(0,e))},nonnegative(e){return this.check(di(0,e))},negative(e){return this.check(ci(0,e))},nonpositive(e){return this.check(li(0,e))},multipleOf(e,t){return this.check(fi(e,t))},step(e,t){return this.check(fi(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 qa(e){return ii(Ka,e)}const Ja=S(`ZodNumberFormat`,(e,t)=>{Kn.init(e,t),Ka.init(e,t)});function Ya(e){return ai(Ja,e)}const Xa=S(`ZodUnknown`,(e,t)=>{qn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Za(){return oi(Xa)}const Qa=S(`ZodNever`,(e,t)=>{Jn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bi(e,t,n,r)});function $a(e){return si(Qa,e)}const eo=S(`ZodArray`,(e,t)=>{Xn.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r),e.element=t.element,wa(e,`ZodArray`,{min(e,t){return this.check(mi(e,t))},nonempty(e){return this.check(mi(1,e))},max(e,t){return this.check(pi(e,t))},length(e,t){return this.check(hi(e,t))},unwrap(){return this.element}})});function to(e,t){return Oi(eo,e,t)}const no=S(`ZodObject`,(e,t)=>{tr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),w(e,`shape`,()=>t.shape),wa(e,`ZodObject`,{keyof(){return fo(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Za()})},loose(){return this.clone({...this._zod.def,catchall:Za()})},strict(){return this.clone({...this._zod.def,catchall:$a()})},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(ho,this,e[0])},required(...e){return Ze(To,this,e[0])}})});function R(e,t){return new no({type:`object`,shape:e,catchall:$a(),...E(t)})}function ro(e,t){return new no({type:`object`,shape:e,catchall:Za(),...E(t)})}const io=S(`ZodUnion`,(e,t)=>{rr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r),e.options=t.options});function ao(e,t){return new io({type:`union`,options:e,...E(t)})}const oo=S(`ZodIntersection`,(e,t)=>{ir.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qi(e,t,n,r)});function so(e,t){return new oo({type:`intersection`,left:e,right:t})}const co=S(`ZodRecord`,(e,t)=>{sr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ji(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function lo(e,t,n){return!t||!t._zod?new co({type:`record`,keyType:I(),valueType:e,...E(t)}):new co({type:`record`,keyType:e,valueType:t,...E(n)})}const uo=S(`ZodEnum`,(e,t)=>{cr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(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 uo({...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 uo({...t,checks:[],...E(r),entries:i})}});function fo(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new uo({type:`enum`,entries:n,...E(t)})}const po=S(`ZodTransform`,(e,t)=>{lr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(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 mo(e){return new po({type:`transform`,transform:e})}const ho=S(`ZodOptional`,(e,t)=>{dr.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 go(e){return new ho({type:`optional`,innerType:e})}const _o=S(`ZodExactOptional`,(e,t)=>{fr.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 vo(e){return new _o({type:`optional`,innerType:e})}const yo=S(`ZodNullable`,(e,t)=>{pr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bo(e){return new yo({type:`nullable`,innerType:e})}const xo=S(`ZodDefault`,(e,t)=>{mr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function So(e,t){return new xo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}const Co=S(`ZodPrefault`,(e,t)=>{gr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wo(e,t){return new Co({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}const To=S(`ZodNonOptional`,(e,t)=>{_r.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Eo(e,t){return new To({type:`nonoptional`,innerType:e,...E(t)})}const Do=S(`ZodCatch`,(e,t)=>{yr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Oo(e,t){return new Do({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ko=S(`ZodPipe`,(e,t)=>{br.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r),e.in=t.in,e.out=t.out});function Ao(e,t){return new ko({type:`pipe`,in:e,out:t})}const jo=S(`ZodPreprocess`,(e,t)=>{ko.init(e,t),Sr.init(e,t)}),Mo=S(`ZodReadonly`,(e,t)=>{Cr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function No(e){return new Mo({type:`readonly`,innerType:e})}const Po=S(`ZodCustom`,(e,t)=>{Tr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(e,t,n,r)});function Fo(e,t={}){return ki(Po,e,t)}function Io(e,t){return Ai(e,t)}function Lo(e,t){return new jo({type:`pipe`,in:mo(e),out:t})}const Ro=new Set([`__proto__`,`constructor`,`prototype`]),zo=(e,t,n)=>Lo((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),Bo=e=>e.length>0&&!Ro.has(e),Vo=e=>zo(Bo,()=>`package key must be non-empty and not "__proto__", "constructor", or "prototype"`,lo(I().min(1),e)),Ho=[`blobless`,`full`],Uo=[`ssh`,`https`],Wo=/^(?!\.{1,2}$)[^/\\%:]+$/u,Go=/^[a-z0-9][a-z0-9.-]*(?:_[1-9]\d{0,4})?$/u,Ko=/^(?<amount>[1-9]\d{0,3})(?<unit>[mhd])$/u,qo={d:864e5,h:36e5,m:6e4},Jo=e=>e!==``&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e),Yo=e=>{if(e===void 0)return!0;let t=Number(e);return t>=1&&t<=65535},Xo=e=>{let[t=``,n]=e.split(`_`);return Yo(n)?t.split(`.`).every(e=>Jo(e)):!1},z=I().refine(e=>{let[t,...n]=e.split(`/`);return t===void 0||n.length<2||!Go.test(t)||!Xo(t)?!1:n.every(e=>Wo.test(e))},`ref key must be host/path…/repo with safe, non-empty segments`).brand(),Zo=I().regex(Ko,`duration must be <n>m, <n>h, or <n>d`).brand(),Qo=e=>{let t=Ko.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)*qo[r]},$o=fo(Ho),es=fo(Uo),ts=I().refine(e=>e.includes(`{version}`),`tag format must contain {version}`),ns=I().refine(e=>{if(e===`.`)return!0;let t=e.split(`/`);return t.length>0&&t.every(e=>Wo.test(e)&&e!==`.`)},`package path must be "." or a normalized relative path without traversal`),rs={clone_mode:`blobless`,git_transport:`https`,sync_ttl:`1h`},is=R({clone_mode:$o.default(rs.clone_mode),git_transport:es.default(rs.git_transport),sync_ttl:Zo.default(Zo.parse(rs.sync_ttl))}),as=R((e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.removeDefault().optional()])))(is.shape)),os=R({description:I().min(1),path:ns,tag_format:ts.optional()}),ss=R({default_branch:I().min(1),description:I().min(1),packages:Vo(os).optional(),tag_format:ts,url:I().min(1),...as.shape}),cs=R({meta:ro({cli_version:I().min(1),schema_version:qa().int().positive()}),refs:zo(e=>z.safeParse(e).success,()=>`ref key must be host/path…/repo with safe, non-empty segments`,lo(I(),ss)).default({}),settings:is});
67
67
  /*!
68
68
  * Copyright (c) Squirrel Chat et al., All rights reserved.
69
69
  * SPDX-License-Identifier: BSD-3-Clause
@@ -153,8 +153,8 @@ let ps=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,ms=/^[+-]?
153
153
  `?t++:e[t]===`\r`&&e[t+1]===`
154
154
  `&&(t+=2));let o=``,s=t,c=0;for(let l=t;l<e.length;l++)if(n=e[l],a&&(n===`
155
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 _s(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=ps.test(e);if(i||ms.test(e)){if(hs.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 us(e);if(!a.isValid())throw new B(`invalid value`,{toml:t,ptr:n});return a}
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 _s(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=ps.test(e);if(i||ms.test(e)){if(hs.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 us(e);if(!a.isValid())throw new B(`invalid value`,{toml:t,ptr:n});return a}
158
158
  /*!
159
159
  * Copyright (c) Squirrel Chat et al., All rights reserved.
160
160
  * SPDX-License-Identifier: BSD-3-Clause
@@ -246,7 +246,7 @@ function Ss(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(ys(e,i),r=r
246
246
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
247
247
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
248
248
  */
249
- let ws=/^[a-zA-Z0-9-_]+[ \t]*$/;function Ts(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]=gs(e,t);r=e.indexOf(`.`,c);let l=e.slice(c,r<0||r>a?a:r),u=vs(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(!ws.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,bs(e,a+1,!0,!0)]}function Es(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=ys(e,t);else if(o!==` `&&o!==` `&&o!==`
249
+ let ws=/^[a-zA-Z0-9-_]+[ \t]*$/;function Ts(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]=gs(e,t);r=e.indexOf(`.`,c);let l=e.slice(c,r<0||r>a?a:r),u=vs(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(!ws.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,bs(e,a+1,!0,!0)]}function Es(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=ys(e,t);else if(o!==` `&&o!==` `&&o!==`
250
250
  `&&o!==`\r`){let o,s=i,c=!1,[l,u]=Ts(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]=Cs(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 Ds(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=ys(e,t);else if(a!==` `&&a!==` `&&a!==`
251
251
  `&&a!==`\r`){let a=Cs(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]}
252
252
  /*!
@@ -311,7 +311,7 @@ let As=/^[a-z0-9-_]+$/i;function js(e){let t=typeof e;if(t===`object`){if(Array.
311
311
  `)+Rs(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=Ps(t[c],e,r,i),a+=`
312
312
  `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function zs(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(js(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=Rs(0,e,``,t,n);return r[r.length-1]===`
313
313
  `?r:r+`
314
- `}const V=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,Bs=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{configPath:h(t,`config.toml`),hooksDir:h(t,`hooks`),locksDir:h(t,`locks`),root:t,sourcesDir:h(t,`sources`),statePath:h(t,`state.json`)}},U=(e,t)=>h(e.sourcesDir,...t.split(`/`)),Vs=e=>`${e.configPath}.bak`,Hs=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}},Us=e=>{let{ancestor:t,missing:n}=Hs(e),r=ue(t);return n.length===0?r:h(r,...n)},Ws=(e,t,n)=>{let r=ie(Us(e),Us(t)),i=r===`..`||r.startsWith(`..`+oe);if(!(r!==``&&!i&&!ne(r)))throw x(`path escapes ${n} (containment violation): ${t}`)},Gs=(e,t)=>{Ws(e.sourcesDir,t,`sources directory`)},Ks=e=>typeof e==`object`&&!!e&&!Array.isArray(e),qs=(e,t)=>Ks(e)?e:t,Js=async e=>{try{return await o(e.configPath,`utf8`)}catch(e){throw V(e)?y(`no config found — run: refs init`):e}},Ys=(e,t)=>{try{return ks(e)}catch(e){throw e instanceof B?x(`invalid TOML in ${t}: ${e.message}`):e}},Xs=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,Zs=e=>{let{meta:t}=e;if(!Ks(t))return;let n=t.schema_version;if(Xs(n))return n},Qs=(e,t)=>{let n=Zs(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 Js(e),n=Ys(t,e.configPath);Qs(n,e.configPath);let r=cs.safeParse(n);if(!r.success)throw x(k(r.error));return r.data},$s=async(e,t)=>{let n=cs.safeParse(t);if(!n.success)throw x(k(n.error));await Bs(e.configPath,zs(n.data))},ec=async e=>{try{return await f(e),!0}catch(e){if(V(e))return!1;throw e}},tc=async(e,t)=>await ec(e.configPath)?`noop`:(await Bs(e.configPath,`# refs configuration
314
+ `}const V=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`,Bs=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{configPath:h(t,`config.toml`),hooksDir:h(t,`hooks`),locksDir:h(t,`locks`),root:t,sourcesDir:h(t,`sources`),statePath:h(t,`state.json`)}},U=(e,t)=>h(e.sourcesDir,...t.split(`/`)),Vs=e=>`${e.configPath}.bak`,Hs=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}},Us=e=>{let{ancestor:t,missing:n}=Hs(e),r=ue(t);return n.length===0?r:h(r,...n)},Ws=(e,t,n)=>{let r=Us(e),i=Us(t),a=ie(r,i),o=a===`..`||a.startsWith(`..`+oe);if(!(a!==``&&!o&&!ne(a)))throw x(`path escapes ${n} (containment violation): ${t}`)},Gs=(e,t)=>{Ws(e.sourcesDir,t,`sources directory`)},Ks=e=>typeof e==`object`&&!!e&&!Array.isArray(e),qs=(e,t)=>Ks(e)?e:t,Js=async e=>{try{return await o(e.configPath,`utf8`)}catch(e){throw V(e)?y(`no config found — run: refs init`):e}},Ys=(e,t)=>{try{return ks(e)}catch(e){throw e instanceof B?x(`invalid TOML in ${t}: ${e.message}`):e}},Xs=e=>typeof e==`number`&&Number.isInteger(e)&&e>=1,Zs=e=>{let{meta:t}=e;if(!Ks(t))return;let n=t.schema_version;if(Xs(n))return n},Qs=(e,t)=>{let n=Zs(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 Js(e),n=Ys(t,e.configPath);Qs(n,e.configPath);let r=cs.safeParse(n);if(!r.success)throw x(O(r.error));return r.data},$s=async(e,t)=>{let n=cs.safeParse(t);if(!n.success)throw x(O(n.error));await Bs(e.configPath,zs(n.data))},ec=async e=>{try{return await f(e),!0}catch(e){if(V(e))return!1;throw e}},tc=async(e,t)=>await ec(e.configPath)?`noop`:(await Bs(e.configPath,`# refs configuration
315
315
  #
316
316
  # Every global setting under [settings] can also be set per-ref: add the same
317
317
  # key directly inside a [refs."host/owner/repo"] table to override it just for
@@ -342,29 +342,29 @@ sync_ttl = "1h"
342
342
  # tag_format = "v{version}"
343
343
  # # Per-ref overrides of [settings] go in the same table, e.g.:
344
344
  # # clone_mode = "full"
345
- `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),nc=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:Ks(t)&&Ks(r)&&(n[e]=nc(t,r))}return n},rc={meta:{},refs:{},settings:{}},ic=async e=>{try{return await Js(e)}catch(e){if(e instanceof v&&e.code===`not_found`)return;throw e}},ac=e=>{if(e!==void 0&&e>1)throw x(`config schema ${e} is newer than this CLI supports — upgrade refs`)},oc=async(e,t,n)=>{let r=qs(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await Bs(e.configPath,zs(i))},sc=async(e,t,n)=>{await r(e.configPath,Vs(e));let i=nc(t,rc),a=qs(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=cs.safeParse(o);if(!s.success)throw x(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${Vs(e)}): ${k(s.error)}`);await Bs(e.configPath,zs(o))},cc=async(e,t,n)=>{let r=Ys(t,e.configPath),i=Zs(r);return ac(i),i===1?(await oc(e,r,n),`noop`):(await sc(e,r,n),`migrated`)},lc=async(e,t)=>{let n=await ic(e);return n===void 0?(await tc(e,t),`seeded`):cc(e,n,t)},uc=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)}…`},dc=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,fc=(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(` | `)},pc=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:dc(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=fc(n,r);return o!==void 0&&(a.warning=o),a},mc=(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`)),hc=e=>`refusing to sync ${e}: not a refs-managed checkout`,gc=async(e,t)=>{if(!G(t))throw x(hc(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw x(hc(t))},_c=/filtering not recognized/iu,vc=e=>e===void 0?{}:{cwd:e},K=(e,t,n)=>({action:e,args:t,cmd:`git`,...vc(n)}),yc=async(e,t)=>{let n=await e.run(t.cmd,t.args,vc(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}`)},bc=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(t.cloneUrl,t.dest);let r=await yc(e,K(`git clone`,n));return await yc(e,K(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&_c.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}},xc=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},Sc=async(e,t)=>{let n=await xc(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await xc(e,t);if(r!==void 0)return r;throw x(`could not detect the default branch for checkout: ${t}`)},Cc=async(e,t)=>(await yc(e,K(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),wc=async(e,t)=>(await yc(e,K(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Tc=async(e,t)=>{await yc(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 Sc(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${uc(n)}`),i},Ec=e=>[K(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),K(`git clean -fd`,[`clean`,`-fd`],e)],Dc=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Ec(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 yc(e,t)},Oc=async(e,t)=>{await gc(e,t.dir);let n=await Cc(e,t.dir),r=await Tc(e,t),i=await wc(e,t.dir);return await Dc(e,{branch:r.branch,dir:t.dir,dirty:i}),pc(mc(r,i,{newSha:await Cc(e,t.dir),oldSha:n}))},kc=async(e,t,n=20)=>(await yc(e,K(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
345
+ `.replaceAll(`{{CLI_VERSION}}`,t)),`seeded`),nc=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];t===void 0?n[e]=r:Ks(t)&&Ks(r)&&(n[e]=nc(t,r))}return n},rc={meta:{},refs:{},settings:{}},ic=async e=>{try{return await Js(e)}catch(e){if(e instanceof v&&e.code===`not_found`)return;throw e}},ac=e=>{if(e!==void 0&&e>1)throw x(`config schema ${e} is newer than this CLI supports — upgrade refs`)},oc=async(e,t,n)=>{let r=qs(t.meta,{});if(r.cli_version===n)return;let i={...t,meta:{...r,cli_version:n}};await Bs(e.configPath,zs(i))},sc=async(e,t,n)=>{await r(e.configPath,Vs(e));let i=nc(t,rc),a=qs(i.meta,{}),o={...i,meta:{...a,cli_version:n,schema_version:1}},s=cs.safeParse(o);if(!s.success)throw x(`config in ${e.configPath} is malformed beyond automatic migration (backup preserved at ${Vs(e)}): ${O(s.error)}`);await Bs(e.configPath,zs(o))},cc=async(e,t,n)=>{let r=Ys(t,e.configPath),i=Zs(r);return ac(i),i===1?(await oc(e,r,n),`noop`):(await sc(e,r,n),`migrated`)},lc=async(e,t)=>{let n=await ic(e);return n===void 0?(await tc(e,t),`seeded`):cc(e,n,t)},uc=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)}…`},dc=(e,t)=>t?`restored`:e.oldSha===e.newSha?`fresh`:`updated`,fc=(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(` | `)},pc=e=>{let{branchRenamedTo:t,dirty:n,setHeadWarning:r,shas:i}=e,a={...i,status:dc(i,n)};t!==void 0&&(a.branchRenamedTo=t);let o=fc(n,r);return o!==void 0&&(a.warning=o),a},mc=(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`)),hc=e=>`refusing to sync ${e}: not a refs-managed checkout`,gc=async(e,t)=>{if(!G(t))throw x(hc(t));let n=await e.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:t});if(n.exitCode!==0||n.stdout.trim()===``)throw x(hc(t))},_c=/filtering not recognized/iu,vc=e=>e===void 0?{}:{cwd:e},K=(e,t,n)=>({action:e,args:t,cmd:`git`,...vc(n)}),yc=async(e,t)=>{let n=await e.run(t.cmd,t.args,vc(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}`)},bc=async(e,t)=>{let n=[`clone`,`-q`];t.mode===`blobless`&&n.push(`--filter=blob:none`),n.push(`--`,t.cloneUrl,t.dest);let r=await yc(e,K(`git clone`,n));return await yc(e,K(`git config core.hooksPath`,[`config`,`core.hooksPath`,t.hooksDir],t.dest)),t.mode===`blobless`&&_c.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}},xc=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},Sc=async(e,t)=>{let n=await xc(e,t);if(n!==void 0)return n;await e.run(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:t});let r=await xc(e,t);if(r!==void 0)return r;throw x(`could not detect the default branch for checkout: ${t}`)},Cc=async(e,t)=>(await yc(e,K(`git rev-parse HEAD`,[`rev-parse`,`HEAD`],t))).stdout.trim(),wc=async(e,t)=>(await yc(e,K(`git status --porcelain`,[`status`,`--porcelain`],t))).stdout.trim()!==``,Tc=async(e,t)=>{await yc(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 Sc(e,t.dir),i={branch:r};return r!==t.defaultBranch&&(i.branchRenamedTo=r),n.exitCode!==0&&(i.warning=`could not refresh origin/HEAD: ${uc(n)}`),i},Ec=e=>[K(`git reset --hard HEAD (pre-checkout)`,[`reset`,`--hard`,`HEAD`],e),K(`git clean -fd`,[`clean`,`-fd`],e)],Dc=async(e,t)=>{let{branch:n,dir:r,dirty:i}=t,a=[];i&&a.push(...Ec(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 yc(e,t)},Oc=async(e,t)=>{await gc(e,t.dir);let n=await Cc(e,t.dir),r=await Tc(e,t),i=await wc(e,t.dir);await Dc(e,{branch:r.branch,dir:t.dir,dirty:i});let a=await Cc(e,t.dir);return pc(mc(r,i,{newSha:a,oldSha:n}))},kc=async(e,t,n=20)=>(await yc(e,K(`git tag`,[`tag`,`--sort=-version:refname`],t))).stdout.split(`
347
347
  `).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),Ac=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,jc=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
348
- `),Mc=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=h(e.hooksDir,n);await Bs(r,jc),await t(r,493)}))},Nc=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Pc=/\d+\.\d+\.\d+/gu,Fc=e=>ts.safeParse(e).success,Ic=e=>{let t=e.match(Pc);return t!==null&&t.length>1},Lc=e=>{let t=Nc.exec(e);if(!t||Ic(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Fc(r))return r},Rc=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},zc=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Lc(r);e&&Rc(t,e,n)}return t},Bc=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Vc=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])=>Bc(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Hc=e=>{let t=zc(e);return Vc(t)},Uc=(e,t)=>e.replaceAll(`{version}`,()=>t),Wc=async(e,t,n,r)=>{let i=Uc(n,r);if(!await Ac(e,t,i))throw y(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Gc=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,q=e=>{let t=e.replace(Gc,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},Kc=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,qc=/^git\+/u,Jc={"https:":`443`,"ssh:":`22`},Yc=e=>e.replace(/\.git$/u,``),Xc=e=>e.split(`/`).some(e=>e===`.`||e===`..`),Zc=e=>e.includes(`\\`),Qc=e=>e.includes(`%`),$c=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},el=({host:e,port:t,protocol:n})=>{let r=Jc[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},tl=e=>{let t=Yc(e.path.replace(/^\/+/u,``).replace(/\/+$/u,``));return $c(`${el(e)}/${t}`)},nl=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 $c(`local/${n}/${r}`)},rl=(e,t)=>{try{return new URL(e)}catch{throw x(`not a supported git url: ${q(t)}`)}},il=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`)},al=(e,t)=>{if(e.protocol===`file:`){if(!t)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return nl(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return il(e),tl({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},ol=(e,t)=>{if(Qc(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`)},sl=(e,t)=>{let n=e.groups?.path??``;return ol(n,t),tl({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},cl=(e,t)=>{if(Zc(e))throw x(`not a supported git url: backslash not allowed in ${q(t)}`)},ll=(e,t)=>{if(Xc(e))throw x(`not a supported git url: path traversal segment in ${q(t)}`)},ul=(e,t,n)=>{if(e.protocol!==`file:`&&Qc(t))throw x(`not a supported git url: percent-encoding not supported in ${q(n)}`)},dl=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(qc,``);cl(r,e),ll(r,e);let i=Kc.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:sl(i,e)};let a=rl(r,e);return ul(a,r,e),{cloneUrl:r,key:al(a,n)}},fl=`.git`,pl=e=>e.replace(/^\/+/u,``).replace(/\/+$/u,``),ml=e=>e.endsWith(fl)?e:`${e}${fl}`,hl=(e,t)=>`https://${e.toLowerCase()}/${pl(t)}`,gl=(e,t)=>`git@${e.toLowerCase()}:${ml(pl(t))}`,_l=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw x(`not a supported git url: unsupported protocol ${e}`)},vl=(e,t,n)=>{let r=Jc[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`)},yl=(e,t)=>t===`https`?hl(e.hostname,e.pathname):gl(e.hostname,e.pathname),bl=(e,t,n)=>{let r=dl(t).key;if(r!==n)throw x(`git_transport transform changed repo identity: '${q(e)}' → '${t}' (key '${n}' → '${r}')`);return t},xl=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return bl(t.cloneUrl,hl(n,r),t.originalKey)},Sl=e=>{let t=rl(e.cloneUrl,e.cloneUrl);return _l(t.protocol)===e.transport?e.cloneUrl:(vl(t,e.transport,e.cloneUrl),bl(e.cloneUrl,yl(t,e.transport),e.originalKey))},Cl=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:dl(e).key,transport:t},r=Kc.exec(e);return r?.groups===void 0?Sl(n):xl(r,n)},wl=`meta.json`,Tl=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},El=e=>{try{return process.kill(e,0),!0}catch(e){return Tl(e)!==`ESRCH`}},Dl=e=>{try{return JSON.parse(e)}catch{return}},Ol=async e=>{try{return await o(e,`utf8`)}catch{return}},kl=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Al=e=>{if(typeof e!=`object`||!e)return;let t=e,{pid:n}=t,r=kl(t.acquired_at);if(typeof n==`number`&&r!==void 0)return{acquiredAtMs:r,pid:n}},jl=async e=>{let t=await Ol(h(e,wl));if(t!==void 0)return Al(Dl(t))},Ml=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Nl=async e=>{let t=await Ol(h(e,wl));if(t!==void 0)return Ml(Dl(t))},Pl=async e=>{try{return(await f(e)).mtimeMs}catch{return}},Fl=async(e,t)=>{let n=h(e,wl),r=`${n}.tmp-${se()}`;await p(r,t,`utf8`),await l(r,n)},Il=async(e,t)=>{await Fl(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Ll=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),Rl=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),zl=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Tl(e);if(t!==void 0&&Ll.has(t))return!1;throw e}},Bl=async(e,t)=>{try{return await l(e,t),!0}catch(e){let t=Tl(e);if(t!==void 0&&Rl.has(t))return!1;throw e}},Vl=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,Hl=async e=>{let t=await jl(e);if(t===void 0){let t=await Pl(e);return t!==void 0&&Date.now()-t>5e3}return Date.now()-t.acquiredAtMs>6e5||!El(t.pid)},Ul=async(e,t)=>{try{await Il(e,t)}catch(e){if(Tl(e)===`ENOENT`)return`retry`;throw e}return t},Wl=async e=>{if(!await zl(e))return;let t=await Ul(e,se());return t===`retry`?Wl(e):t},Gl=e=>h(e.locksDir,`${e.name}.steal-claim`),Kl=e=>h(e.locksDir,`${e.name}.steal.${se()}`),ql=async e=>{let t=await Pl(e);return t!==void 0&&Date.now()-t>2e3},Jl=async e=>await zl(e)?!0:await ql(e)?(await u(e,{force:!0,recursive:!0}),zl(e)):!1,Yl=async e=>{let t=Kl(e);return await Bl(e.lockPath,t)?t:void 0},Xl=async e=>{if(!await Hl(e.lockPath))return;let t=await Yl(e);t!==void 0&&await u(t,{force:!0,recursive:!0})},Zl=async e=>{let t=Gl(e);if(await Jl(t))try{await Xl(e)}finally{await u(t,{force:!0,recursive:!0})}},Ql=async(e,t)=>{if(await Hl(e.lockPath)){await Zl(e);return}if(Date.now()>=t)throw ve(`lock ${e.name} is held — another refs process is running`);await fe(100)},$l=async(e,t)=>{let n=await Wl(e.lockPath);return n===void 0?(await Ql(e,t),$l(e,t)):n},eu=async(e,t)=>{await Nl(e)===t&&await u(e,{force:!0,recursive:!0})},tu=e=>{if(e===`.`||e===`..`||!Vl.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)=>{tu(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 $l(i,o);try{return await n()}finally{await eu(i.lockPath,s)}},nu=ro({directory:L().optional(),url:L().optional()}),ru=ro({repository:ao([L(),nu]).optional()}),iu=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,au=new Set([`node_modules`,`favicon.ico`]),ou=e=>y(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),su=e=>{let[t,n]=e.split(`/`);return n??t??e},cu=e=>{if(e.length>214)throw b(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!iu.test(e))throw b(`invalid package name: '${e}' does not match npm naming rules`);let t=su(e);if(au.has(t))throw b(`invalid package name: '${e}' uses a reserved name`)},lu=e=>e.replace(`/`,`%2F`),uu=e=>typeof e==`string`?e:e?.url,du=e=>{if(typeof e==`object`&&e?.directory){let t=ns.safeParse(e.directory);if(t.success)return t.data}},fu=async(e,t)=>{try{return await e.json()}catch{throw x(`invalid npm registry response for '${t}': not parseable JSON`)}},pu=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${lu(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 fu(n,t),i=ru.safeParse(r);if(!i.success)throw x(`invalid npm package response for '${t}'`);return i.data},mu=(e,t)=>{try{return dl(e)}catch{throw ou(t)}},hu=async(e,t)=>{cu(t);let n=await pu(e,t),r=uu(n.repository);if(r===void 0||r===``)throw ou(t);let{cloneUrl:i,key:a}=mu(r,t),o=du(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},gu=new Set;let _u=!1;const vu=()=>{for(let e of gu)try{e.kill(`SIGKILL`)}catch{}},yu=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],bu=e=>{let t=()=>{vu(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},xu=()=>{_u||(_u=!0,yu.forEach(e=>{bu(e)}),process.on(`exit`,vu))},Su=()=>{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}}},Cu=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
349
- `),wu=(e,t,n)=>{let r=e;return t.truncated&&(r=Cu(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=Cu(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},Tu={clear:()=>{},markedTimedOut:()=>!1},Eu=(e,t)=>{if(t===void 0)return Tu;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}},Du=e=>e===void 0?{}:{cwd:e},Ou=(e,t)=>Cu(e,`refs: command timed out after ${String(t)}ms`),ku=(e,t)=>({exitCode:124,stderr:Ou(e,t),stdout:``,timedOut:!0}),Au=(e,t,n)=>{let r=ge(e,t,{...Du(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});gu.add(r);let i=Su(),a=Su();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:Eu(r,n?.timeoutMs)}},ju=(e,t,n)=>{try{return Au(e,t,n)}catch(e){return{exitCode:127,stderr:Nu(e),stdout:``}}},Mu=e=>!(`child`in e),Nu=e=>e instanceof Error?e.message:String(e),Pu=async e=>{try{let[t]=await me(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:Nu(e)}}},Fu=e=>e===null?1:e,Iu=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,Lu=e=>e.timedOut?ku(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Iu({exitCode:Fu(e.code),stderr:wu(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Iu({exitCode:127,stderr:Cu(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Ru=class{async run(e,t,n){xu();let r=ju(e,t,n);if(Mu(r))return r;let i=await Pu(r.child);return gu.delete(r.child),r.timeout.clear(),Lu({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const zu=os.partial({description:!0}),Bu=no({default_branch:L().min(1),key:z,tag_format_candidate:ts.nullable(),url:L().min(1)});Bu.extend({description:L().default(``),packages:Vo(zu)});const Vu=Bu.extend({description:L().min(1),packages:Vo(os)}),Hu=no({effective_clone_mode:$o.optional(),head_sha:L().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:L().optional(),last_fetched_at:ra().optional(),pending_proposal_at:ra().optional()}),Uu=no({refs:zo(e=>e.length>0&&!Ro.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,lo(L(),Hu)).default({})}),Y=(e,t,n)=>t?.[e]??n[e],Wu=async e=>{try{return await o(e.statePath,`utf8`)}catch(e){if(V(e))return;throw e}},Gu=e=>{try{return JSON.parse(e)}catch{return}},X=async e=>{let t=await Wu(e);if(t===void 0)return Uu.parse({});let n=Gu(t);if(n===void 0)return Uu.parse({});let r=Uu.safeParse(n);return r.success?r.data:Uu.parse({})},Ku=async(e,t)=>{let n=Uu.safeParse(t);if(!n.success)throw x(k(n.error));await Bs(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},qu=/[/\\]/u,Ju={kind:`ignore`},Yu=e=>!ne(e)&&e.split(qu).every(e=>e!==`.`&&e!==`..`),Xu=e=>Yu(e)&&!e.startsWith(`!`)&&!e.includes(`**`)&&(e.match(/\*/gu)??[]).length<=1,Zu=e=>Xu(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`}:e===`*`?{baseDir:`.`,kind:`expand-children`}:e.includes(`*`)?Ju:{dir:e,kind:`probe-dir`}:Ju,Qu=(e,t)=>{if(t&&e===``)return!0;let n=e===`..`||e.startsWith(`..`+oe);return e!==``&&!n&&!ne(e)},$u=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>re.join(e,t)),ed=(e,t)=>t?.name?{description:t.description,name:t.name,path:e}:void 0,td=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},nd=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,rd=/^packages:\s*(?:#.*)?$/u,id=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ad=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!id(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},od=Symbol(`end-of-section`),sd=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!rd.test(e))return od;if(!t.startsWith(`-`))return;let n=nd.exec(e)?.groups?.pattern?.trim();if(n)return n},cd=e=>{let t=[];for(let n of e){let e=sd(n);if(e===od)break;e!==void 0&&t.push(e)}return t},ld=e=>{let t=e.findIndex(e=>rd.test(e));return t===-1?[]:cd(e.slice(t+1))},ud=e=>{let{name:t}=e;if(typeof t==`string`)return t},dd=e=>{let{description:t}=e;if(typeof t==`string`)return t},fd=async(e,t,n=!1)=>{try{return Qu(ie(await c(e),await c(t)),n)}catch{return!1}},pd=async(e,t)=>{try{let n=h(t,`package.json`);return await fd(e,n)?(await o(n,`utf8`),!0):!1}catch{return!1}},md=async(e,t)=>{try{let n=h(e,t);if(!await fd(e,n,t===`.`))return[];let r=(await s(n,{withFileTypes:!0})).filter(e=>e.isDirectory()),i=await Promise.all(r.map(t=>pd(e,h(n,t.name))));return $u(t,r.map(e=>e.name),i)}catch{return[]}},hd=async(e,t)=>{let n=Zu(t);if(n.kind===`expand-children`)return md(e,n.baseDir);if(n.kind===`probe-dir`){let t=h(e,n.dir);if(await fd(e,t)&&await pd(e,t))return[n.dir]}return[]},gd=async(e,t)=>{try{let n=h(t,`package.json`);if(!await fd(e,n))return;let r=await o(n,`utf8`),i=JSON.parse(r);return{description:dd(i),name:ud(i)}}catch{return}},_d=async(e,t)=>{let n=new Set;try{if(!await fd(e,t))return n;let r=await o(t,`utf8`);ad(JSON.parse(r).workspaces).forEach(e=>n.add(e))}catch{}return n},vd=async(e,t)=>{let n=new Set;try{if(!await fd(e,t))return n;ld((await o(t,`utf8`)).split(`
350
- `)).forEach(e=>n.add(e))}catch{}return n},yd=async(e,t)=>{let n=new Set,r=[...t].map(t=>hd(e,t));return(await Promise.all(r)).forEach(e=>{e.forEach(e=>n.add(e))}),n},bd=async(e,t)=>{let n=h(e,t);if(await fd(e,n))return ed(t,await gd(e,n))},xd=async(e,t)=>{let n=[...t].map(t=>bd(e,t));return(await Promise.all(n)).filter(e=>e!==void 0)},Sd=async e=>{let t=h(e,`package.json`),n=h(e,`pnpm-workspace.yaml`),r=await _d(e,t),i=await vd(e,n),a=new Set([...r,...i]);if(a.size===0)return[];let o=await yd(e,a);return td(await xd(e,o))};var Cd=`0.8.0`;const wd=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Td=()=>({cliVersion:Cd,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:e=>fetch(e),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:wd,runner:new Ru});var Ed=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}},Dd=class extends Ed{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},Od=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new Dd(`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 kd(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var Ad=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=>kd(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(`
348
+ `),Mc=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=h(e.hooksDir,n);await Bs(r,jc),await t(r,493)}))},Nc=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Pc=/\d+\.\d+\.\d+/gu,Fc=e=>ts.safeParse(e).success,Ic=e=>{let t=e.match(Pc);return t!==null&&t.length>1},Lc=e=>{let t=Nc.exec(e);if(!t||Ic(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Fc(r))return r},Rc=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},zc=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Lc(r);e&&Rc(t,e,n)}return t},Bc=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Vc=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])=>Bc(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Hc=e=>{let t=zc(e);return Vc(t)},Uc=(e,t)=>e.replaceAll(`{version}`,()=>t),Wc=async(e,t,n,r)=>{let i=Uc(n,r);if(!await Ac(e,t,i))throw y(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Gc=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,q=e=>{let t=e.replace(Gc,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},Kc=/\.git$/u,qc=e=>e.replace(Kc,``),Jc=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)},Yc=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,Xc=/^git\+/u,Zc={"https:":`443`,"ssh:":`22`},Qc=e=>e.split(`/`).some(e=>e===`.`||e===`..`),$c=e=>e.includes(`\\`),el=e=>e.includes(`%`),tl=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},nl=({host:e,port:t,protocol:n})=>{let r=Zc[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},rl=e=>{let t=qc(Jc(e.path));return tl(`${nl(e)}/${t}`)},il=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 tl(`local/${n}/${r}`)},al=(e,t)=>{try{return new URL(e)}catch{throw x(`not a supported git url: ${q(t)}`)}},ol=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`)},sl=(e,t)=>{if(e.protocol===`file:`){if(!t)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return il(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw x(`not a supported git url: unsupported protocol ${e.protocol}`);return ol(e),rl({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},cl=(e,t)=>{if(el(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`)},ll=(e,t)=>{let n=e.groups?.path??``;return cl(n,t),rl({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},ul=(e,t)=>{if($c(e))throw x(`not a supported git url: backslash not allowed in ${q(t)}`)},dl=(e,t)=>{if(Qc(e))throw x(`not a supported git url: path traversal segment in ${q(t)}`)},fl=(e,t,n)=>{if(e.protocol!==`file:`&&el(t))throw x(`not a supported git url: percent-encoding not supported in ${q(n)}`)},pl=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(Xc,``);ul(r,e),dl(r,e);let i=Yc.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:ll(i,e)};let a=al(r,e);return fl(a,r,e),{cloneUrl:r,key:sl(a,n)}},ml=`.git`,hl=e=>e.endsWith(ml)?e:`${e}${ml}`,gl=(e,t)=>`https://${e.toLowerCase()}/${Jc(t)}`,_l=(e,t)=>`git@${e.toLowerCase()}:${hl(Jc(t))}`,vl=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw x(`not a supported git url: unsupported protocol ${e}`)},yl=(e,t,n)=>{let r=Zc[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`)},bl=(e,t)=>t===`https`?gl(e.hostname,e.pathname):_l(e.hostname,e.pathname),xl=(e,t,n)=>{let r=pl(t).key;if(r!==n)throw x(`git_transport transform changed repo identity: '${q(e)}' → '${t}' (key '${n}' → '${r}')`);return t},Sl=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return xl(t.cloneUrl,gl(n,r),t.originalKey)},Cl=e=>{let t=al(e.cloneUrl,e.cloneUrl);return vl(t.protocol)===e.transport?e.cloneUrl:(yl(t,e.transport,e.cloneUrl),xl(e.cloneUrl,bl(t,e.transport),e.originalKey))},wl=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:pl(e).key,transport:t},r=Yc.exec(e);return r?.groups===void 0?Cl(n):Sl(r,n)},Tl=`meta.json`,El=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},Dl=e=>{try{return process.kill(e,0),!0}catch(e){return El(e)!==`ESRCH`}},Ol=e=>{try{return JSON.parse(e)}catch{return}},kl=async e=>{try{return await o(e,`utf8`)}catch{return}},Al=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},jl=e=>{if(typeof e!=`object`||!e)return;let t=e,{pid:n}=t,r=Al(t.acquired_at);if(typeof n==`number`&&r!==void 0)return{acquiredAtMs:r,pid:n}},Ml=async e=>{let t=await kl(h(e,Tl));if(t!==void 0)return jl(Ol(t))},Nl=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Pl=async e=>{let t=await kl(h(e,Tl));if(t!==void 0)return Nl(Ol(t))},Fl=async e=>{try{return(await f(e)).mtimeMs}catch{return}},Il=async(e,t)=>{let n=h(e,Tl),r=`${n}.tmp-${se()}`;await p(r,t,`utf8`),await l(r,n)},Ll=async(e,t)=>{await Il(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Rl=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),zl=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),Bl=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=El(e);if(t!==void 0&&Rl.has(t))return!1;throw e}},Vl=async(e,t)=>{try{return await l(e,t),!0}catch(e){let t=El(e);if(t!==void 0&&zl.has(t))return!1;throw e}},Hl=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,Ul=async e=>{let t=await Ml(e);if(t===void 0){let t=await Fl(e);return t!==void 0&&Date.now()-t>5e3}return Date.now()-t.acquiredAtMs>6e5||!Dl(t.pid)},Wl=async(e,t)=>{try{await Ll(e,t)}catch(e){if(El(e)===`ENOENT`)return`retry`;throw e}return t},Gl=async(e,t)=>{if(!await Bl(e))return;let n=await Wl(e,se());return n===`retry`?Date.now()>=t?void 0:Gl(e,t):n},Kl=e=>h(e.locksDir,`${e.name}.steal-claim`),ql=e=>h(e.locksDir,`${e.name}.steal.${se()}`),Jl=async e=>{let t=await Fl(e);return t!==void 0&&Date.now()-t>2e3},Yl=async e=>await Bl(e)?!0:await Jl(e)?(await u(e,{force:!0,recursive:!0}),Bl(e)):!1,Xl=async e=>{let t=ql(e);return await Vl(e.lockPath,t)?t:void 0},Zl=async e=>{if(!await Ul(e.lockPath))return!1;let t=await Xl(e);return t!==void 0&&(await u(t,{force:!0,recursive:!0}),!0)},Ql=async e=>{let t=Kl(e);if(!await Yl(t))return!1;try{return await Zl(e)}finally{await u(t,{force:!0,recursive:!0})}},$l=async(e,t)=>{if(!(await Ul(e.lockPath)&&await Ql(e))){if(Date.now()>=t)throw ve(`lock ${e.name} is held — another refs process is running`);await fe(100)}},eu=async(e,t)=>{let n=await Gl(e.lockPath,t);return n===void 0?(await $l(e,t),eu(e,t)):n},tu=async(e,t)=>{await Pl(e)===t&&await u(e,{force:!0,recursive:!0})},nu=e=>{if(e===`.`||e===`..`||!Hl.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)=>{nu(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 eu(i,o);try{return await n()}finally{await tu(i.lockPath,s)}},ru=ro({directory:I().optional(),url:I().optional()}),iu=ro({repository:ao([I(),ru]).optional()}),au=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,ou=new Set([`node_modules`,`favicon.ico`]),su=e=>y(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),cu=e=>{let[t,n]=e.split(`/`);return n??t??e},lu=e=>{if(e.length>214)throw b(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!au.test(e))throw b(`invalid package name: '${e}' does not match npm naming rules`);let t=cu(e);if(ou.has(t))throw b(`invalid package name: '${e}' uses a reserved name`)},uu=e=>e.replaceAll(`/`,`%2F`),du=e=>typeof e==`string`?e:e?.url,fu=e=>{if(typeof e==`object`&&e?.directory){let t=ns.safeParse(e.directory);if(t.success)return t.data}},pu=async(e,t)=>{try{return await e.json()}catch{throw x(`invalid npm registry response for '${t}': not parseable JSON`)}},mu=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${uu(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 pu(n,t),i=iu.safeParse(r);if(!i.success)throw x(`invalid npm package response for '${t}'`);return i.data},hu=(e,t)=>{try{return pl(e)}catch{throw su(t)}},gu=async(e,t)=>{lu(t);let n=await mu(e,t),r=du(n.repository);if(r===void 0||r===``)throw su(t);let{cloneUrl:i,key:a}=hu(r,t),o=fu(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},_u=new Set;let vu=!1;const yu=()=>{for(let e of _u)try{e.kill(`SIGKILL`)}catch{}},bu=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],xu=e=>{let t=()=>{yu(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},Su=()=>{vu||(vu=!0,bu.forEach(e=>{xu(e)}),process.on(`exit`,yu))},Cu=()=>{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}}},wu=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
349
+ `),Tu=(e,t,n)=>{let r=e;return t.truncated&&(r=wu(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=wu(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},Eu={clear:()=>{},markedTimedOut:()=>!1},Du=(e,t)=>{if(t===void 0)return Eu;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}},Ou=e=>e===void 0?{}:{cwd:e},ku=(e,t)=>wu(e,`refs: command timed out after ${String(t)}ms`),Au=(e,t)=>({exitCode:124,stderr:ku(e,t),stdout:``,timedOut:!0}),ju=(e,t,n)=>{let r=ge(e,t,{...Ou(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});_u.add(r);let i=Cu(),a=Cu();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:Du(r,n?.timeoutMs)}},Mu=(e,t,n)=>{try{return ju(e,t,n)}catch(e){return{exitCode:127,stderr:Pu(e),stdout:``}}},Nu=e=>!(`child`in e),Pu=e=>e instanceof Error?e.message:String(e),Fu=async e=>{try{let[t]=await me(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:Pu(e)}}},Iu=e=>e===null?1:e,Lu=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,Ru=e=>e.timedOut?Au(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Lu({exitCode:Iu(e.code),stderr:Tu(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Lu({exitCode:127,stderr:wu(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var zu=class{async run(e,t,n){Su();let r=Mu(e,t,n);if(Nu(r))return r;let i=await Fu(r.child);return _u.delete(r.child),r.timeout.clear(),Ru({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const Bu=os.partial({description:!0}),Vu=R({default_branch:I().min(1),key:z,tag_format_candidate:ts.nullable(),url:I().min(1)});Vu.extend({description:I().default(``),packages:Vo(Bu)});const Hu=Vu.extend({description:I().min(1),packages:Vo(os)}),Uu=R({effective_clone_mode:$o.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:ia().optional(),pending_proposal_at:ia().optional()}),Wu=R({refs:zo(e=>e.length>0&&!Ro.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,lo(I(),Uu)).default({})}),Y=(e,t,n)=>t?.[e]??n[e],Gu=async e=>{try{return await o(e.statePath,`utf8`)}catch(e){if(V(e))return;throw e}},Ku=e=>{try{return JSON.parse(e)}catch{return}},X=async e=>{let t=await Gu(e);if(t===void 0)return Wu.parse({});let n=Ku(t);if(n===void 0)return Wu.parse({});let r=Wu.safeParse(n);return r.success?r.data:Wu.parse({})},qu=async(e,t)=>{let n=Wu.safeParse(t);if(!n.success)throw x(O(n.error));await Bs(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},Ju=/[/\\]/u,Yu={kind:`ignore`},Xu=e=>!ne(e)&&e.split(Ju).every(e=>e!==`.`&&e!==`..`),Zu=e=>Xu(e)&&!e.startsWith(`!`)&&!e.includes(`**`)&&(e.match(/\*/gu)??[]).length<=1,Qu=e=>Zu(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`}:e===`*`?{baseDir:`.`,kind:`expand-children`}:e.includes(`*`)?Yu:{dir:e,kind:`probe-dir`}:Yu,$u=(e,t)=>{if(t&&e===``)return!0;let n=e===`..`||e.startsWith(`..`+oe);return e!==``&&!n&&!ne(e)},ed=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>re.join(e,t)),td=(e,t)=>t?.name?{description:t.description,name:t.name,path:e}:void 0,nd=e=>{let t=e.map(e=>[e.path,e]),n=[...new Map(t).values()];return n.sort((e,t)=>e.path.localeCompare(t.path)),n},rd=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,id=/^packages:\s*(?:#.*)?$/u,ad=e=>typeof e==`object`&&!!e&&!Array.isArray(e),od=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!ad(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},sd=Symbol(`end-of-section`),cd=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!id.test(e))return sd;if(!t.startsWith(`-`))return;let n=rd.exec(e)?.groups?.pattern?.trim();if(n)return n},ld=e=>{let t=[];for(let n of e){let e=cd(n);if(e===sd)break;e!==void 0&&t.push(e)}return t},ud=e=>{let t=e.findIndex(e=>id.test(e));return t===-1?[]:ld(e.slice(t+1))},dd=e=>{let{name:t}=e;if(typeof t==`string`)return t},fd=e=>{let{description:t}=e;if(typeof t==`string`)return t},pd=async(e,t,n=!1)=>{try{let r=await c(e),i=await c(t);return $u(ie(r,i),n)}catch{return!1}},md=async(e,t)=>{try{let n=h(t,`package.json`);return await pd(e,n)?(await o(n,`utf8`),!0):!1}catch{return!1}},hd=async(e,t)=>{try{let n=h(e,t);if(!await pd(e,n,t===`.`))return[];let r=(await s(n,{withFileTypes:!0})).filter(e=>e.isDirectory()),i=await Promise.all(r.map(t=>md(e,h(n,t.name))));return ed(t,r.map(e=>e.name),i)}catch{return[]}},gd=async(e,t)=>{let n=Qu(t);if(n.kind===`expand-children`)return hd(e,n.baseDir);if(n.kind===`probe-dir`){let t=h(e,n.dir);if(await pd(e,t)&&await md(e,t))return[n.dir]}return[]},_d=async(e,t)=>{try{let n=h(t,`package.json`);if(!await pd(e,n))return;let r=await o(n,`utf8`),i=JSON.parse(r);return{description:fd(i),name:dd(i)}}catch{return}},vd=async(e,t)=>{let n=new Set;try{if(!await pd(e,t))return n;let r=await o(t,`utf8`),i=JSON.parse(r);od(i.workspaces).forEach(e=>n.add(e))}catch{}return n},yd=async(e,t)=>{let n=new Set;try{if(!await pd(e,t))return n;let r=await o(t,`utf8`);ud(r.split(`
350
+ `)).forEach(e=>n.add(e))}catch{}return n},bd=async(e,t)=>{let n=new Set,r=[...t].map(t=>gd(e,t));return(await Promise.all(r)).forEach(e=>{e.forEach(e=>n.add(e))}),n},xd=async(e,t)=>{let n=h(e,t);if(await pd(e,n))return td(t,await _d(e,n))},Sd=async(e,t)=>{let n=[...t].map(t=>xd(e,t));return(await Promise.all(n)).filter(e=>e!==void 0)},Cd=async e=>{let t=h(e,`package.json`),n=h(e,`pnpm-workspace.yaml`),r=await vd(e,t),i=await yd(e,n),a=new Set([...r,...i]);if(a.size===0)return[];let o=await bd(e,a),s=await Sd(e,o);return nd(s)};var wd=`0.8.2`;const Td=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Ed=()=>{try{return de()}catch{return``}},Dd=()=>({cliVersion:wd,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:e=>fetch(e),homedir:Ed(),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:Td,runner:new zu});var Od=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}},kd=class extends Od{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},Ad=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 kd(`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 jd(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var Md=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=>jd(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
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,`
352
352
  `+` `.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
- `)}},jd=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=Pd(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 Dd(`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?Nd(this.name().replace(/^no-/,``)):Nd(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}},Md=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 Nd(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Pd(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}
353
+ `)}},Nd=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=Id(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 kd(`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?Fd(this.name().replace(/^no-/,``)):Fd(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}},Pd=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 Fd(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Id(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
354
  - a short flag is a single dash and a single character
355
355
  - either use a single dash and a single character (for a short flag)
356
356
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
357
357
  - too many short flags`):i.test(t)?Error(`${n}
358
358
  - 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 Fd(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 Id(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=Fd(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 Ld=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:()=>zd()??(g.stdout.isTTY&&g.stdout.hasColors?.()),getErrHasColors:()=>zd()??(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 Ad,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 Od(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
361
- Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Ed(e,t,n)),g.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new jd(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 jd)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.
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 Ld(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 Rd(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=Ld(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 zd=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:()=>Vd()??(g.stdout.isTTY&&g.stdout.hasColors?.()),getErrHasColors:()=>Vd()??(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 Md,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 Ad(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 Od(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 Nd(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 Nd)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
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
364
364
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
365
365
  - 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=Rd(g.execArgv).concat(t),s=he.spawn(g.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=Rd(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 Ed(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 Ed(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}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
367
- `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in 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 Md(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=Id(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=Id(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=>kd(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 Rd(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 zd(){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 Ld;const Bd=[],Vd=e=>Array.isArray(e)?e:[e],Hd=e=>e===void 0?Bd:[e],Ud=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??Bd};e.out(JSON.stringify(t));return}for(let t of Vd(n))e.out(t);for(let t of i??Bd)e.errLine(`refs: warning: ${t}`)},Wd=(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}`)},Gd=(e,t)=>{e.errLine(`refs: ${t}`)},$=(e,t,n)=>async()=>{try{await n()}catch(n){let r=be(n,{verbose:t.verbose});Wd(e,t,r),process.exitCode=r.exitCode}},Kd=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`}},qd=/^v(?<major>\d+)\.(?<minor>\d+)/u,Jd=e=>{let t=qd.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},Yd=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,Xd=e=>{let{nodeVersion:t}=e;return Yd(Jd(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},Zd=()=>cs.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),Qd=async e=>{try{return{config:await W(e)}}catch(e){return{config:Zd(),errorMessage:Ud(e)}}},$d=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},ef=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),tf=[`pre-commit`,`pre-push`],nf=async(t,r)=>{try{return await e(h(t.hooksDir,r),n.X_OK),!0}catch{return!1}},rf=async e=>{let t=await Promise.all(tf.map(t=>nf(e,t)));return tf.filter((e,n)=>!t[n])},af=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},of=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:`${tf.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},sf=async(e,t,n)=>{let r=ef(t,n),[i,a]=await Promise.all([rf(t),Promise.all(r.map(n=>af(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return of({badKeys:o,checkoutCount:r.length,missingHooks:i})},cf=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}},lf=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=ef(t,n),i=await Promise.all(r.map(t=>cf(e,t)));return lf(i)},df=async e=>{try{return await X(e)}catch{return Uu.parse({})}},ff=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}},pf=async(e,t)=>{if(G(e))return[[...t]];let n=await ff(e);return(await Promise.all(n.map(n=>pf(h(e,n),[...t,n])))).flat()},mf=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},hf=(e,t,n)=>mf(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,gf=(e,t)=>({dest:h(e.sourcesDir,...t),key:t.join(`/`)}),_f=async(e,t,n)=>{let r=(await pf(e.sourcesDir,[])).map(t=>gf(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=>hf(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},vf=[`.agents`,`skills`,`refs`,`SKILL.md`],yf=[`skills`,`refs`,`SKILL.md`],bf=[`.claude`,`skills`,`refs`,`SKILL.md`],xf=`npx skills add kaisers-io/refs`,Sf=`npm i -g @kaisers-io/refs@latest`,Cf=(e,t)=>e===void 0?void 0:{display:t,path:e},wf=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}:Cf(r===void 0?void 0:h(r,t),`~/${t}`)},Tf=e=>{let t=e.env.HOME;return[{label:`shared ~/.agents`,root:Cf(t,`~/.agents`),segments:vf},{label:`Claude Code`,root:wf({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:yf},{label:`Codex`,root:wf({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:yf},{label:`project ./.agents`,root:Cf(e.cwd,`./.agents`),segments:vf},{label:`project ./.claude`,root:Cf(e.cwd,`./.claude`),segments:bf}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:h(t.path,...n)}])},Ef=async(e,t)=>{try{let n=await c(e);return{label:t,realPath:n,source:await o(n,`utf8`)}}catch{return}},Df=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Of=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,kf=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,Af=e=>{let t=Of.exec(e)?.groups?.body;if(t!==void 0)return kf.exec(t)?.groups?.version},jf=/^\d+\.\d+\.\d+$/u,Mf=e=>{if(jf.test(e))return e.split(`.`).map(Number)},Nf=(e,t)=>{if(e===t)return`match`;let n=Mf(e),r=Mf(t);if(n===void 0||r===void 0)return`unknown`;let i=n.findIndex((e,t)=>e!==r[t]);return i===-1?`match`:(n[i]??0)>(r[i]??0)?`cli-older`:`skill-older`},Pf={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${Sf}`,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: ${xf}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${Sf} and ${xf}`},Ff=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: ${xf}`,name:`skill`,status:`warn`};let i=Nf(r,t);return{detail:`${n}: ${Pf[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},If=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: ${xf}`,name:`skill`,status:`warn`}),Lf=async e=>{let t=Tf(e),n=await Promise.all(t.map(e=>Ef(e.path,e.label))),r=Df(n.filter(e=>e!==void 0)).map(t=>Ff({cliVersion:e.cliVersion,label:t.label,skillVersion:Af(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??If(t)},Rf=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,zf=e=>e===``?{}:{user:e},Bf=e=>e===``?{}:{port:e},Vf=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...zf(t.username),...Bf(t.port)}:void 0}catch{return}},Hf=e=>{let t=Rf.exec(e),n=t?.groups?.host;return n===void 0?Vf(e):{host:n,user:t?.groups?.user??`git`}},Uf=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,Wf=e=>e.user===void 0?Uf(e):`${e.user}@${Uf(e)}`,Gf=e=>{let t=Object.values(e.refs).map(e=>Hf(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(Wf(e),e);return[...n.values()].toSorted((e,t)=>Wf(e).localeCompare(Wf(t)))},Kf=/Permission denied/u,qf=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Jf=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,Yf=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Jf(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},Xf=async(e,t,n)=>{let r=Wf(t),i=await e.runner.run(`ssh`,Yf(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:Kf.test(i.stderr)?{host:r,outcome:`denied`}:qf.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},Zf=(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`}},Qf=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`}},$f=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`}},ep=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),tp=(e,t)=>Zf(e,t)??Qf(e)??$f(e)??ep(e),np=async(e,t,n)=>{let r=Gf(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>Xf(e,t,i)));return tp(a,i)},rp=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${Ud(t)}`,name:e.name,status:`fail`}}},ip=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await rp(t),i=await ip(n);return r===void 0?i:[r,...i]},ap=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Kd(n)},{name:`node`,run:()=>Promise.resolve(Xd(n))},{name:`config`,run:()=>Promise.resolve($d(t.errorMessage))},{name:`hooks-guard`,run:()=>sf(n,r,t.config)},{name:`dirty-checkouts`,run:()=>uf(n,r,t.config)},{name:`orphans`,run:()=>_f(r,t.config,i)},{name:`skill`,run:()=>Lf(n)},{name:`ssh-auth`,run:()=>np(n,t.config)}]},op=async e=>{let t=H(e.env),n=await Qd(t),r=await df(t);return ip(ap({configLoad:n,ctx:e,home:t,state:r}))},sp={fail:`FAIL`,ok:`OK`,warn:`WARN`},cp=e=>e.map(e=>`[${sp[e.status]}] ${e.name}: ${e.detail}`),lp=e=>e.some(e=>e.status===`fail`),up=(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 op(t);Q(t,r,cp(e),{checks:e}),lp(e)&&(process.exitCode=_.UNEXPECTED)})()})},dp=async e=>{let t=H(e.env),n=await J(t,`home`,()=>lc(t,Cd));return n===`migrated`?{backup:Vs(t),result:n}:{backup:null,result:n}},fp=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${ee(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,pp=(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 dp(t);Q(t,r,fp(e),e)})()})},mp=`never`,hp=(e,t,n)=>e===void 0||n-Date.parse(e)>t,gp=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,_p=(e,t)=>{if(e===void 0)return mp;let n=t-Date.parse(e);if(Number.isNaN(n))return mp;let r=Math.floor(n/1e3);if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return gp(i,`minute`);let a=Math.floor(i/60);if(a<24)return gp(a,`hour`);let o=Math.floor(a/24);return o<365?gp(o,`day`):gp(Math.floor(o/365),`year`)},vp=e=>{let t=_p(e.lastFetchedAt,e.now),n=[`synced: ${t}`];return e.stale&&t!==mp&&n.push(`status: stale`),e.missing&&n.push(`missing: checkout not found — run: refs sync`),n},yp=(e,t,n)=>{let r=e.state.refs[t],i=Qo(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:hp(r?.last_fetched_at,i,e.now)}},bp=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])=>yp(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},xp=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=await X(r);return bp({config:i,home:r,includePackages:t,now:n,state:a})},Sp=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...vp({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],Cp=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...Sp(n,t)),e),[]),wp=e=>e.split(`/`),Tp=(e,t)=>{let n=wp(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Ep=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=wp(t),r=Object.keys(e.refs).filter(e=>Tp(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)},Dp=(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 xp(t,e.packages===!0,n);Q(t,r,Cp(i,n),i)})()})},Op=e=>`ref.${e.replaceAll(`/`,`_`)}`,kp=e=>e.REFS_ALLOW_FILE_URLS===`1`,Ap=(e,t)=>{let n=dl(t,{allowFileUrls:kp(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},jp=async(e,t)=>{if(t===``)throw b(`refs add npm: requires a package name, e.g. npm:left-pad`);Gd(e,`resolving npm package '${t}'…`);let n=await hu(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},Mp=(e,t)=>t.startsWith(`npm:`)?jp(e,t.slice(4)):Promise.resolve(Ap(e,t)),Np=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Y(`git_transport`,void 0,t);return{...e,cloneUrl:Cl(e.cloneUrl,n)}},Pp=e=>`ref '${e}' already exists — use refs edit or refs remove`,Fp=(e,t)=>{if(e.refs[t]!==void 0)throw ve(Pp(t))},Ip=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},Lp=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),Rp=async(e,t)=>{let n=await Ip(e);if(n===void 0)return{kind:`stop`};let r=Lp(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}},zp=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await Rp(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):zp(a.nextDir,i,[...n,r])},Bp=[],Vp=async(e,t)=>{let n=await zp(e.sourcesDir,t.split(`/`),Bp);if(n!==void 0)throw ve(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},Hp=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},Up=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},Wp=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},Gp=async e=>{let t=await Up(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},Kp=async e=>{let t=await Wp(e);return t===void 0?!0:t?Gp(e):!1},qp=async(e,t)=>{t!==e.sourcesDir&&await Kp(t)&&await qp(e,te(t))},Jp=async(e,t)=>await Hp(t)?(Gs(e,t),await u(t,{force:!0,recursive:!0}),await qp(e,te(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},Yp=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),Xp=async(e,t)=>{let n=await W(e);await $s(e,{...n,refs:Yp(n.refs,t)});let r=await X(e);await Ku(e,{...r,refs:Yp(r.refs,t)})},Zp=async(e,t)=>{let n=H(e.env),r=Ep(await W(n),t),i=U(n,r),{removedCheckout:a,warning:o}=await J(n,Op(r),()=>Jp(n,i));return await J(n,`home`,()=>Xp(n,r)),{data:{key:r,removed_checkout:a},warnings:Hd(o)}},Qp=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],$p=(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 Zp(t,e);Q(t,i,Qp(n),n,r)})()})},em=(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},tm=(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},rm=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,im=/^[a-z][a-z0-9+.-]*:\/\//iu,am=/^git@[^:/\s]+:[^\s]+$/u,om=e=>im.test(e)||am.test(e),sm=(e,t)=>{try{return dl(e,t)}catch{if(om(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}},cm=(e,t,n)=>{let r=sm(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw y(rm(t))}},lm=(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},um=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,dm=(e,t)=>{let n=lm(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw b(um(t,n.map(e=>e.key)));return r}},fm=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=dm(e,r);if(i!==void 0)return{...i,name:r}}},pm=(e,t)=>{try{return Ep(e,t)}catch(e){throw e instanceof v&&e.code===`not_found`?y(rm(t)):e}},mm=(e,t,n)=>{let r=cm(e,t,n);if(r!==void 0)return r;let i=dm(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=fm(e,t);return a===void 0?{key:pm(e,t)}:{key:a.key,packageMatch:a}},hm=(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}},gm=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=mm(i,t,{allowFileUrls:kp(e.env)}),o=em(i,a.key),s=await X(r),c=U(r,a.key),l=Qo(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:hm(a,c),stale:hp(u,l,n)}},_m=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...vp({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},vm=(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 gm(t,e,n);Q(t,i,_m(r,n),r)})()})},ym={},bm=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await kc(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${Ud(e)}`}}},xm=async(e,t,n,r)=>{let i=H(e.env),a=await W(i),o=Ep(a,t),s=em(a,o),c=await X(i),l=U(i,o),{packages:u,...d}=s,f=n.tags?await bm(e,l):void 0,p=c.refs[o]??ym;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:hp(p.last_fetched_at,Qo(Y(`sync_ttl`,s,a.settings)),r),state:p},warnings:Hd(f?.warning)}},Sm=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...vp({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},Cm=(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 xm(t,e,r,a);Q(t,i,Sm(o,a),o,s)})()})},wm=(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},Tm=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await $s(e,r))},Em=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Tm(e,t,n.branchRenamedTo);let r=await X(e);r.refs[t]=wm(r.refs[t],n),await Ku(e,r)}),Dm=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 Ku(e,r)})}catch{}},Om=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()}}},km=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Am=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,jm=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,Mm=(e,t)=>{try{return dl(e,{allowFileUrls:t}).key}catch{return}},Nm=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=jm(n),i=Mm(t.expectedUrl,t.allowFileUrls),a=Mm(r,t.allowFileUrls);if(i===void 0||a!==i)throw ve(Am(t.dest,r,t.expectedUrl))},Pm=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,Fm=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(Pm(t.dest))},Im=async(e,t)=>{await a(te(t.dest),{recursive:!0}),Gd(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await bc(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},Lm=async(e,t)=>(Gs(t.home,t.dest),G(t.dest)?(await Nm(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await Fm(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Im(e,t)),Rm=(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`,zm=(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`,Bm=async(e,t)=>{await Nm(e,t),await Fm(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(Rm(t.key,t.dest));let r=n.stdout.trim();if(!Hu.shape.head_sha.safeParse(r).success)throw x(zm(t.key,t.dest,r));return r},Vm=(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`,Hm=(e,t,n)=>{if(!Hu.shape.head_sha.safeParse(n).success)throw x(Vm(e,t,n));return n},Um=(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},Wm=async(e,t,n)=>{await a(te(n),{recursive:!0});let r=Y(`clone_mode`,t.ref,t.settings),i=await bc(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Sc(e.runner,n),s=await Bm(e.runner,{allowFileUrls:kp(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return Um(t,i,{actualBranch:o,headSha:s})},Gm=async(e,t,n)=>{await Fm(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await Nm(e.runner,{allowFileUrls:kp(e.env),dest:n,expectedUrl:t.ref.url});let r=await Oc(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Hm(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},Km=(e,t)=>J(t.home,Op(t.key),()=>{let n=U(t.home,t.key);return Gs(t.home,n),G(n)?Gm(e,t,n):Wm(e,t,n)}),qm=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(` | `)},Jm=(e,t)=>{let n={key:e,status:t.status},r=qm(t);return r!==void 0&&(n.warning=r),n},Ym=async(e,t)=>{try{let n=await Km(e,t);return await Em(t.home,t.key,n),Jm(t.key,n)}catch(e){let n=Ud(e);return await Dm(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},Xm=(e,t)=>e.status===`rejected`?{error:Ud(e.reason),key:t,status:`failed`}:e.value,Zm=async(e,t)=>{let n=Om(4);return(await Promise.allSettled(t.map(t=>km(n,()=>Ym(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return Xm(e,r.key)})},Qm=(e,t,n)=>({home:e,key:n,ref:em(t,n),settings:t.settings}),$m=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>Qm(e,t,z.parse(n))):n.map(n=>Qm(e,t,Ep(t,n))),eh=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=Qo(Y(`sync_ttl`,t.ref,t.settings)),a=hp(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},th=async(e,t,n)=>{if(!n)return t;let r=await X(e);return eh(e,t,r)},nh=async(e,t)=>{let n=H(e.env),r=await W(n),i=$m(n,r,t.refs),a=await Zm(e,await th(n,i,t.staleOnly));return{failedCount:a.filter(e=>e.status===`failed`).length,results:a}},rh=[`updated`,`fresh`,`cloned`,`restored`,`failed`],ih={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},ah=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},oh=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,sh=e=>{let t=ah(e),n=[rh.map(e=>`${ih[e]} (${t[e].length})`).join(` / `)];for(let e of rh)for(let r of t[e])n.push(oh(r));return n},ch=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),lh=(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 nh(t,ch(e,n));Q(t,i,sh(r.results),{results:r.results}),r.failedCount>0&&(process.exitCode=_.UNEXPECTED)})()})},uh=(e,t,n)=>n===void 0?e.tag_format:nm(e,t,n).tag_format??e.tag_format,dh=async(e,t)=>{let n=H(e.env),r=await W(n),i=Ep(r,t.query),a=em(r,i),o=uh(a,i,t.opts.packageName),s=U(n,i);tm(s,i);let c=await Wc(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},fh=e=>[`${e.key}@${e.version} -> ${e.tag}`],ph=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},mh=[up,pp,$p,vm,Cm,lh,(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 dh(t,{opts:ph(r),query:e,version:n});Q(t,a,fh(i),i)})()})}],hh=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},gh=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,hh(e)])):n===void 0?{}:{[n]:{path:t??`.`}},_h=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}},vh=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,_h(t)]))},yh=e=>e.description===void 0||e.description===``,bh=e=>Object.entries(e).filter(([,e])=>yh(e)).map(([e])=>e).toSorted(),xh=e=>{let t=bh(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`)},Sh=e=>{if(Object.keys(e).length!==0)return e},Ch=e=>{if(e===null)throw x(`tag_format_candidate must be set to a valid tag format (containing '{version}') before finalizing — edit the proposal and provide one, or add the ref manually`);return e},wh=e=>e.packages===void 0?{default_branch:e.default_branch,description:e.description,tag_format:e.tag_format,url:e.url}:{default_branch:e.default_branch,description:e.description,packages:e.packages,tag_format:e.tag_format,url:e.url},Th=async(e,t,n)=>{let r=await Sc(e.runner,t),i=Hc(await kc(e.runner,t));return Gd(e,`detecting workspace packages…`),{defaultBranch:r,packages:gh(await Sd(t),n.npmDirectory,n.npmPkgName),tagFormatCandidate:i}},Eh=(e,t)=>J(t.home,Op(t.resolved.key),async()=>{let n=await Lm(e,{allowFileUrls:kp(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await Th(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),Dh=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},Oh=async(e,t)=>{let n=H(e.env),r=await W(n),i=Np(await Mp(e,t),r.settings);Fp(r,i.key),await Vp(n,i.key);let a=U(n,i.key),o=Y(`clone_mode`,void 0,r.settings),s=await Eh(e,{cloneMode:o,dest:a,home:n,resolved:i});return Dh({cloneResult:s,dest:a,resolved:i})},kh=(e,t,n)=>J(e,`home`,async()=>{Fp(await W(e),t);let r=await X(e),i=r.refs[t],a=n??i?.effective_clone_mode,o={...i,pending_proposal_at:new Date().toISOString()};a!==void 0&&(o.effective_clone_mode=a),r.refs[t]=o,await Ku(e,r)}),Ah=(e,t)=>{let n=cs.safeParse(e);if(!n.success)throw x(k(n.error));let r=Uu.safeParse(t);if(!r.success)throw x(k(r.error));return{config:n.data,state:r.data}},jh=async(e,t)=>{let n=await W(e.home);Fp(n,e.ref.key);let r=wh(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()},{...Ah(n,i),entry:r}},Mh=async(e,t)=>{let n=kp(e.env),r=await J(t.home,Op(t.ref.key),()=>(Gs(t.home,t.dest),Bm(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 jh(t,r);return await Ku(t.home,i),await $s(t.home,e),{entry:n,key:t.ref.key}})},Nh=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),Ph=e=>{try{return JSON.parse(e)}catch(e){throw x(`invalid JSON in proposal: ${Ud(e)}`)}},Fh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ih=e=>Fh(e)&&`ok`in e&&!(`key`in e),Lh=e=>{if(!Ih(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(Fh(e.data))return e.data;throw x(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},Rh=e=>e.code===`unrecognized_keys`,zh=e=>e.path.length===0,Bh=(e,t)=>{let n=t.toSorted().map(e=>`"${e}"`).join(`, `);return e===``?`✖ unrecognized key(s) in proposal: ${n}`:`✖ unrecognized key(s) in proposal at ${e}: ${n}`},Vh=e=>{let t=new Map;for(let n of e){let e=ct(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Bh(e,t))},Hh=e=>`✖ invalid proposal: ${e.message}`,Uh=e=>{let t=e.issues.filter(e=>Rh(e)),n=e.issues.filter(e=>!Rh(e)),r=n.filter(e=>zh(e));if(t.length===0&&r.length===0)return k(e);let i=n.filter(e=>!zh(e)),a=[...Vh(t),...r.map(e=>Hh(e))];return i.length>0&&a.push(k({issues:i})),a.join(`
369
- `)},Wh=e=>{let t=Vu.safeParse(e);if(!t.success)throw x(Uh(t.error));return t.data},Gh=async(e,t)=>{let n=await Nh(e,t);return Wh(Lh(Ph(n)))},Kh=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],qh=async(e,t)=>{let n=await Oh(e,t);await kh(H(e.env),n.proposal.key,n.effectiveCloneMode);let r=Hd(n.warning);return{data:n.proposal,human:Kh(n.proposal.key,n.dest),warnings:r}},Jh=e=>[`refs add: '${e}' added to config`],Yh=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,tag_format:Ch(e.tag_format_candidate),url:e.url},n=Sh(e.packages);return n!==void 0&&(t.packages=n),t},Xh=async(e,t)=>{let n=await Gh(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{entry:a,key:o}=await Mh(e,{dest:i,home:r,ref:Yh(n)});return{data:{entry:a,key:o},human:Jh(o),warnings:[]}},Zh=(e,t)=>{xh(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,tag_format:Ch(e.proposal.tag_format_candidate),url:e.proposal.url},r=vh(e.proposal.packages);return r!==void 0&&(n.packages=r),n},Qh=async(e,t,n)=>{let r=await Oh(e,t),i=H(e.env),a=Zh(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await Mh(e,o),l=Hd(r.warning);return{data:{entry:s,key:c},human:Jh(c),warnings:l}},$h=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`)},eg=e=>{if(e===void 0||e===``)throw b(`refs add requires <source> (a git url or npm:<package>)`);return e},tg=(e,t)=>($h(t),t.proposal===void 0?t.description===void 0?qh(e,eg(t.source)):Qh(e,eg(t.source),t.description):Xh(e,t.proposal)),ng=(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},rg=(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 tg(t,ng(e,n));Q(t,i,r.human,r.data,r.warnings)})()})},ig=e=>e===void 0?null:e,ag=()=>Object.keys(os.shape).toSorted().join(`, `),og=e=>`unknown package field '${e}' — valid fields: ${ag()}`,sg=e=>Object.hasOwn(os.shape,e),cg=(e,t,n)=>{if(!sg(t))throw b(og(t));let r=e[t],i=os.safeParse({...e,[t]:n});if(!i.success)throw x(k(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},lg=async e=>{let t=nm(e.entry,e.key,e.packageName),n=cg(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await $s(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:ig(n.newValue),old:ig(n.oldValue)}},ug=`packages`,dg=()=>Object.keys(ss.shape).filter(e=>e!==ug).toSorted().join(`, `),fg=e=>`unknown ref field '${e}' — valid fields: ${dg()}`,pg=e=>Object.hasOwn(ss.shape,e),mg=(e,t,n)=>`failed to rewrite git remote at ${e} to '${q(t)}': ${n.trim()}`,hg=async(e,t)=>{if(Gs(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(mg(t.dest,t.cloneUrl,n.stderr))},gg=async(e,t)=>{let n=dl(t.value,{allowFileUrls:kp(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 hg(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},_g=(e,t,n)=>{let r={...e,[t]:n},i=ss.safeParse(r);if(!i.success)throw x(k(i.error));return i.data},vg=(e,t)=>t.field===`url`?gg(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(_g(t.entry,t.field,t.value)),yg=async(e,t)=>{let{field:n}=t;if(n===ug)throw b(`use --package <name> <field> <value>`);if(!pg(n))throw b(fg(n));let r=t.entry[n],i=await vg(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},bg=(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=Ep(t,a),c=em(t,s);if(i.packageName!==void 0)return lg({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await yg(e,{entry:c,field:r,home:n,key:s,value:o});return await $s(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:ig(l.new),old:ig(l.old)}})},xg=`settings`,Sg=[],Cg=()=>Object.keys(is.shape).toSorted().join(`, `),wg=e=>`unknown setting '${e}' — valid settings: ${Cg()}`,Tg=e=>Object.hasOwn(is.shape,e),Eg=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,Dg=e=>{try{let t=Ep(e,xg);return[Eg(`ref '${t}'`)]}catch(e){if(e instanceof v&&e.code===`usage`)return[Eg("one of several matching refs — see `refs list`")];if(e instanceof v&&e.code===`not_found`)return Sg;throw e}},Og=e=>({data:{field:e.key,key:xg,new:ig(e.parsed[e.key]),old:ig(e.old)},warnings:Dg(e.config)}),kg=(e,t)=>{let n=H(e.env);return J(n,`home`,async()=>{let e=await W(n);if(!Tg(t.key))throw b(wg(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=is.safeParse(i);if(!a.success)throw x(k(a.error));return await $s(n,{...e,settings:a.data}),Og({config:e,key:t.key,old:r,parsed:a.data})})},Ag=[],jg=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Mg=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 kg(e,{key:t.second,value:t.value})}return{data:await bg(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:Ag}},Ng=e=>e==null?`(unset)`:String(e),Pg=e=>[`${e.key}: ${e.field} '${Ng(e.old)}' -> '${Ng(e.new)}'`],Fg=(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 Mg(t,{first:e,opts:jg(i),second:n,value:r});Q(t,o,Pg(a),a,s)})()})},Ig=`Install the agent skill: npx skills add kaisers-io/refs (private phase: npx skills add <path-to-this-repo> --skill refs)`,Lg={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},Rg=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})},zg=async e=>{let t=H(e.env);return await Rg(t),{config:await J(t,`home`,async()=>{let e=await lc(t,Cd);return await Mc(t),e}),home:t.root,skill_hint:Ig}},Bg=[(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 zg(t);Q(t,r,[`home: ${e.home}`,`config: ${Lg[e.config]}`,``,Ig],e)})()})},rg,Fg,Dp,...mh],Vg=(e,t)=>{for(let n of Bg)n(e,t)},Hg=[``,`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
- `),Ug=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),Wg=`--json`,Gg=`--verbose`,Kg=/\n$/u,qg=/^error: /u,Jg=e=>e.replace(qg,``),Yg=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},Xg=e=>Yg(e,Wg),Zg=e=>Yg(e,Gg),Qg=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,$g=e=>{let t=new Ld().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(Cd).option(Wg,`emit machine-readable JSON on stdout instead of human-readable text`).option(Gg,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(Kg,``))},writeOut:t=>{e.out(t.replace(Kg,``))}});return t.addHelpText(`after`,Hg),Vg(t,e),t},e_=()=>{process.exitCode=_.OK},t_=(e,t,n)=>{Wd(e,t,{code:`usage`,message:Qg(Jg(n.message),n.stack,t.verbose)}),process.exitCode=_.USAGE},n_=(e,t,n)=>{if(Ug.has(n.code)){e_();return}t_(e,t,n)},r_=(e,t,n)=>{let r=be(n,{verbose:t.verbose});Wd(e,t,r),process.exitCode=r.exitCode},i_=async(e,t,n)=>{let r={json:Xg(n),verbose:Zg(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof Ed){n_(e,r,t);return}r_(e,r,t)}},a_=(e,t)=>i_(e,$g(e),t);import.meta.main&&await a_(Td(),process.argv);export{$g as buildProgram,Z as cliOptsOf,Q as emit,Wd as emitError,Ud as errorMessageOf,Gd as progress,Td as realContext,Vg as registerCommands,a_ as run,i_ as runProgram,Hd as warningsFor,$ as wrapAction};
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=Bd(g.execArgv).concat(t),s=he.spawn(g.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=Bd(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 Od(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 Od(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 Pd(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=Rd(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=Rd(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=>jd(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 Bd(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 Vd(){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 zd;const Hd=[],Ud=e=>Array.isArray(e)?e:[e],Wd=e=>e===void 0?Hd:[e],Gd=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??Hd};e.out(JSON.stringify(t));return}for(let t of Ud(n))e.out(t);for(let t of i??Hd)e.errLine(`refs: warning: ${t}`)},Kd=(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}`)},qd=(e,t)=>{e.errLine(`refs: ${t}`)},$=(e,t,n)=>async()=>{try{await n()}catch(n){let r=be(n,{verbose:t.verbose});Kd(e,t,r),process.exitCode=r.exitCode}},Jd=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`}},Yd=/^v(?<major>\d+)\.(?<minor>\d+)/u,Xd=e=>{let t=Yd.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},Zd=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=2,Qd=e=>{let{nodeVersion:t}=e;return Zd(Xd(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.2`,name:`node`,status:`fail`}},$d=()=>cs.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),ef=async e=>{try{return{config:await W(e)}}catch(e){return{config:$d(),errorMessage:Gd(e)}}},tf=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},nf=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),rf=[`pre-commit`,`pre-push`],af=async(t,r)=>{try{return await e(h(t.hooksDir,r),n.X_OK),!0}catch{return!1}},of=async e=>{let t=await Promise.all(rf.map(t=>af(e,t)));return rf.filter((e,n)=>!t[n])},sf=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},cf=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:`${rf.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},lf=async(e,t,n)=>{let r=nf(t,n),[i,a]=await Promise.all([of(t),Promise.all(r.map(n=>sf(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return cf({badKeys:o,checkoutCount:r.length,missingHooks:i})},uf=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}},df=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`}},ff=async(e,t,n)=>{let r=nf(t,n),i=await Promise.all(r.map(t=>uf(e,t)));return df(i)},pf=async e=>{try{return await X(e)}catch{return Wu.parse({})}},mf=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}},hf=async(e,t)=>{if(G(e))return[[...t]];let n=await mf(e);return(await Promise.all(n.map(n=>hf(h(e,n),[...t,n])))).flat()},gf=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},_f=(e,t,n)=>gf(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,vf=(e,t)=>({dest:h(e.sourcesDir,...t),key:t.join(`/`)}),yf=async(e,t,n)=>{let r=(await hf(e.sourcesDir,[])).map(t=>vf(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=>_f(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},bf=[`.agents`,`skills`,`refs`,`SKILL.md`],xf=[`skills`,`refs`,`SKILL.md`],Sf=[`.claude`,`skills`,`refs`,`SKILL.md`],Cf=`npx skills add kaisers-io/refs`,wf=`npm i -g @kaisers-io/refs@latest`,Tf=(e,t)=>e===void 0?void 0:{display:t,path:e},Ef=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}:Tf(r===void 0?void 0:h(r,t),`~/${t}`)},Df=e=>{let t=e.homedir.length>0?e.homedir:void 0;return[{label:`shared ~/.agents`,root:Tf(t,`~/.agents`),segments:bf},{label:`Claude Code`,root:Ef({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:xf},{label:`Codex`,root:Ef({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:xf},{label:`project ./.agents`,root:Tf(e.cwd,`./.agents`),segments:bf},{label:`project ./.claude`,root:Tf(e.cwd,`./.claude`),segments:Sf}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:h(t.path,...n)}])},Of=async(e,t)=>{try{let n=await c(e);return{label:t,realPath:n,source:await o(n,`utf8`)}}catch{return}},kf=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Af=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,jf=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,Mf=e=>{let t=Af.exec(e)?.groups?.body;if(t!==void 0)return jf.exec(t)?.groups?.version},Nf=/^\d+\.\d+\.\d+$/u,Pf=e=>{if(Nf.test(e))return e.split(`.`).map(Number)},Ff=(e,t)=>{if(e===t)return`match`;let n=Pf(e),r=Pf(t);if(n===void 0||r===void 0)return`unknown`;let i=n.findIndex((e,t)=>e!==r[t]);return i===-1?`match`:(n[i]??0)>(r[i]??0)?`cli-older`:`skill-older`},If={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${wf}`,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: ${Cf}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${wf} and ${Cf}`},Lf=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: ${Cf}`,name:`skill`,status:`warn`};let i=Ff(r,t);return{detail:`${n}: ${If[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},Rf=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: ${Cf}`,name:`skill`,status:`warn`}),zf=async e=>{let t=Df(e),n=await Promise.all(t.map(e=>Of(e.path,e.label))),r=kf(n.filter(e=>e!==void 0)).map(t=>Lf({cliVersion:e.cliVersion,label:t.label,skillVersion:Mf(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??Rf(t)},Bf=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,Vf=e=>e===``?{}:{user:e},Hf=e=>e===``?{}:{port:e},Uf=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...Vf(t.username),...Hf(t.port)}:void 0}catch{return}},Wf=e=>{let t=Bf.exec(e),n=t?.groups?.host;return n===void 0?Uf(e):{host:n,user:t?.groups?.user??`git`}},Gf=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,Kf=e=>e.user===void 0?Gf(e):`${e.user}@${Gf(e)}`,qf=e=>{let t=Object.values(e.refs).map(e=>Wf(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(Kf(e),e);return[...n.values()].toSorted((e,t)=>Kf(e).localeCompare(Kf(t)))},Jf=/Permission denied/u,Yf=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Xf=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,Zf=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Xf(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},Qf=async(e,t,n)=>{let r=Kf(t),i=await e.runner.run(`ssh`,Zf(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:Jf.test(i.stderr)?{host:r,outcome:`denied`}:Yf.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},$f=(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`}},ep=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`}},tp=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`}},np=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),rp=(e,t)=>$f(e,t)??ep(e)??tp(e)??np(e),ip=async(e,t,n)=>{let r=qf(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>Qf(e,t,i)));return rp(a,i)},ap=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${Gd(t)}`,name:e.name,status:`fail`}}},op=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await ap(t),i=await op(n);return r===void 0?i:[r,...i]},sp=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Jd(n)},{name:`node`,run:()=>Promise.resolve(Qd(n))},{name:`config`,run:()=>Promise.resolve(tf(t.errorMessage))},{name:`hooks-guard`,run:()=>lf(n,r,t.config)},{name:`dirty-checkouts`,run:()=>ff(n,r,t.config)},{name:`orphans`,run:()=>yf(r,t.config,i)},{name:`skill`,run:()=>zf(n)},{name:`ssh-auth`,run:()=>ip(n,t.config)}]},cp=async e=>{let t=H(e.env),n=await ef(t),r=await pf(t);return op(sp({configLoad:n,ctx:e,home:t,state:r}))},lp={fail:`FAIL`,ok:`OK`,warn:`WARN`},up=e=>e.map(e=>`[${lp[e.status]}] ${e.name}: ${e.detail}`),dp=e=>e.some(e=>e.status===`fail`),fp=(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 cp(t);Q(t,r,up(e),{checks:e}),dp(e)&&(process.exitCode=_.UNEXPECTED)})()})},pp=async e=>{let t=H(e.env),n=await J(t,`home`,()=>lc(t,wd));return n===`migrated`?{backup:Vs(t),result:n}:{backup:null,result:n}},mp=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${ee(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,hp=(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 pp(t);Q(t,r,mp(e),e)})()})},gp=`never`,_p=(e,t,n)=>e===void 0||n-Date.parse(e)>t,vp=(e,t)=>`${e} ${t}${e===1?``:`s`} ago`,yp=(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 vp(i,`minute`);let a=Math.floor(i/60);if(a<24)return vp(a,`hour`);let o=Math.floor(a/24);return o<365?vp(o,`day`):vp(Math.floor(o/365),`year`)},bp=e=>{let t=yp(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=Qo(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:_p(r?.last_fetched_at,i,e.now)}},Sp=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))},Cp=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=await X(r);return Sp({config:i,home:r,includePackages:t,now:n,state:a})},wp=(e,t)=>[`ref: ${e.key}`,`description: ${e.description}`,...bp({lastFetchedAt:e.last_fetched_at,missing:e.missing,now:t,stale:e.stale})],Tp=(e,t)=>e.length===0?[`no refs configured — run: refs add <source>`]:e.reduce((e,n,r)=>(r>0&&e.push(``),e.push(...wp(n,t)),e),[]),Ep=e=>e.split(`/`),Dp=(e,t)=>{let n=Ep(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Op=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=Ep(t),r=Object.keys(e.refs).filter(e=>Dp(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)},kp=(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 Cp(t,e.packages===!0,n);Q(t,r,Tp(i,n),i)})()})},Ap=e=>`ref.${e.replaceAll(`/`,`_`)}`,jp=e=>e.REFS_ALLOW_FILE_URLS===`1`,Mp=(e,t)=>{let n=pl(t,{allowFileUrls:jp(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},Np=async(e,t)=>{if(t===``)throw b(`refs add npm: requires a package name, e.g. npm:left-pad`);qd(e,`resolving npm package '${t}'…`);let n=await gu(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},Pp=(e,t)=>t.startsWith(`npm:`)?Np(e,t.slice(4)):Promise.resolve(Mp(e,t)),Fp=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Y(`git_transport`,void 0,t);return{...e,cloneUrl:wl(e.cloneUrl,n)}},Ip=e=>`ref '${e}' already exists — use refs edit or refs remove`,Lp=(e,t)=>{if(e.refs[t]!==void 0)throw ve(Ip(t))},Rp=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},zp=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),Bp=async(e,t)=>{let n=await Rp(e);if(n===void 0)return{kind:`stop`};let r=zp(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}},Vp=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await Bp(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):Vp(a.nextDir,i,[...n,r])},Hp=[],Up=async(e,t)=>{let n=await Vp(e.sourcesDir,t.split(`/`),Hp);if(n!==void 0)throw ve(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},Wp=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},Gp=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},Kp=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},qp=async e=>{let t=await Gp(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},Jp=async e=>{let t=await Kp(e);return t===void 0?!0:t?qp(e):!1},Yp=async(e,t)=>{t!==e.sourcesDir&&await Jp(t)&&await Yp(e,te(t))},Xp=async(e,t)=>await Wp(t)?(Gs(e,t),await u(t,{force:!0,recursive:!0}),await Yp(e,te(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},Zp=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),Qp=async(e,t)=>{let n=await W(e),r={...n,refs:Zp(n.refs,t)};await $s(e,r);let i=await X(e),a={...i,refs:Zp(i.refs,t)};await qu(e,a)},$p=async(e,t)=>{let n=H(e.env),r=await W(n),i=Op(r,t),a=U(n,i),{removedCheckout:o,warning:s}=await J(n,Ap(i),()=>Xp(n,a));return await J(n,`home`,()=>Qp(n,i)),{data:{key:i,removed_checkout:o},warnings:Wd(s)}},em=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],tm=(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 $p(t,e);Q(t,i,em(n),n,r)})()})},nm=(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},rm=(e,t)=>{if(!G(e))throw y(`checkout for '${t}' is missing — run: refs sync ${t}`)},im=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw y(`no package '${n}' registered on ref '${t}'`);return r},am=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,om=/^[a-z][a-z0-9+.-]*:\/\//iu,sm=/^git@[^:/\s]+:[^\s]+$/u,cm=e=>om.test(e)||sm.test(e),lm=(e,t)=>{try{return pl(e,t)}catch{if(cm(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}},um=(e,t,n)=>{let r=lm(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw y(am(t))}},dm=(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},fm=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,pm=(e,t)=>{let n=dm(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw b(fm(t,n.map(e=>e.key)));return r}},mm=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=pm(e,r);if(i!==void 0)return{...i,name:r}}},hm=(e,t)=>{try{return Op(e,t)}catch(e){throw e instanceof v&&e.code===`not_found`?y(am(t)):e}},gm=(e,t,n)=>{let r=um(e,t,n);if(r!==void 0)return r;let i=pm(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=mm(e,t);return a===void 0?{key:hm(e,t)}:{key:a.key,packageMatch:a}},_m=(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}},vm=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=gm(i,t,{allowFileUrls:jp(e.env)}),o=nm(i,a.key),s=await X(r),c=U(r,a.key),l=Qo(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:_m(a,c),stale:_p(u,l,n)}},ym=(e,t)=>{let n=[`ref: ${e.key}`,`path: ${e.local_path}`,...bp({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},bm=(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 vm(t,e,n);Q(t,i,ym(r,n),r)})()})},xm={},Sm=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await kc(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${Gd(e)}`}}},Cm=async(e,t,n,r)=>{let i=H(e.env),a=await W(i),o=Op(a,t),s=nm(a,o),c=await X(i),l=U(i,o),{packages:u,...d}=s,f=n.tags?await Sm(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:_p(p.last_fetched_at,Qo(Y(`sync_ttl`,s,a.settings)),r),state:p},warnings:Wd(f?.warning)}},wm=(e,t)=>{let n=[`ref: ${e.key}`,`description: ${e.description}`,`url: ${e.url}`,`path: ${e.local_path}`,...bp({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},Tm=(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 Cm(t,e,r,a);Q(t,i,wm(o,a),o,s)})()})},Em=(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},Dm=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await $s(e,r))},Om=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await Dm(e,t,n.branchRenamedTo);let r=await X(e);r.refs[t]=Em(r.refs[t],n),await qu(e,r)}),km=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 qu(e,r)})}catch{}},Am=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()}}},jm=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Mm=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,Nm=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,Pm=(e,t)=>{try{return pl(e,{allowFileUrls:t}).key}catch{return}},Fm=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=Nm(n),i=Pm(t.expectedUrl,t.allowFileUrls),a=Pm(r,t.allowFileUrls);if(i===void 0||a!==i)throw ve(Mm(t.dest,r,t.expectedUrl))},Im=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,Lm=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw ve(Im(t.dest))},Rm=async(e,t)=>{await a(te(t.dest),{recursive:!0}),qd(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await bc(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},zm=async(e,t)=>(Gs(t.home,t.dest),G(t.dest)?(await Fm(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await Lm(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Rm(e,t)),Bm=(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`,Vm=(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`,Hm=async(e,t)=>{await Fm(e,t),await Lm(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(Bm(t.key,t.dest));let r=n.stdout.trim();if(!Uu.shape.head_sha.safeParse(r).success)throw x(Vm(t.key,t.dest,r));return r},Um=(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`,Wm=(e,t,n)=>{if(!Uu.shape.head_sha.safeParse(n).success)throw x(Um(e,t,n));return n},Gm=(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},Km=async(e,t,n)=>{await a(te(n),{recursive:!0});let r=Y(`clone_mode`,t.ref,t.settings),i=await bc(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Sc(e.runner,n),s=await Hm(e.runner,{allowFileUrls:jp(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return Gm(t,i,{actualBranch:o,headSha:s})},qm=async(e,t,n)=>{await Lm(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await Fm(e.runner,{allowFileUrls:jp(e.env),dest:n,expectedUrl:t.ref.url});let r=await Oc(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Wm(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},Jm=(e,t)=>J(t.home,Ap(t.key),()=>{let n=U(t.home,t.key);return Gs(t.home,n),G(n)?qm(e,t,n):Km(e,t,n)}),Ym=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(` | `)},Xm=(e,t)=>{let n={key:e,status:t.status},r=Ym(t);return r!==void 0&&(n.warning=r),n},Zm=async(e,t)=>{try{let n=await Jm(e,t);return await Om(t.home,t.key,n),Xm(t.key,n)}catch(e){let n=Gd(e);return await km(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},Qm=(e,t)=>e.status===`rejected`?{error:Gd(e.reason),key:t,status:`failed`}:e.value,$m=async(e,t)=>{let n=Am(4);return(await Promise.allSettled(t.map(t=>jm(n,()=>Zm(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return Qm(e,r.key)})},eh=(e,t,n)=>({home:e,key:n,ref:nm(t,n),settings:t.settings}),th=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>eh(e,t,z.parse(n))):n.map(n=>eh(e,t,Op(t,n))),nh=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=Qo(Y(`sync_ttl`,t.ref,t.settings)),a=_p(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},rh=async(e,t,n)=>{if(!n)return t;let r=await X(e);return nh(e,t,r)},ih=async(e,t)=>{let n=H(e.env),r=await W(n),i=th(n,r,t.refs),a=await rh(n,i,t.staleOnly),o=await $m(e,a);return{failedCount:o.filter(e=>e.status===`failed`).length,results:o}},ah=[`updated`,`fresh`,`cloned`,`restored`,`failed`],oh={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},sh=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},ch=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,lh=e=>{let t=sh(e),n=[ah.map(e=>`${oh[e]} (${t[e].length})`).join(` / `)];for(let e of ah)for(let r of t[e])n.push(ch(r));return n},uh=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),dh=(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 ih(t,uh(e,n));Q(t,i,lh(r.results),{results:r.results}),r.failedCount>0&&(process.exitCode=_.UNEXPECTED)})()})},fh=(e,t,n)=>n===void 0?e.tag_format:im(e,t,n).tag_format??e.tag_format,ph=async(e,t)=>{let n=H(e.env),r=await W(n),i=Op(r,t.query),a=nm(r,i),o=fh(a,i,t.opts.packageName),s=U(n,i);rm(s,i);let c=await Wc(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},mh=e=>[`${e.key}@${e.version} -> ${e.tag}`],hh=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},gh=[fp,hp,tm,bm,Tm,dh,(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 ph(t,{opts:hh(r),query:e,version:n});Q(t,a,mh(i),i)})()})}],_h=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},vh=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,_h(e)])):n===void 0?{}:{[n]:{path:t??`.`}},yh=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}},bh=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,yh(t)]))},xh=e=>e.description===void 0||e.description===``,Sh=e=>Object.entries(e).filter(([,e])=>xh(e)).map(([e])=>e).toSorted(),Ch=e=>{let t=Sh(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`)},wh=e=>{if(Object.keys(e).length!==0)return e},Th=e=>{if(e===null)throw x(`tag_format_candidate must be set to a valid tag format (containing '{version}') before finalizing — edit the proposal and provide one, or add the ref manually`);return e},Eh=e=>e.packages===void 0?{default_branch:e.default_branch,description:e.description,tag_format:e.tag_format,url:e.url}:{default_branch:e.default_branch,description:e.description,packages:e.packages,tag_format:e.tag_format,url:e.url},Dh=async(e,t,n)=>{let r=await Sc(e.runner,t),i=await kc(e.runner,t),a=Hc(i);qd(e,`detecting workspace packages…`);let o=await Cd(t);return{defaultBranch:r,packages:vh(o,n.npmDirectory,n.npmPkgName),tagFormatCandidate:a}},Oh=(e,t)=>J(t.home,Ap(t.resolved.key),async()=>{let n=await zm(e,{allowFileUrls:jp(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=H(e.env),r=await W(n),i=Fp(await Pp(e,t),r.settings);Lp(r,i.key),await Up(n,i.key);let a=U(n,i.key),o=Y(`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 W(e);Lp(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 qu(e,i)}),Mh=(e,t)=>{let n=cs.safeParse(e);if(!n.success)throw x(O(n.error));let r=Wu.safeParse(t);if(!r.success)throw x(O(r.error));return{config:n.data,state:r.data}},Nh=async(e,t)=>{let n=await W(e.home);Lp(n,e.ref.key);let r=Eh(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()},{...Mh(n,i),entry:r}},Ph=async(e,t)=>{let n=jp(e.env),r=await J(t.home,Ap(t.ref.key),()=>(Gs(t.home,t.dest),Hm(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 qu(t.home,i),await $s(t.home,e),{entry:n,key:t.ref.key}})},Fh=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),Ih=e=>{try{return JSON.parse(e)}catch(e){throw x(`invalid JSON in proposal: ${Gd(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 x(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(Lh(e.data))return e.data;throw x(`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 O(e);let i=n.filter(e=>!Vh(e)),a=[...Uh(t),...r.map(e=>Wh(e))];return i.length>0&&a.push(O({issues:i})),a.join(`
369
+ `)},Kh=e=>{let t=Hu.safeParse(e);if(!t.success)throw x(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=H(e.env);await jh(r,n.proposal.key,n.effectiveCloneMode);let i=Wd(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,tag_format:Th(e.tag_format_candidate),url:e.url},n=wh(e.packages);return n!==void 0&&(t.packages=n),t},Qh=async(e,t)=>{let n=await qh(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=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)=>{Ch(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,tag_format:Th(e.proposal.tag_format_candidate),url:e.proposal.url},r=bh(e.proposal.packages);return r!==void 0&&(n.packages=r),n},eg=async(e,t,n)=>{let r=await Ah(e,t),i=H(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=Wd(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 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},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=Z(r);return $(t,i,async()=>{let r=await rg(t,ig(e,n));Q(t,i,r.human,r.data,r.warnings)})()})},og=e=>e===void 0?null:e,sg=()=>Object.keys(os.shape).toSorted().join(`, `),cg=e=>`unknown package field '${e}' — valid fields: ${sg()}`,lg=e=>Object.hasOwn(os.shape,e),ug=(e,t,n)=>{if(!lg(t))throw b(cg(t));let r=e[t],i=os.safeParse({...e,[t]:n});if(!i.success)throw x(O(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},dg=async e=>{let t=im(e.entry,e.key,e.packageName),n=ug(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await $s(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:og(n.newValue),old:og(n.oldValue)}},fg=`packages`,pg=()=>Object.keys(ss.shape).filter(e=>e!==fg).toSorted().join(`, `),mg=e=>`unknown ref field '${e}' — valid fields: ${pg()}`,hg=e=>Object.hasOwn(ss.shape,e),gg=(e,t,n)=>`failed to rewrite git remote at ${e} to '${q(t)}': ${n.trim()}`,_g=async(e,t)=>{if(Gs(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(gg(t.dest,t.cloneUrl,n.stderr))},vg=async(e,t)=>{let n=pl(t.value,{allowFileUrls:jp(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 _g(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},yg=(e,t,n)=>{let r={...e,[t]:n},i=ss.safeParse(r);if(!i.success)throw x(O(i.error));return i.data},bg=(e,t)=>t.field===`url`?vg(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(yg(t.entry,t.field,t.value)),xg=async(e,t)=>{let{field:n}=t;if(n===fg)throw b(`use --package <name> <field> <value>`);if(!hg(n))throw b(mg(n));let r=t.entry[n],i=await bg(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},Sg=(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=Op(t,a),c=nm(t,s);if(i.packageName!==void 0)return dg({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await xg(e,{entry:c,field:r,home:n,key:s,value:o});return await $s(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:og(l.new),old:og(l.old)}})},Cg=`settings`,wg=[],Tg=()=>Object.keys(is.shape).toSorted().join(`, `),Eg=e=>`unknown setting '${e}' — valid settings: ${Tg()}`,Dg=e=>Object.hasOwn(is.shape,e),Og=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,kg=e=>{try{let t=Op(e,Cg);return[Og(`ref '${t}'`)]}catch(e){if(e instanceof v&&e.code===`usage`)return[Og("one of several matching refs — see `refs list`")];if(e instanceof v&&e.code===`not_found`)return wg;throw e}},Ag=e=>({data:{field:e.key,key:Cg,new:og(e.parsed[e.key]),old:og(e.old)},warnings:kg(e.config)}),jg=(e,t)=>{let n=H(e.env);return J(n,`home`,async()=>{let e=await W(n);if(!Dg(t.key))throw b(Eg(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=is.safeParse(i);if(!a.success)throw x(O(a.error));return await $s(n,{...e,settings:a.data}),Ag({config:e,key:t.key,old:r,parsed:a.data})})},Mg=[],Ng=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Pg=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 jg(e,{key:t.second,value:t.value})}return{data:await Sg(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:Mg}},Fg=e=>e==null?`(unset)`:String(e),Ig=e=>[`${e.key}: ${e.field} '${Fg(e.old)}' -> '${Fg(e.new)}'`],Lg=(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 Pg(t,{first:e,opts:Ng(i),second:n,value:r});Q(t,o,Ig(a),a,s)})()})},Rg=`Install the agent skill: npx skills add kaisers-io/refs (from a local clone: npx skills add <path-to-this-repo> --skill refs)`,zg={migrated:`migrated`,noop:`unchanged`,seeded:`seeded`},Bg=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})},Vg=async e=>{let t=H(e.env);return await Bg(t),{config:await J(t,`home`,async()=>{let e=await lc(t,wd);return await Mc(t),e}),home:t.root,skill_hint:Rg}},Hg=[(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 Vg(t);Q(t,r,[`home: ${e.home}`,`config: ${zg[e.config]}`,``,Rg],e)})()})},ag,Lg,kp,...gh],Ug=(e,t)=>{for(let n of Hg)n(e,t)},Wg=[``,`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
+ `),Gg=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),Kg=`--json`,qg=`--verbose`,Jg=/\n$/u,Yg=/^error: /u,Xg=e=>e.replace(Yg,``),Zg=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},Qg=e=>Zg(e,Kg),$g=e=>Zg(e,qg),e_=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,t_=e=>{let t=new zd().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(wd).option(Kg,`emit machine-readable JSON on stdout instead of human-readable text`).option(qg,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(Jg,``))},writeOut:t=>{e.out(t.replace(Jg,``))}});return t.addHelpText(`after`,Wg),Ug(t,e),t},n_=()=>{process.exitCode=_.OK},r_=(e,t,n)=>{let r={code:`usage`,message:e_(Xg(n.message),n.stack,t.verbose)};Kd(e,t,r),process.exitCode=_.USAGE},i_=(e,t,n)=>{if(Gg.has(n.code)){n_();return}r_(e,t,n)},a_=(e,t,n)=>{let r=be(n,{verbose:t.verbose});Kd(e,t,r),process.exitCode=r.exitCode},o_=async(e,t,n)=>{let r={json:Qg(n),verbose:$g(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof Od){i_(e,r,t);return}a_(e,r,t)}},s_=(e,t)=>o_(e,t_(e),t);import.meta.main&&await s_(Dd(),process.argv);export{t_ as buildProgram,Z as cliOptsOf,Q as emit,Kd as emitError,Gd as errorMessageOf,qd as progress,Dd as realContext,Ug as registerCommands,s_ as run,o_ as runProgram,Wd as warningsFor,$ as wrapAction};