@tomato414941/foundation 30.1.0 → 30.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -118,8 +118,8 @@ ${c}`:c:"",l=Function,d=`return (input) => {
|
|
|
118
118
|
${c}
|
|
119
119
|
}`,p;try{p=new l(...s,d)(...a)}catch(f){throw new se(`this schema (generated code failed to evaluate: ${f.message})`)}return t?.debug&&(p.code=u),p.definite=o.definite,p}function K(e,t){for(let[o,n]of e.constants)if(n===t)return o;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function ea(e,t){return e.definite=!1,K(e,t)}function V(e){return`v${e.varCounter++}`}function MY(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return Zt;let o=r;return o.issues.length===0?o.value:Zt}function Ut(e,t,r,o,n=!0){let i=e.content.length,s=t.constants.size,a=t.constantCounter,c=t.varCounter;try{return Le(e,t,r,o,n)}catch(u){if(!(u instanceof se)||!u.islandable)throw u;if(e.content.length=i,t.constants.size>s){let l=Array.from(t.constants.keys()).slice(s);for(let d of l)t.constants.delete(d)}return t.constantCounter=a,t.varCounter=c,LY(e,t,r,o)}}function LY(e,t,r,o){t.definite=!1;let n=K(t,r),i=K(t,MY),s=V(t);return e.write(`const ${s} = ${i}(${n}, ${o});`),e.write(`if (${s} === INVALID) return INVALID;`),s}var FY=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function VY(e,t,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let s of n){let a=s._zod.def;if(a.when&&!FY.has(a.check))throw new se('check with a custom "when" condition');switch(a.check){case"greater_than":BY(e,t,a,i);break;case"less_than":HY(e,t,a,i);break;case"multiple_of":KY(e,t,a,i);break;case"number_format":uz(e,a,i);break;case"min_length":{let c=Ri(a.minimum,"min_length"),u=II(e,t,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);e.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Ri(a.maximum,"max_length"),u=II(e,t,i,`${i}.length > ${c}`);e.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Ri(a.length,"length_equals"),u=II(e,t,i,`${i}.length >= ${c} && ${i}.length <= ${a.length*2}`);e.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":e.write(`if (${i}.size < ${Ri(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${Ri(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${Ri(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=lz(e,t,a,i);break;case"custom":i=XY(e,t,s,i);break;case"bigint_format":WY(e,a,i);break;case"mime_type":qY(e,t,a,i);break;case"property":ZY(e,t,a,i);break;case"properties":JY(e,t,a,i);break;case"overwrite":{let c=V(t);GY(e,t,s,i,c),i=c;break}default:throw new se(`check type ${a.check}`)}}return i}function II(e,t,r,o){let n=K(t,Zs),i=V(t);return e.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function Ri(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new se(`${t} bound of type ${typeof e}`);return`${e}`}function cz(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new se("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new se("comparison check with Invalid Date bound");return K(e,t)}throw new se(`comparison check bound of type ${typeof t}`)}function BY(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${cz(t,r.value)}) return INVALID;`)}function HY(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${cz(t,r.value)}) return INVALID;`)}function KY(e,t,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new se("multiple_of check with a zero divisor");e.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=K(t,ql);e.write(`if (${n}(${o}, ${Ri(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function uz(e,t,r){let o=t.format;switch(o){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new se(`number format ${o}`)}}function WY(e,t,r){let o=t.format;if(o)switch(o){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new se(`bigint format ${o}`)}}function qY(e,t,r,o){let n=r.mime;if(n&&n.length>0){let i=K(t,new Set(n));e.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function JY(e,t,r,o){if(r.when)throw new se('check with a custom "when" condition');e.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let s=typeof i=="symbol"?K(t,i):qt(i),a=V(t);e.write(`const ${a} = ${o}[${s}];`),Ut(e,t,n[i],a,!1)}}function ZY(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Le(e,t,r.schema,n)}function GY(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new se("overwrite check without a transform function");if(ta(i))throw new ln("z.compile: async overwrite transforms are not supported");let s=K(t,i);e.write(`const ${n} = ${s}(${o});`)}function AI(){throw new sr}function TI(e){this.issues.push(e)}function XY(e,t,r,o){let n=r._zod.def;if(n.fn){if(ta(n.fn))throw new ln("z.compile: async .refine() predicates are not supported");let i=ea(t,n.fn),s=K(t,AI),a=V(t);return e.write(`const ${a} = ${i}(${o});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`),o}if(r._zod.check){if(ta(r._zod.check))throw new ln("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=ea(t,u=>{let l={value:u,issues:[],addIssue:TI};return i(l)instanceof Promise&&AI(),l.issues.length===0?l.value:Zt}),c=V(t);return e.write(`const ${c} = ${a}(${o});`),e.write(`if (${c} === INVALID) return INVALID;`),c}throw new se("custom check without a predicate or check function")}var YY=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function lz(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let u=K(t,pd);return e.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=K(t,uh);return e.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=K(t,fh),l=K(t,r.alg??null);return e.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=K(t,fd);return e.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=K(t,ah);return e.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=K(t,lh);return e.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=K(t,dh);return e.write(`if (!${u}(${o})) return INVALID;`),o}let s=r;if(i==="url"||i==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=K(t,oh),l=K(t,r),d=V(t),p=V(t);if(e.write(`const ${d} = ${o}.trim();`),e.write(`const ${p} = ${u}(${d}, ${l});`),e.write(`if (typeof ${p} === "number") return INVALID;`),s.hostname!==void 0){let g=K(t,ih);e.write(`if (!${g}(${p}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let g=K(t,sh);e.write(`if (!${g}(${p}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let f=V(t),m=s.normalize?`${p}.href`:`${K(t,dd)}(${d})`;return e.write(`const ${f} = ${m};`),f}let a=r.fn;if(a){if(ta(a))throw new se(`async string format ${i}`);let u=K(t,a);return e.write(`if (!${u}(${o})) return INVALID;`),o}if(YY.has(i)&&r.pattern){let u=K(t,r.pattern);return e.write(`${u}.lastIndex = 0;`),e.write(`if (!${u}.test(${o})) return INVALID;`),o}let c=r.format;switch(c){case"regex":throw new se("regex format without a pattern");case"lowercase":e.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${o}.includes(${qt(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;e.write(`if (${o}.slice(0, ${u.length}) !== ${qt(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;e.write(`if (${o}.slice(-${u.length}) !== ${qt(u)}) return INVALID;`);break}default:throw new se(`string format ${c}`)}return o}function Le(e,t,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new se(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=QY(e,t,r,o,a);break;case"number":c=eQ(e,r,o);break;case"boolean":c=tQ(e,o);break;case"bigint":c=rQ(e,r,o);break;case"symbol":c=nQ(e,o);break;case"undefined":c=oQ(e,o);break;case"null":c=iQ(e,o);break;case"any":case"unknown":c=o;break;case"never":e.write("return INVALID;"),c=o;break;case"void":c=sQ(e,o);break;case"nan":c=aQ(e,o);break;case"date":c=cQ(e,o);break;case"object":c=uQ(e,t,r,o,a);break;case"optional":c=lQ(e,t,r,o,a);break;case"nullable":c=pQ(e,t,r,o,a);break;case"array":c=mQ(e,t,r,o,a);break;case"literal":c=hQ(e,t,r,o);break;case"enum":c=gQ(e,t,r,o);break;case"readonly":{let u=iz(e,t,r,o),l=V(t);e.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":iz(e,t,r,o),c="true";break;case"default":case"prefault":c=yQ(e,t,r,o);break;case"nonoptional":c=wQ(e,t,r,o);break;case"tuple":c=vQ(e,t,r,o);break;case"union":c=bQ(e,t,r,o);break;case"intersection":c=xQ(e,t,r,o);break;case"record":c=EQ(e,t,r,o);break;case"map":c=AQ(e,t,r,o);break;case"set":c=kQ(e,t,r,o);break;case"file":c=$Q(e,o);break;case"template_literal":c=TQ(e,t,r,o);break;case"lazy":c=PQ(e,t,r,o);break;case"pipe":c=CQ(e,t,r,o);break;case"custom":c=RQ(e,t,r,o);break;case"transform":c=DQ(e,t,r,o);break;case"catch":c=NQ(e,t,r,o);break;default:throw new se(`schema type ${s}`)}return c===null?null:VY(e,t,r,c)}function QY(e,t,r,o,n=!0){e.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:lz(e,t,i,o,n)}function eQ(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=t._zod.def;return o.check==="number_format"&&o.format&&uz(e,{format:o.format},r),r}function tQ(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function rQ(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=t._zod.def;if(o.format)switch(o.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function nQ(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function oQ(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function iQ(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function sQ(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function aQ(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function cQ(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function uQ(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let s=i.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=b=>typeof b=="symbol"?K(t,b):qt(b),d=b=>typeof b=="symbol"?`[${l(b)}]`:qt(b),p=s;if(a.includes("__proto__"))throw new se('object shape key "__proto__"');let f=new Map;for(let b of u){let x=p[b],E=l(b),T=V(t);if(e.write(`const ${T} = ${o}[${E}];`),x._zod.optin!==void 0){let R=V(t);e.write(`let ${R} = (() => {`),e.indented(U=>{let j=Ut(U,t,x,T);U.write(`return ${j};`)}),e.write("})();"),x._zod.optout==="optional"?(e.write(`if (${R} === INVALID) {`),e.indented(U=>{U.write(`if (${E} in ${o}) return INVALID;`),U.write(`${R} = undefined;`)}),e.write("}")):e.write(`if (${R} === INVALID) return INVALID;`),f.set(b,R)}else{fQ(x)&&e.write(`if (!(${E} in ${o})) return INVALID;`);let R=Ut(e,t,x,T,n);R!==null&&f.set(b,R)}}let m=i.catchall,g="none";if(m){let b=m._zod.def.type;if(b==="never"){let x=a.map(E=>`k !== ${qt(E)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(E=>{E.write(`if (${x}) return INVALID;`)}),e.write("}")}else(b==="unknown"||b==="any")&&!m._zod.def.checks?.length?g="passthrough":g="schema"}let w=V(t),v=u.some(b=>oz(p[b])||kI(p[b]));if(!n){if(g==="schema"){let b=a.length>0?K(t,new Set(a)):null;e.write(`for (const k in ${o}) {`),e.indented(x=>{x.write('if (k === "__proto__") continue;'),b&&x.write(`if (${b}.has(k)) continue;`);let E=V(t);x.write(`const ${E} = ${o}[k];`),Ut(x,t,m,E,!1)}),e.write("}")}return null}if(v){e.write(`const ${w} = {};`);for(let b of u){let x=l(b),E=f.get(b);kI(p[b])?e.write(`if (${x} in ${o}) ${w}[${x}] = ${E};`):oz(p[b])?e.write(`if (${E} !== undefined || ${x} in ${o}) ${w}[${x}] = ${E};`):e.write(`${w}[${x}] = ${E};`)}}else{let b=u.map(x=>`${d(x)}: ${f.get(x)}`).join(", ");e.write(`const ${w} = { ${b} };`)}if(g!=="none"){let b=a.length>0?K(t,new Set(a)):null;e.write(`for (const k in ${o}) {`),e.indented(x=>{if(x.write('if (k === "__proto__") continue;'),b&&x.write(`if (${b}.has(k)) continue;`),g==="passthrough")x.write(`${w}[k] = ${o}[k];`);else{let E=V(t);x.write(`const ${E} = ${o}[k];`);let T=Ut(x,t,m,E);x.write(`${w}[k] = ${T};`)}}),e.write("}")}return w}function lQ(e,t,r,o,n=!0){let i=r._zod.def;if(dQ(r))return Le(e,t,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=V(t),c=V(t);return e.write(`let ${a};`),e.write(`if (${o} === undefined) {`),e.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=Le(l,t,i.innerType,o);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),e.write("} else {"),e.indented(u=>{let l=Le(u,t,i.innerType,o);u.write(`${a} = ${l};`)}),e.write("}"),a}let s=n?V(t):null;return s&&e.write(`let ${s};`),e.write(`if (${o} !== undefined) {`),e.indented(a=>{let c=Le(a,t,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),e.write("}"),s}function dQ(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function fQ(e){return e._zod.optin===void 0&&Qs(e)}function Qs(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Qs(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Qs(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Qs):!0;case"intersection":return!t.left||!t.right?!0:Qs(t.left)&&Qs(t.right);case"pipe":return t.in?Qs(t.in):!0;default:return!0}}function kI(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function oz(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&xc(e)}function xc(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?xc(t.innerType):!0;case"union":return t.options?t.options.some(xc):!0;case"intersection":return!t.left||!t.right||xc(t.left)||xc(t.right);case"pipe":return t.out?xc(t.out):!0;default:return!0}}function pQ(e,t,r,o,n=!0){let i=r._zod.def,s=n?V(t):null;return s&&e.write(`let ${s} = null;`),e.write(`if (${o} !== null) {`),e.indented(a=>{let c=Le(a,t,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),e.write("}"),s}function PI(e,t,r){for(let[o,n]of pc(t._zod.def.checks))e.write(`if (${r} > ${Ri(o,n._zod.def.check)}) return INVALID;`)}function mQ(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`),PI(e,r,`${o}.length`);let s=n?V(t):null,a=V(t),c=V(t);return s&&e.write(`const ${s} = new Array(${o}.length);`),e.write(`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`),e.indented(u=>{u.write(`const ${c} = ${o}[${a}];`);let l=Ut(u,t,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),e.write("}"),s}function hQ(e,t,r,o){let i=r._zod.def.values;if(i.length!==1){let a=K(t,new Set(i));return e.write(`if (!${a}.has(${o})) return INVALID;`),o}let s=i[0];if(typeof s=="number"&&Number.isNaN(s)){let a=K(t,new Set(i));return e.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")e.write(`if (${o} !== ${qt(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")e.write(`if (${o} !== ${s}) return INVALID;`);else if(s===null)e.write(`if (${o} !== null) return INVALID;`);else if(s===void 0)e.write(`if (${o} !== undefined) return INVALID;`);else if(typeof s=="bigint")e.write(`if (${o} !== ${s}n) return INVALID;`);else throw new se(`literal type ${typeof s}`);return o}function gQ(e,t,r,o){let n=r._zod.values;if(!n)throw new se("enum schema without enumerated values");let i=K(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function iz(e,t,r,o){let n=r._zod.def;return Le(e,t,n.innerType,o)}function yQ(e,t,r,o){let n=r._zod.def,s=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!s)return Le(e,t,n.innerType,o);let c=K(t,s),u=V(t);return e.write(`let ${u} = ${o};`),e.write(`if (${o} === undefined) ${u} = ${c}();`),Le(e,t,n.innerType,u)}let a=V(t);if(s){let c=K(t,s),u=K(t,Jl);e.write(`let ${a};`),e.write(`if (${o} === undefined) {`),e.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),e.write("} else {"),e.indented(l=>{let d=Le(l,t,n.innerType,o);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(c=>{let u=Le(c,t,n.innerType,o);c.write(`${a} = ${u};`)}),e.write("}");return a}function wQ(e,t,r,o){let n=r._zod.def,i=Le(e,t,n.innerType,o),s=V(t);return e.write(`const ${s} = ${i};`),e.write(`if (${s} === undefined) return INVALID;`),s}function vQ(e,t,r,o){let n=r._zod.def,i=n.items,s=n.rest;e.write(`if (!Array.isArray(${o})) return INVALID;`);let a=sz(i,"optin"),c=sz(i,"optout");s?e.write(`if (${o}.length < ${a}) return INVALID;`):e.write(`if (${o}.length < ${a} || ${o}.length > ${i.length}) return INVALID;`);let u=V(t);e.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)e.write(`if (${u}.length === ${l}) {`),e.indented(p=>{p.write(`if (${l} < ${o}.length) {`),p.indented(f=>{let m=V(t);f.write(`const ${m} = ${o}[${l}];`);let g=Ut(f,t,d,m);f.write(`${u}[${l}] = ${g};`)}),p.write("} else {"),p.indented(f=>{if(kI(d)){f.write(`${u}.length = ${l};`);return}let m=V(t),g=V(t);f.write(`const ${m} = undefined;`),f.write(`const ${g} = (() => {`),f.indented(w=>{let v=Ut(w,t,d,m);w.write(`return ${v};`)}),f.write("})();"),f.write(`if (${g} === INVALID || ${g} === undefined) ${u}.length = ${l};`),f.write(`else ${u}[${l}] = ${g};`)}),p.write("}")}),e.write("}");else{let p=V(t);e.write(`const ${p} = ${o}[${l}];`);let f=Ut(e,t,d,p);e.write(`${u}[${l}] = ${f};`)}}if(s){let l=V(t),d=V(t);e.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),e.indented(p=>{p.write(`const ${d} = ${o}[${l}];`);let f=Ut(p,t,s,d);p.write(`${u}[${l}] = ${f};`)}),e.write("}")}return u}function sz(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function bQ(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return SQ(e,t,n,o);if(n.inclusive===!1)throw new se("exclusive unions (z.xor)");if(i.length===0)return e.write("return INVALID;"),o;if(i.length===1)return Le(e,t,i[0],o);if(i.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(i.flatMap(l=>l._zod.def.values)),u=K(t,c);return e.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=V(t);e.write(`let ${a};`);for(let c=0;c<i.length;c++){let u=i[c];c===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(l=>{let d=Le(l,t,u,o);l.write(`return ${d};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function SQ(e,t,r,o){if(r.unionFallback)throw new se("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),o;let n=V(t),i=V(t);e.write(`const ${n} = ${o}?.[${qt(r.discriminator)}];`),e.write(`let ${i};`);let s=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new se("discriminated union option without static discriminator values");for(let p of u){if(a.has(p))throw new se(`duplicate discriminator value ${String(p)}`);a.add(p)}let l=Array.from(u,p=>_Q(t,n,p)),d=s?"if":"else if";e.write(`${d} (${l.join(" || ")}) {`),e.indented(p=>{let f=Le(p,t,c,o);p.write(`${i} = ${f};`)}),e.write("}"),s=!1}return e.write("else { return INVALID; }"),i}function _Q(e,t,r){if(typeof r=="string")return`${t} === ${qt(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let o=K(e,r);return`${t} === ${o}`}throw new se(`literal discriminator value ${String(r)}`)}function xQ(e,t,r,o){let n=r._zod.def;t.definite=!1;let i=Ut(e,t,n.left,o),s=Ut(e,t,n.right,o),a=K(t,bc),c=V(t);return e.write(`const ${c} = ${a}(${i}, ${s});`),e.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function EQ(e,t,r,o){let n=r._zod.def,i=K(t,Dr);e.write(`if (!${i}(${o})) return INVALID;`);let s=V(t),a=V(t),c=V(t);e.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let f=[];for(let g of l){if(!(typeof g=="string"||typeof g=="number"||typeof g=="symbol"))throw new se(`record key value ${String(g)}`);let w=typeof g=="number"?g.toString():g;if(w==="__proto__")throw new se('record key "__proto__"');f.push(w);let v=K(t,g),b=Le(e,t,n.keyType,v),x=V(t);e.write(`const ${x} = ${o}[${IQ(t,w)}];`);let E=Ut(e,t,n.valueType,x);e.write(`${s}[${b}] = ${E};`)}let m=K(t,new Set(f));return e.write(`for (const ${a} in ${o}) {`),e.indented(g=>{g.write(`if (${m}.has(${a})) continue;`),u.mode==="loose"?g.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):g.write("return INVALID;")}),e.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let f=n.mode==="loose",m=Ph(n.keyType);m.definite===!1&&(t.definite=!1);let g=K(t,m),w=K(t,Xo),v=V(t);return az(e,t,o,a,b=>{b.write(`let ${v} = ${g}(${a});`),b.write(`if (${v} === INVALID && typeof ${a} === "string" && ${w}.test(${a})) ${v} = ${g}(Number(${a}));`),f?b.write(`if (${v} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):b.write(`if (${v} === INVALID) return INVALID;`),b.write(`if (${v} === "__proto__") continue;`);let x=V(t);b.write(`const ${x} = ${o}[${a}];`);let E=Ut(b,t,n.valueType,x);b.write(`${s}[${v}] = ${E};`)}),s}return az(e,t,o,a,f=>{f.write(`const ${c} = ${o}[${a}];`);let m=Ut(f,t,n.valueType,c);f.write(`${s}[${a}] = ${m};`)},"return INVALID;"),s}function az(e,t,r,o,n,i){let s=K(t,Object.prototype.propertyIsEnumerable),a=V(t),c=V(t),u=V(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${c} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),e.indented(l=>{l.write(`const ${o} = ${c}[${u}];`),l.write(`if (${o} === "__proto__" || !${s}.call(${r}, ${o})) continue;`),n(l)}),e.write("}"),e.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),e.indented(l=>{l.write(`const ${o} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),e.write("}")}function IQ(e,t){return typeof t=="string"?qt(t):K(e,t)}function AQ(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),PI(e,r,`${o}.size`);let i=V(t),s=V(t),a=V(t);return e.write(`const ${i} = new Map();`),e.write(`for (const [${s}, ${a}] of ${o}) {`),e.indented(c=>{let u=Le(c,t,n.keyType,s),l=Le(c,t,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),e.write("}"),i}function kQ(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),PI(e,r,`${o}.size`);let i=V(t),s=V(t);return e.write(`const ${i} = new Set();`),e.write(`for (const ${s} of ${o}) {`),e.indented(a=>{let c=Le(a,t,n.valueType,s);a.write(`${i}.add(${c});`)}),e.write("}"),i}function $Q(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function TQ(e,t,r,o){e.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=K(t,n);e.write(`${i}.lastIndex = 0;`),e.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function PQ(e,t,r,o){let n=r._zod.def,i=ea(t,n.getter),s=K(t,{parser:null});e.write(`if (!${s}.parser) {`),e.indented(c=>{c.write(`const inner = ${i}();`),c.write(`${s}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),e.write("}");let a=V(t);return e.write(`const ${a} = ${s}.parser(${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function CQ(e,t,r,o){let n=r._zod.def,i=Le(e,t,n.in,o);if(n.transform){if(ta(n.transform))throw new ln("z.compile: async transforms in pipes are not supported");let s=n.transform,c=ea(t,l=>{let d={value:l,issues:[],addIssue:TI},p=s(l,d);return p instanceof Promise?Zt:d.issues.length===0?p:Zt}),u=V(t);return e.write(`const ${u} = ${c}(${i});`),e.write(`if (${u} === INVALID) return INVALID;`),Le(e,t,n.out,u)}else return Le(e,t,n.out,i)}function ta(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function RQ(e,t,r,o){let n=r._zod.def;if(n.fn){if(ta(n.fn))throw new ln("z.compile: async custom predicates are not supported");let i=ea(t,n.fn),s=K(t,AI),a=V(t);e.write(`const ${a} = ${i}(${o});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`)}else throw new se("custom schema without a predicate function");return o}function OQ(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return Zt;let n=o;return n.issues.length===0?n.value:t()}function NQ(e,t,r,o){let n=r._zod.def;if(!n.catchValue[Dm])throw new se("catch with a callback (only a constant catch value compiles)",!1);let i=V(t);e.write(`let ${i} = (() => {`),e.indented(u=>{let l=Ut(u,t,n.innerType,o);u.write(`return ${l};`)}),e.write("})();");let s=K(t,n.innerType),a=ea(t,n.catchValue),c=K(t,OQ);return e.write(`if (${i} === INVALID) {`),e.indented(u=>{u.write(`${i} = ${c}(${s}, ${a}, ${o});`),u.write(`if (${i} === INVALID) return INVALID;`)}),e.write("}"),i}function DQ(e,t,r,o){let n=r._zod.def;if(n.transform){if(ta(n.transform))throw new ln("z.compile: async transforms are not supported");let i=n.transform,a=ea(t,u=>{let l={value:u,issues:[],addIssue:TI},d=i(u,l);return d instanceof Promise?Zt:l.issues.length===0?d:Zt}),c=V(t);return e.write(`const ${c} = ${a}(${o});`),e.write(`if (${c} === INVALID) return INVALID;`),c}return o}function Ch(e){return e.checks&&(e.checks=[...e.checks]),e}function CI(e,t){return new e(Ch({type:"string",...P(t)}))}function RI(e,t){return new e(Ch({type:"string",coerce:!0,...P(t)}))}function Rh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function Oh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function Nh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function Dh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function zh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function Uh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Ed(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function jh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function Mh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function Lh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function Fh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function Vh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function Bh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function Hh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function Kh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function Wh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function OI(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...P(t)})}function qh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Jh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function Zh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function Gh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function Xh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function NI(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...P(t)})}function DI(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...P(t)})}function Yh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}var zI={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Id(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function Ad(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function kd(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function $d(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function UI(e,t){return new e(Ch({type:"number",checks:[],...P(t)}))}function jI(e,t){return new e(Ch({type:"number",coerce:!0,checks:[],...P(t)}))}function MI(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function LI(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...P(t)})}function FI(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...P(t)})}function VI(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...P(t)})}function BI(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...P(t)})}function HI(e,t){return new e({type:"boolean",...P(t)})}function KI(e,t){return new e({type:"boolean",coerce:!0,...P(t)})}function WI(e,t){return new e({type:"bigint",...P(t)})}function qI(e,t){return new e({type:"bigint",coerce:!0,...P(t)})}function JI(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...P(t)})}function ZI(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...P(t)})}function GI(e,t){return new e({type:"symbol",...P(t)})}function XI(e,t){return new e({type:"undefined",...P(t)})}function YI(e,t){return new e({type:"null",...P(t)})}function QI(e){return new e({type:"any"})}function eA(e){return new e({type:"unknown"})}function tA(e,t){return new e({type:"never",...P(t)})}function rA(e,t){return new e({type:"void",...P(t)})}function nA(e,t){return new e({type:"date",...P(t)})}function oA(e,t){return new e({type:"date",coerce:!0,...P(t)})}function iA(e,t){return new e({type:"nan",...P(t)})}function Jn(e,t){return new Xm({check:"less_than",...P(t),value:e,inclusive:!1})}function vr(e,t){return new Xm({check:"less_than",...P(t),value:e,inclusive:!0})}function Zn(e,t){return new Ym({check:"greater_than",...P(t),value:e,inclusive:!1})}function br(e,t){return new Ym({check:"greater_than",...P(t),value:e,inclusive:!0})}function Qh(e){return Zn(0,e)}function eg(e){return Jn(0,e)}function tg(e){return vr(0,e)}function rg(e){return br(0,e)}function Oi(e,t){return new Fx({check:"multiple_of",...P(t),value:e})}function Ni(e,t){return new Hx({check:"max_size",...P(t),maximum:e})}function Gn(e,t){return new Kx({check:"min_size",...P(t),minimum:e})}function ra(e,t){return new Wx({check:"size_equals",...P(t),size:e})}function na(e,t){return new qx({check:"max_length",...P(t),maximum:e})}function Yo(e,t){return new Jx({check:"min_length",...P(t),minimum:e})}function oa(e,t){return new Zx({check:"length_equals",...P(t),length:e})}function Ec(e,t){return new Gx({check:"string_format",format:"regex",...P(t),pattern:e})}function Ic(e){return new Xx({check:"string_format",format:"lowercase",...P(e)})}function Ac(e){return new Yx({check:"string_format",format:"uppercase",...P(e)})}function kc(e,t){return new Qx({check:"string_format",format:"includes",...P(t),includes:e})}function $c(e,t){return new eE({check:"string_format",format:"starts_with",...P(t),prefix:e})}function Tc(e,t){return new tE({check:"string_format",format:"ends_with",...P(t),suffix:e})}function ng(e,t,r){return new rE({check:"property",property:e,schema:t,...P(r)})}function Pc(e,t){return new nE({check:"properties",shape:e,...P(t)})}function Cc(e,t){return new oE({check:"mime_type",mime:e,...P(t)})}function dn(e){return new iE({check:"overwrite",tx:e})}function Rc(e){return dn(t=>t.normalize(e))}function Oc(){return dn(e=>e.trim())}function Nc(){return dn(e=>e.toLowerCase())}function Dc(){return dn(e=>e.toUpperCase())}function zc(){return dn(e=>B_(e))}function sA(e,t,r){return new e({type:"array",element:t,...P(r)})}function zQ(e,t,r){return new e({type:"union",options:t,...P(r)})}function UQ(e,t,r){return new e({type:"union",options:t,inclusive:!1,...P(r)})}function jQ(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...P(o)})}function MQ(e,t,r){return new e({type:"intersection",left:t,right:r})}function LQ(e,t,r,o){let n=r instanceof X,i=n?o:r,s=n?r:null;return new e({type:"tuple",items:t,rest:s,...P(i)})}function FQ(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...P(o)})}function VQ(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...P(o)})}function BQ(e,t,r){return new e({type:"set",valueType:t,...P(r)})}function HQ(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...P(r)})}function KQ(e,t,r){return new e({type:"enum",entries:t,...P(r)})}function WQ(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...P(r)})}function aA(e,t){return new e({type:"file",...P(t)})}function qQ(e,t){return new e({type:"transform",transform:t})}function JQ(e,t){return new e({type:"optional",innerType:t})}function ZQ(e,t){return new e({type:"nullable",innerType:t})}function GQ(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():Jl(r)}})}function XQ(e,t,r){return new e({type:"nonoptional",innerType:t,...P(r)})}function YQ(e,t){return new e({type:"success",innerType:t})}function QQ(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:Z_(r)})}function eee(e,t,r){return new e({type:"pipe",in:t,out:r})}function tee(e,t){return new e({type:"readonly",innerType:t})}function ree(e,t,r){return new e({type:"template_literal",parts:t,...P(r)})}function nee(e,t){return new e({type:"lazy",getter:t})}function oee(e,t){return new e({type:"promise",innerType:t})}function cA(e,t,r){let o=P(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function uA(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function lA(e,t){let r=dz(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(mc(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(mc(i))}},e(o.value,o)),t);return r}function dz(e,t){let r=new Ae({check:"custom",...P(t)});return r._zod.check=e,r}function dA(e){let t=new Ae({check:"describe"});return t._zod.onattach=[r=>{let o=Et.get(r)??{};Et.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function fA(e){let t=new Ae({check:"meta"});return t._zod.onattach=[r=>{let o=Et.get(r)??{};Et.add(r,{...o,...e})}],t._zod.check=()=>{},t}function pA(e,t){let r=P(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(o),s=new Set(n),a=e.Codec??yd,c=e.Boolean??hd,u=e.String??Ys,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new a({type:"pipe",in:l,out:d,transform:((f,m)=>{let g=f;return r.case!=="sensitive"&&(g=g.toLowerCase()),i.has(g)?!0:s.has(g)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:p,continue:!1}),{})}),reverseTransform:((f,m)=>f===!0?o[0]||"true":n[0]||"false"),error:r.error});return p._zod.bag.truthy=o,p._zod.bag.falsy=n,p._zod.bag.case=r.case??"insensitive",p}function ia(e,t,r,o={}){let n=P(o),i={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)}function Td(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&xt(e,o,r[o]);return e}function Di(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??Et,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function nt(e,t,r,o,n){let i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:o.path,message:n}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function xe(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{let p=s.schema,f=t.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(e,t,p,l)}let d=e._zod.parent;d&&(s.ref||(s.ref=d),xe(d,t,l),t.seen.get(d).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Td(s.schema,c),t.io==="input"&&Gt(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function fz(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function zi(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let o=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(s[0])?.id,p=e.external.uri??(m=>m);if(d)return{ref:p(d)};let f=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${fz(f)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+fz(l)}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=n(s);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
120
120
|
|
|
121
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&e.reused==="ref"&&i(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function hz(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;hz(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var gz=new Set(["type","properties","required","additionalProperties"]),pz=["oneOf","anyOf"];function mz(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function mA(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!gz.has(s))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of t){let l=u.properties?.[s]??mz(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:mA(a)??{allOf:a};xt(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of t){let a=mz(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function iee(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of gz)if(n in e)return;let r=t.filter(n=>pz.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=mA(t);else{let n=r[0],i=pz.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=t.filter(c=>c!==n),a=n[i].map(c=>mA([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete e.allOf,Td(e,o))}function Ui(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=e.seen.get(d),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Td(u,m),Td(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&f.def)for(let w in u)w==="$ref"||w==="allOf"||w in f.def&&JSON.stringify(u[w])===JSON.stringify(f.def[w])&&delete u[w]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=e.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())o(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())hz(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])iee(u)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Td(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,xt(s,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Uc(t,"input",e.processors),output:Uc(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Gt(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Gt(o.element,r);if(o.type==="set")return Gt(o.valueType,r);if(o.type==="lazy")return Gt(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Gt(o.innerType,r);if(o.type==="intersection")return Gt(o.left,r)||Gt(o.right,r);if(o.type==="record"||o.type==="map")return Gt(o.keyType,r)||Gt(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Gt(o.in,r)||Gt(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Gt(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Gt(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Gt(n,r))return!0;return!!(o.rest&&Gt(o.rest,r))}return!1}var hA=(e,t={})=>r=>{let o=Di({...r,processors:t});return xe(e,o),zi(o,e),Ui(o,e)},Uc=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Di({...n??{},target:i,io:t,processors:r});return xe(e,s),zi(s,e),Ui(s,e)};var jc=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Mc=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},yz=(e,t)=>{jc(e,"minimum",t),Mc(e,"maximum",t)},Sz=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},_z=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},xz=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Ez=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},wz=(e,t)=>jc(e,"minimum",t.minimum),vz=(e,t)=>Mc(e,"maximum",t.maximum),bz=e=>(t,r)=>{Ez(t,r.format);let[o,n]=e[r.format];jc(t,"minimum",o),Mc(t,"maximum",n)},see={greater_than:(e,t)=>jc(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Mc(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Sz(e,t.value),number_format:bz(Gl),bigint_format:bz(Xl),min_length:wz,max_length:vz,length_equals:(e,t)=>yz(e,t.length),min_size:wz,max_size:vz,size_equals:(e,t)=>yz(e,t.size),string_format:(e,t)=>{Ez(e,t.format),t.pattern&&_z(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>xz(e,t.mime)};function ot(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)see[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&jc(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&jc(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Mc(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Mc(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&Sz(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&xz(t,n.mime);for(let i of n.patterns??[])_z(t,i);return t}var aee={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},cee=new Map([[ch,Sx],[md,_x]]),Iz=e=>cee.get(e)??e,wA=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=ot(e);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=aee[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(Iz);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},vA=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=ot(e);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let v of a)Number.isFinite(v)&&v!==0?m.add(Math.abs(v)):nt(e,t,n,o,`A multipleOf divisor of ${v} cannot be represented in JSON Schema`);let[g,...w]=m;g!==void 0&&(n.multipleOf=g),w.length&&(n.allOf=[...n.allOf??[],...w.map(v=>({multipleOf:v}))])}},bA=(e,t,r,o)=>{r.type="boolean"},SA=(e,t,r,o)=>{nt(e,t,r,o,"BigInt cannot be represented in JSON Schema")},_A=(e,t,r,o)=>{nt(e,t,r,o,"Symbols cannot be represented in JSON Schema")},xA=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},EA=(e,t,r,o)=>{nt(e,t,r,o,"Undefined cannot be represented in JSON Schema")},IA=(e,t,r,o)=>{nt(e,t,r,o,"Void cannot be represented in JSON Schema")},AA=(e,t,r,o)=>{r.not={}},kA=(e,t,r,o)=>{},$A=(e,t,r,o)=>{},TA=(e,t,r,o)=>{nt(e,t,r,o,"Date cannot be represented in JSON Schema")},PA=(e,t,r,o)=>{let n=e._zod.def,i=uc(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},CA=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(nt(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(nt(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},RA=(e,t,r,o)=>{nt(e,t,r,o,"NaN cannot be represented in JSON Schema")},OA=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},NA=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=ot(e);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},DA=(e,t,r,o)=>{r.type="boolean"},zA=(e,t,r,o)=>{nt(e,t,r,o,"Custom types cannot be represented in JSON Schema")},UA=(e,t,r,o)=>{nt(e,t,r,o,"Function types cannot be represented in JSON Schema")},jA=(e,t,r,o)=>{nt(e,t,r,o,"Transforms cannot be represented in JSON Schema")},MA=(e,t,r,o)=>{nt(e,t,r,o,"Map cannot be represented in JSON Schema")},LA=(e,t,r,o)=>{nt(e,t,r,o,"Set cannot be represented in JSON Schema")},FA=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=ot(e);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=xe(i.element,t,{...o,path:[...o.path,"items"]})};function Pd(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Pd(t.out):t.type==="catch"?Pd(t.innerType):e._zod.optin}var VA=(e,t,r,o)=>{let n=r,i=e._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&nt(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)xt(n.properties,u,xe(s[u],t,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(t.io==="input"?Pd(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=xe(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},ig=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>xe(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},BA=(e,t,r,o)=>{let n=e._zod.def,i=xe(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=xe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,t.intersections.push(c)},HA=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((g,w)=>xe(g,t,{...o,path:[...o.path,s,w]})),u=i.rest?xe(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let g=i.items[l-1];if(!(t.io==="input"?Pd(g)!==void 0:g._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):t.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=ot(e);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function gA(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let g=gA(e,m,r);return g===m?t:g}for(let m of["anyOf","oneOf"]){let g=t[m];if(!Array.isArray(g))continue;let w=g.map(v=>gA(e,v,r));w.some((v,b)=>v!==g[b])&&(t={...t,[m]:w})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=t;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?Xo:ad).source)),f}var yA=new WeakMap;function uee(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of yA.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=gA(t,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var KA=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,a=ot(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=xe(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)xt(n.patternProperties,Iz(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=xe(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let l=yA.get(t);l||(l=[],yA.set(t,l),t.deferred.push(()=>uee(t))),l.push(e)}n.additionalProperties=xe(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=t.io==="input"&&Pd(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},WA=(e,t,r,o)=>{let n=e._zod.def,i=xe(n.innerType,t,o),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},qA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},JA=Symbol();function Az(e,t,r,o,n){let i=!1,s=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(nt(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),JA):JSON.parse(s)}var ZA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s=Az(n.defaultValue,e,t,r,o);s!==JA&&(r.default=s)},GA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let s=Az(n.defaultValue,e,t,r,o);s!==JA&&(r._prefault=s)},XA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{nt(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},YA=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;xe(s,t,o);let a=t.seen.get(e);a.ref=s},QA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},ek=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},sg=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},tk=(e,t,r,o)=>{let n=e._zod.innerType;xe(n,t,o);let i=t.seen.get(e);i.ref=n},og={string:wA,number:vA,boolean:bA,bigint:SA,symbol:_A,null:xA,undefined:EA,void:IA,never:AA,any:kA,unknown:$A,date:TA,enum:PA,literal:CA,nan:RA,template_literal:OA,file:NA,success:DA,custom:zA,function:UA,transform:jA,map:MA,set:LA,array:FA,object:VA,union:ig,intersection:BA,tuple:HA,record:KA,nullable:WA,nonoptional:qA,default:ZA,prefault:GA,catch:XA,pipe:YA,readonly:QA,promise:ek,optional:sg,lazy:tk};function ag(e,t){if("_idmap"in e){let o=e,n=Di({...t,processors:og}),i={};for(let c of o._idmap.entries()){let[u,l]=c;xe(l,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;zi(n,l),xt(s,u,Ui(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Di({...t,processors:og});return xe(e,r),zi(r,e),Ui(r,e)}var cg=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Di({processors:og,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return xe(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,zi(this.ctx,t);let o=Ui(this.ctx,t),{"~standard":n,...i}=o;return i}};var kz={};var qc={};Ce(qc,{ZodAny:()=>xk,ZodArray:()=>kk,ZodBase64:()=>kg,ZodBase64URL:()=>$g,ZodBigInt:()=>Kc,ZodBigIntFormat:()=>Cg,ZodBoolean:()=>Hc,ZodCIDRv4:()=>Ig,ZodCIDRv6:()=>Ag,ZodCUID:()=>wg,ZodCUID2:()=>vg,ZodCatch:()=>Jk,ZodCodec:()=>Ld,ZodCreditCard:()=>hk,ZodCustom:()=>Fd,ZodCustomStringFormat:()=>ua,ZodDate:()=>Nd,ZodDefault:()=>Vk,ZodDiscriminatedUnion:()=>Tk,ZodE164:()=>Tg,ZodEmail:()=>mg,ZodEmoji:()=>gg,ZodEnum:()=>Fc,ZodExactOptional:()=>Dg,ZodFile:()=>jk,ZodFunction:()=>o$,ZodGUID:()=>hg,ZodIBAN:()=>gk,ZodIPv4:()=>xg,ZodIPv6:()=>Eg,ZodISODate:()=>Mi,ZodISODateTime:()=>ji,ZodISODuration:()=>Fi,ZodISOTime:()=>Li,ZodInstanceOf:()=>a$,ZodIntersection:()=>Pk,ZodJWT:()=>Pg,ZodKSUID:()=>_g,ZodLazy:()=>t$,ZodLiteral:()=>Uk,ZodMAC:()=>mk,ZodMap:()=>Dk,ZodNaN:()=>Gk,ZodNanoID:()=>yg,ZodNever:()=>Ik,ZodNonOptional:()=>zg,ZodNull:()=>Sk,ZodNullable:()=>Fk,ZodNumber:()=>Bc,ZodNumberFormat:()=>la,ZodObject:()=>zd,ZodOptional:()=>jd,ZodPipe:()=>Md,ZodPrefault:()=>Hk,ZodPreprocess:()=>Xk,ZodPromise:()=>n$,ZodReadonly:()=>Yk,ZodRecord:()=>Lc,ZodSet:()=>zk,ZodString:()=>Vc,ZodStringFormat:()=>Ee,ZodSuccess:()=>qk,ZodSymbol:()=>vk,ZodTemplateLiteral:()=>e$,ZodTransform:()=>Mk,ZodTuple:()=>Rk,ZodType:()=>te,ZodULID:()=>bg,ZodURL:()=>Od,ZodUUID:()=>Xn,ZodUndefined:()=>bk,ZodUnion:()=>Ud,ZodUnknown:()=>Ek,ZodVoid:()=>Ak,ZodXID:()=>Sg,ZodXor:()=>$k,_ZodString:()=>pg,_default:()=>Bk,_function:()=>MU,any:()=>gU,array:()=>Dd,base64:()=>Gz,base64url:()=>Xz,bigint:()=>dU,boolean:()=>wk,catch:()=>Zk,check:()=>LU,cidrv4:()=>Jz,cidrv6:()=>Zz,codec:()=>DU,creditCard:()=>Qz,cuid:()=>Lz,cuid2:()=>Fz,currencyCode:()=>iU,custom:()=>FU,date:()=>wU,describe:()=>VU,discriminatedUnion:()=>EU,e164:()=>Yz,email:()=>Pz,emoji:()=>jz,enum:()=>Og,exactOptional:()=>Lk,file:()=>CU,float32:()=>aU,float64:()=>cU,function:()=>MU,guid:()=>Cz,hash:()=>sU,hex:()=>oU,hostname:()=>nU,httpUrl:()=>Uz,iban:()=>eU,instanceof:()=>HU,int:()=>dg,int32:()=>uU,int64:()=>fU,intersection:()=>Ck,invertCodec:()=>zU,ipv4:()=>Kz,ipv6:()=>qz,json:()=>WU,jwt:()=>tU,keyof:()=>vU,ksuid:()=>Hz,lazy:()=>r$,literal:()=>PU,looseObject:()=>_U,looseRecord:()=>AU,mac:()=>Wz,map:()=>kU,meta:()=>BU,nan:()=>NU,nanoid:()=>Mz,nativeEnum:()=>TU,never:()=>Rg,nonoptional:()=>Wk,null:()=>_k,nullable:()=>Rd,nullish:()=>RU,number:()=>yk,object:()=>bU,optional:()=>aa,partialRecord:()=>IU,pipe:()=>fg,prefault:()=>Kk,preprocess:()=>qU,promise:()=>jU,readonly:()=>Qk,record:()=>Nk,refine:()=>i$,set:()=>$U,strictObject:()=>SU,string:()=>Cd,stringFormat:()=>rU,stringbool:()=>KU,success:()=>OU,superRefine:()=>s$,symbol:()=>mU,templateLiteral:()=>UU,transform:()=>Ng,tuple:()=>Ok,uint32:()=>lU,uint64:()=>pU,ulid:()=>Vz,undefined:()=>hU,union:()=>Wc,unknown:()=>sa,url:()=>zz,uuid:()=>Rz,uuidv4:()=>Oz,uuidv6:()=>Nz,uuidv7:()=>Dz,void:()=>yU,xid:()=>Bz,xor:()=>xU});var ug={};Ce(ug,{endsWith:()=>Tc,gt:()=>Zn,gte:()=>br,includes:()=>kc,length:()=>oa,lowercase:()=>Ic,lt:()=>Jn,lte:()=>vr,maxLength:()=>na,maxSize:()=>Ni,mime:()=>Cc,minLength:()=>Yo,minSize:()=>Gn,multipleOf:()=>Oi,negative:()=>eg,nonnegative:()=>rg,nonpositive:()=>tg,normalize:()=>Rc,overwrite:()=>dn,positive:()=>Qh,properties:()=>Pc,property:()=>ng,regex:()=>Ec,size:()=>ra,slugify:()=>zc,startsWith:()=>$c,toLowerCase:()=>Nc,toUpperCase:()=>Dc,trim:()=>Oc,uppercase:()=>Ac});var $z=new WeakSet([Object.prototype,Error.prototype]);function lg(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Tz=(e,t)=>{tx.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);$z.has(r)||($z.add(r),lg(r,"format",o=>n=>nd(o,n)),lg(r,"flatten",o=>n=>rd(o,n)),lg(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,lc,2)}),lg(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,lc,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},dee=S("ZodError",Tz),cr=S("ZodError",Tz,void 0,{Parent:Error});var rk=hc(cr),nk=gc(cr),ok=yc(cr),ik=wc(cr),sk=Mm(cr),ak=Lm(cr),ck=Fm(cr),uk=Vm(cr),lk=Bm(cr),dk=Hm(cr),fk=Km(cr),pk=Wm(cr);function pee(){ft.localeError||Ke(Eh())}function ca(){ft.memoizer||Ke({memoizer:Sd()})}var te=S("ZodType",(e,t)=>(pee(),X.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(I.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Se(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(i$(e,t))},superRefine(e,t){return this.check(s$(e,t))},overwrite(e){return this.check(dn(e))},optional(){return aa(this)},exactOptional(){return Lk(this)},nullable(){return Rd(this)},nullish(){return aa(Rd(this))},nonoptional(e){return Wk(this,e)},array(){return Dd(this)},or(e){return Wc([this,e])},and(e){return Ck(this,e)},transform(e){return fg(this,Ng(e))},default(e){return Bk(this,e)},prefault(e){return Kk(this,e)},catch(e){return Zk(this,e)},pipe(e){return fg(this,e)},readonly(){return Qk(this)},describe(e){let t=this.clone();return Et.add(t,{description:e}),t},meta(...e){if(e.length===0)return Et.get(this);let t=this.clone();return Et.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return I.hide(this,"~standard",{...nh(this),jsonSchema:{input:Uc(this,"input"),output:Uc(this,"output")}})},set"~standard"(e){I.own(this,"~standard",e)},parse:function e(t,r){return rk(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await nk(this,t,r,{callee:e})},safeParse(e,t){return ok(this,e,t)},async safeParseAsync(e,t){return ik(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){I.own(this,"spa",e)},validate(e,t){return od(this,e,t)},validateAsync(e,t){return id(this,e,t)},encode:function e(t,r){return sk(this,t,r,{callee:e})},decode:function e(t,r){return ak(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await ck(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await uk(this,t,r,{callee:e})},safeEncode(e,t){return lk(this,e,t)},safeDecode(e,t){return dk(this,e,t)},async safeEncodeAsync(e,t){return fk(this,e,t)},async safeDecodeAsync(e,t){return pk(this,e,t)},toJSONSchema(e){return hA(this,{})(e)},get description(){return Et.get(this)?.description},get _def(){return this._zod.def}}),pg=S("_ZodString",(e,t)=>{Ys.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wA(e,r,o,n)},I.derived({format:e=>ot(e).format??null,minLength:e=>ot(e).minimum??null,maxLength:e=>ot(e).maximum??null},{regex(...e){return this.check(Ec(...e))},includes(...e){return this.check(kc(...e))},startsWith(...e){return this.check($c(...e))},endsWith(...e){return this.check(Tc(...e))},min(...e){return this.check(Yo(...e))},max(...e){return this.check(na(...e))},length(...e){return this.check(oa(...e))},nonempty(...e){return this.check(Yo(1,...e))},lowercase(e){return this.check(Ic(e))},uppercase(e){return this.check(Ac(e))},trim(){return this.check(Oc())},normalize(...e){return this.check(Rc(...e))},toLowerCase(){return this.check(Nc())},toUpperCase(){return this.check(Dc())},slugify(){return this.check(zc())}})),Vc=S("ZodString",(e,t)=>{Ys.init(e,t),pg.init(e,t)},{email(e){return this.check(Rh(mg,e))},url(e){return this.check(Ed(Od,e))},jwt(e){return this.check(Yh(Pg,e))},emoji(e){return this.check(jh(gg,e))},guid(e){return this.check(Oh(hg,e))},uuid(e){return this.check(Nh(Xn,e))},uuidv4(e){return this.check(Dh(Xn,e))},uuidv6(e){return this.check(zh(Xn,e))},uuidv7(e){return this.check(Uh(Xn,e))},nanoid(e){return this.check(Mh(yg,e))},cuid(e){return this.check(Lh(wg,e))},cuid2(e){return this.check(Fh(vg,e))},ulid(e){return this.check(Vh(bg,e))},base64(e){return this.check(Zh(kg,e))},base64url(e){return this.check(Gh($g,e))},xid(e){return this.check(Bh(Sg,e))},ksuid(e){return this.check(Hh(_g,e))},ipv4(e){return this.check(Kh(xg,e))},ipv6(e){return this.check(Wh(Eg,e))},cidrv4(e){return this.check(qh(Ig,e))},cidrv6(e){return this.check(Jh(Ag,e))},e164(e){return this.check(Xh(Tg,e))},datetime(e){return this.check(Id(ji,e))},date(e){return this.check(Ad(Mi,e))},time(e){return this.check(kd(Li,e))},duration(e){return this.check($d(Fi,e))}});function Cd(e){return CI(Vc,e)}var Ee=S("ZodStringFormat",(e,t)=>{_e.init(e,t),pg.init(e,t)}),ji=S("ZodISODateTime",(e,t)=>{SE.init(e,t),Ee.init(e,t)}),Mi=S("ZodISODate",(e,t)=>{_E.init(e,t),Ee.init(e,t)}),Li=S("ZodISOTime",(e,t)=>{xE.init(e,t),Ee.init(e,t)}),Fi=S("ZodISODuration",(e,t)=>{EE.init(e,t),Ee.init(e,t)}),mg=S("ZodEmail",(e,t)=>{lE.init(e,t),Ee.init(e,t)});function Pz(e){return Rh(mg,e)}var hg=S("ZodGUID",(e,t)=>{cE.init(e,t),Ee.init(e,t)});function Cz(e){return Oh(hg,e)}var Xn=S("ZodUUID",(e,t)=>{uE.init(e,t),Ee.init(e,t)});function Rz(e){return Nh(Xn,e)}function Oz(e){return Dh(Xn,e)}function Nz(e){return zh(Xn,e)}function Dz(e){return Uh(Xn,e)}var Od=S("ZodURL",(e,t)=>{pE.init(e,t),Ee.init(e,t)});function zz(e){return Ed(Od,e)}function Uz(e){return Ed(Od,{protocol:sd,hostname:Ex,...I.normalizeParams(e)})}var gg=S("ZodEmoji",(e,t)=>{mE.init(e,t),Ee.init(e,t)});function jz(e){return jh(gg,e)}var yg=S("ZodNanoID",(e,t)=>{hE.init(e,t),Ee.init(e,t)});function Mz(e){return Mh(yg,e)}var wg=S("ZodCUID",(e,t)=>{gE.init(e,t),Ee.init(e,t)});function Lz(e){return Lh(wg,e)}var vg=S("ZodCUID2",(e,t)=>{yE.init(e,t),Ee.init(e,t)});function Fz(e){return Fh(vg,e)}var bg=S("ZodULID",(e,t)=>{wE.init(e,t),Ee.init(e,t)});function Vz(e){return Vh(bg,e)}var Sg=S("ZodXID",(e,t)=>{vE.init(e,t),Ee.init(e,t)});function Bz(e){return Bh(Sg,e)}var _g=S("ZodKSUID",(e,t)=>{bE.init(e,t),Ee.init(e,t)});function Hz(e){return Hh(_g,e)}var xg=S("ZodIPv4",(e,t)=>{IE.init(e,t),Ee.init(e,t)});function Kz(e){return Kh(xg,e)}var mk=S("ZodMAC",(e,t)=>{kE.init(e,t),Ee.init(e,t)});function Wz(e){return OI(mk,e)}var Eg=S("ZodIPv6",(e,t)=>{AE.init(e,t),Ee.init(e,t)});function qz(e){return Wh(Eg,e)}var Ig=S("ZodCIDRv4",(e,t)=>{$E.init(e,t),Ee.init(e,t)});function Jz(e){return qh(Ig,e)}var Ag=S("ZodCIDRv6",(e,t)=>{TE.init(e,t),Ee.init(e,t)});function Zz(e){return Jh(Ag,e)}var kg=S("ZodBase64",(e,t)=>{PE.init(e,t),Ee.init(e,t)});function Gz(e){return Zh(kg,e)}var $g=S("ZodBase64URL",(e,t)=>{CE.init(e,t),Ee.init(e,t)});function Xz(e){return Gh($g,e)}var Tg=S("ZodE164",(e,t)=>{RE.init(e,t),Ee.init(e,t)});function Yz(e){return Xh(Tg,e)}var hk=S("ZodCreditCard",(e,t)=>{OE.init(e,t),Ee.init(e,t)});function Qz(e){return NI(hk,e)}var gk=S("ZodIBAN",(e,t)=>{NE.init(e,t),Ee.init(e,t)});function eU(e){return DI(gk,e)}var Pg=S("ZodJWT",(e,t)=>{DE.init(e,t),Ee.init(e,t)});function tU(e){return Yh(Pg,e)}var ua=S("ZodCustomStringFormat",(e,t)=>{zE.init(e,t),Ee.init(e,t)});function rU(e,t,r={}){return ia(ua,e,t,r)}function nU(e){return ia(ua,"hostname",xx,e)}function oU(e){return ia(ua,"hex",jx,e)}function iU(e){return ia(ua,"currency_code",Ax,e)}function sU(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ur[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return ia(ua,o,n,t)}var Bc=S("ZodNumber",(e,t)=>{ph.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vA(e,r,o,n),e.isFinite=!0},I.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ot(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ot(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ot(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ot(e).format??null},{gt(e,t){return this.check(Zn(e,t))},gte(e,t){return this.check(br(e,t))},min(e,t){return this.check(br(e,t))},lt(e,t){return this.check(Jn(e,t))},lte(e,t){return this.check(vr(e,t))},max(e,t){return this.check(vr(e,t))},int(e){return this.check(dg(e))},safe(e){return this.check(dg(e))},positive(e){return this.check(Zn(0,e))},nonnegative(e){return this.check(br(0,e))},negative(e){return this.check(Jn(0,e))},nonpositive(e){return this.check(vr(0,e))},multipleOf(e,t){return this.check(Oi(e,t))},step(e,t){return this.check(Oi(e,t))},finite(){return this}}));function yk(e){return UI(Bc,e)}var la=S("ZodNumberFormat",(e,t)=>{UE.init(e,t),Bc.init(e,t)});function dg(e){return MI(la,e)}function aU(e){return LI(la,e)}function cU(e){return FI(la,e)}function uU(e){return VI(la,e)}function lU(e){return BI(la,e)}var Hc=S("ZodBoolean",(e,t)=>{hd.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bA(e,r,o,n)});function wk(e){return HI(Hc,e)}var Kc=S("ZodBigInt",(e,t)=>{mh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>SA(e,r,o,n)},I.derived({minValue:e=>ot(e).minimum??null,maxValue:e=>ot(e).maximum??null,format:e=>ot(e).format??null},{gte(e,t){return this.check(br(e,t))},min(e,t){return this.check(br(e,t))},gt(e,t){return this.check(Zn(e,t))},lt(e,t){return this.check(Jn(e,t))},lte(e,t){return this.check(vr(e,t))},max(e,t){return this.check(vr(e,t))},positive(e){return this.check(Zn(BigInt(0),e))},negative(e){return this.check(Jn(BigInt(0),e))},nonpositive(e){return this.check(vr(BigInt(0),e))},nonnegative(e){return this.check(br(BigInt(0),e))},multipleOf(e,t){return this.check(Oi(e,t))}}));function dU(e){return WI(Kc,e)}var Cg=S("ZodBigIntFormat",(e,t)=>{jE.init(e,t),Kc.init(e,t)});function fU(e){return JI(Cg,e)}function pU(e){return ZI(Cg,e)}var vk=S("ZodSymbol",(e,t)=>{ME.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_A(e,r,o,n)});function mU(e){return GI(vk,e)}var bk=S("ZodUndefined",(e,t)=>{LE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>EA(e,r,o,n)});function hU(e){return XI(bk,e)}var Sk=S("ZodNull",(e,t)=>{FE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xA(e,r,o,n)});function _k(e){return YI(Sk,e)}var xk=S("ZodAny",(e,t)=>{VE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kA(e,r,o,n)});function gU(){return QI(xk)}var Ek=S("ZodUnknown",(e,t)=>{BE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$A(e,r,o,n)});function sa(){return eA(Ek)}var Ik=S("ZodNever",(e,t)=>{HE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>AA(e,r,o,n)});function Rg(e){return tA(Ik,e)}var Ak=S("ZodVoid",(e,t)=>{KE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>IA(e,r,o,n)});function yU(e){return rA(Ak,e)}var Nd=S("ZodDate",(e,t)=>{WE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>TA(e,r,o,n),e.min=(r,o)=>e.check(br(r,o)),e.max=(r,o)=>e.check(vr(r,o))},I.derived({minDate:e=>{let{minimum:t}=ot(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ot(e);return t?new Date(t):null}},{}));function wU(e){return nA(Nd,e)}var kk=S("ZodArray",(e,t)=>{ca(),JE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>FA(e,r,o,n),e.element=t.element},{min(e,t){return this.check(Yo(e,t))},nonempty(e){return this.check(Yo(1,e))},max(e,t){return this.check(na(e,t))},length(e,t){return this.check(oa(e,t))},unwrap(){return this.element}});function Dd(e,t){return sA(kk,e,t)}function vU(e){let t=e._zod.def.shape;return Og(Object.keys(t))}var zd=S("ZodObject",(e,t)=>{ca(),ZE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>VA(e,r,o,n),I.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Og(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(I.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(I.mergeDefs(this._zod.def,{catchall:sa()}))},loose(){return this.clone(I.mergeDefs(this._zod.def,{catchall:sa()}))},strict(){return this.clone(I.mergeDefs(this._zod.def,{catchall:Rg()}))},strip(){return this.clone(I.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return I.extend(this,e)},safeExtend(e){return I.safeExtend(this,e)},merge(e){return I.merge(this,e)},pick(e){return I.pick(this,e)},omit(e){return I.omit(this,e)},partial(...e){return I.partial(jd,this,e[0])},exactPartial(...e){return I.partial(Dg,this,e[0],"exactPartial")},required(...e){return I.required(zg,this,e[0])}});function bU(e,t){let r={type:"object",shape:e??{},...I.normalizeParams(t)};return new zd(r)}function SU(e,t){return new zd({type:"object",shape:e,catchall:Rg(),...I.normalizeParams(t)})}function _U(e,t){return new zd({type:"object",shape:e,catchall:sa(),...I.normalizeParams(t)})}var Ud=S("ZodUnion",(e,t)=>{gd.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ig(e,r,o,n),e.options=t.options});function Wc(e,t){return new Ud({type:"union",options:e,...I.normalizeParams(t)})}var $k=S("ZodXor",(e,t)=>{Ud.init(e,t),GE.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ig(e,r,o,n),e.options=t.options});function xU(e,t){return new $k({type:"union",options:e,inclusive:!1,...I.normalizeParams(t)})}var Tk=S("ZodDiscriminatedUnion",(e,t)=>{Ud.init(e,t),YE.init(e,t)});function EU(e,t,r){return new Tk({type:"union",options:t,discriminator:e,...I.normalizeParams(r)})}var Pk=S("ZodIntersection",(e,t)=>{QE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>BA(e,r,o,n)});function Ck(e,t){return new Pk({type:"intersection",left:e,right:t})}var Rk=S("ZodTuple",(e,t)=>{ca(),hh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>HA(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new jd({type:"optional",innerType:t}))})}});function Ok(e,t,r){let o=t instanceof X,n=o?r:t,i=o?t:null;return new Rk({type:"tuple",items:e,rest:i,...I.normalizeParams(n)})}var Lc=S("ZodRecord",(e,t)=>{ca(),eI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>KA(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Nk(e,t,r){return!t||!t._zod?new Lc({type:"record",keyType:Cd(),valueType:e,...I.normalizeParams(t)}):new Lc({type:"record",keyType:e,valueType:t,...I.normalizeParams(r)})}function IU(e,t,r){return new Lc({type:"record",keyType:e,valueType:t,...I.normalizeParams(r),partial:!0})}function AU(e,t,r){return new Lc({type:"record",keyType:e,valueType:t,mode:"loose",...I.normalizeParams(r)})}var Dk=S("ZodMap",(e,t)=>{ca(),tI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>MA(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Gn(...r)),e.nonempty=r=>e.check(Gn(1,r)),e.max=(...r)=>e.check(Ni(...r)),e.size=(...r)=>e.check(ra(...r))});function kU(e,t,r){return new Dk({type:"map",keyType:e,valueType:t,...I.normalizeParams(r)})}var zk=S("ZodSet",(e,t)=>{ca(),rI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>LA(e,r,o,n),e.min=(...r)=>e.check(Gn(...r)),e.nonempty=r=>e.check(Gn(1,r)),e.max=(...r)=>e.check(Ni(...r)),e.size=(...r)=>e.check(ra(...r))});function $U(e,t){return new zk({type:"set",valueType:e,...I.normalizeParams(t)})}var Fc=S("ZodEnum",(e,t)=>{nI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(o,n,i)=>PA(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Fc({...t,checks:[],...I.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Fc({...t,checks:[],...I.normalizeParams(n),entries:i})}});function Og(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Fc({type:"enum",entries:r,...I.normalizeParams(t)})}function TU(e,t){return new Fc({type:"enum",entries:e,...I.normalizeParams(t)})}var Uk=S("ZodLiteral",(e,t)=>{oI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>CA(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function PU(e,t){return new Uk({type:"literal",values:Array.isArray(e)?e:[e],...I.normalizeParams(t)})}var jk=S("ZodFile",(e,t)=>{iI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>NA(e,r,o,n),e.min=(r,o)=>e.check(Gn(r,o)),e.max=(r,o)=>e.check(Ni(r,o)),e.mime=(r,o)=>e.check(Cc(Array.isArray(r)?r:[r],o))});function CU(e){return aA(jk,e)}var Mk=S("ZodTransform",(e,t)=>{ca(),sI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jA(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Ci(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(I.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=e),r.issues.push(I.issue(s))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function Ng(e){return new Mk({type:"transform",transform:e})}var jd=S("ZodOptional",(e,t)=>{gh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sg(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function aa(e){return new jd({type:"optional",innerType:e})}var Dg=S("ZodExactOptional",(e,t)=>{aI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sg(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Lk(e){return new Dg({type:"optional",innerType:e})}var Fk=S("ZodNullable",(e,t)=>{cI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>WA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Fk({type:"nullable",innerType:e})}function RU(e){return aa(Rd(e))}var Vk=S("ZodDefault",(e,t)=>{uI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ZA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bk(e,t){return new Vk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():I.shallowClone(t)}})}var Hk=S("ZodPrefault",(e,t)=>{lI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>GA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Kk(e,t){return new Hk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():I.shallowClone(t)}})}var zg=S("ZodNonOptional",(e,t)=>{dI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Wk(e,t){return new zg({type:"nonoptional",innerType:e,...I.normalizeParams(t)})}var qk=S("ZodSuccess",(e,t)=>{fI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>DA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function OU(e){return new qk({type:"success",innerType:e})}var Jk=S("ZodCatch",(e,t)=>{pI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>XA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Zk(e,t){return new Jk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:I.constantCatch(t)})}var Gk=S("ZodNaN",(e,t)=>{mI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>RA(e,r,o,n)});function NU(e){return iA(Gk,e)}var Md=S("ZodPipe",(e,t)=>{yh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>YA(e,r,o,n),e.in=t.in,e.out=t.out});function fg(e,t){return new Md({type:"pipe",in:e,out:t})}var Ld=S("ZodCodec",(e,t)=>{Md.init(e,t),yd.init(e,t)});function DU(e,t,r){return new Ld({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function zU(e){let t=e._zod.def;return new Ld({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Xk=S("ZodPreprocess",(e,t)=>{Md.init(e,t),hI.init(e,t)}),Yk=S("ZodReadonly",(e,t)=>{gI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>QA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Qk(e){return new Yk({type:"readonly",innerType:e})}var e$=S("ZodTemplateLiteral",(e,t)=>{yI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>OA(e,r,o,n)});function UU(e,t){return new e$({type:"template_literal",parts:e,...I.normalizeParams(t)})}var t$=S("ZodLazy",(e,t)=>{wd.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>tk(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function r$(e){return new t$({type:"lazy",getter:e})}var n$=S("ZodPromise",(e,t)=>{vI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ek(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function jU(e){return new n$({type:"promise",innerType:e})}var o$=S("ZodFunction",(e,t)=>{wI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>UA(e,r,o,n)});function MU(e){return new o$({type:"function",input:Array.isArray(e?.input)?Ok(e?.input):e?.input??Dd(sa()),output:e?.output??sa()})}var Fd=S("ZodCustom",(e,t)=>{bI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zA(e,r,o,n)});function LU(e){let t=new Ae({check:"custom"});return t._zod.check=e,t}function FU(e,t){return cA(Fd,e??(()=>!0),t)}function i$(e,t={}){return uA(Fd,e,t)}function s$(e,t){return lA(e,t)}var VU=dA,BU=fA,a$=S("ZodInstanceOf",(e,t)=>{Fd.init(e,t)},{properties(e,t){return this.check(Pc(e,t))}});function HU(e,t={}){let r=new a$({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...I.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var KU=(...e)=>pA({Codec:Ld,Boolean:Hc,String:Vc},...e);function WU(e){let t=r$(()=>Wc([Cd(e),yk(),wk(),_k(),Dd(t),Nk(Cd(),t)]));return t}function qU(e,t){return new Xk({type:"pipe",in:Ng(e),out:t})}var mee={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function hee(e){Ke({customError:e})}function gee(){return Ke().customError}var c$;c$||(c$={});var Vd={};Ce(Vd,{ZodISODate:()=>Mi,ZodISODateTime:()=>ji,ZodISODuration:()=>Fi,ZodISOTime:()=>Li,date:()=>wee,datetime:()=>yee,duration:()=>bee,time:()=>vee});function yee(e){return Id(ji,e)}function wee(e){return Ad(Mi,e)}function vee(e){return kd(Li,e)}function bee(e){return $d(Fi,e)}var z={...qc,...ug,iso:Vd},See=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function _ee(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function JU(e,t){return e.map((r,o)=>o<t?r:r.optional())}function xee(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Eee(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:xee(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function Iee(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let s of i){let a=t.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(e)}function u$(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let s of e){let a=u$(s,t);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let s=u$(e[i],t);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var Aee=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),kee=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Bd(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Bd):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>Aee.has(t)?Bd(r):!kee.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Bd))}function ZU(e){return e===1?"element":"elements"}function $ee(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=u$(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,s=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(t.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${ZU(i)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${ZU(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function GU(e,t){if(e!==!1)return e===void 0||e===!0?z.any():Xt(e,t)}var Tee=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function XU(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return z.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=Eee(n,t),s=Xt(i,t);return t.refs.set(n,s),t.processing.delete(n),s}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return z.null();if(n.length===0)return z.never();if(n.length===1)return z.literal(n[0]);if(n.every(s=>typeof s=="string"))return z.enum(n);let i=n.map(s=>z.literal(s));return i.length<2?i[0]:z.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return z.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...e,type:i};return XU(s,t)});return n.length===0?z.never():n.length===1?n[0]:z.union(n)}if(!r)return z.any();let o;switch(r){case"string":{let n=z.string();if(e.format){let i=e.format;i==="email"?n=n.check(z.email()):i==="uri"||i==="uri-reference"?n=n.check(z.url()):i==="uuid"||i==="guid"?n=n.check(z.uuid()):i==="date-time"?n=n.check(z.iso.datetime({offset:!0})):i==="date"?n=n.check(z.iso.date()):i==="time"?n=n.check(z.regex(Tee)):i==="duration"?n=n.check(z.iso.duration()):i==="hostname"?n=n.check(z.hostname()):i==="ipv4"?n=n.check(z.ipv4()):i==="ipv6"?n=n.check(z.ipv6()):i==="mac"?n=n.check(z.mac()):i==="cidr"?n=n.check(z.cidrv4()):i==="cidr-v6"?n=n.check(z.cidrv6()):i==="base64"?n=n.check(z.base64()):i==="base64url"?n=n.check(z.base64url()):i==="e164"?n=n.check(z.e164()):i==="credit_card"?n=n.check(z.creditCard()):i==="iban"?n=n.check(z.iban()):i==="jwt"?n=n.check(z.jwt()):i==="emoji"?n=n.check(z.emoji()):i==="nanoid"?n=n.check(z.nanoid()):i==="cuid"?n=n.check(z.cuid()):i==="cuid2"?n=n.check(z.cuid2()):i==="ulid"?n=n.check(z.ulid()):i==="xid"?n=n.check(z.xid()):i==="ksuid"&&(n=n.check(z.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?z.number().int():z.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=z.boolean();break}case"null":{o=z.null();break}case"object":{let n={},i=e.properties||{},s=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Xt(e.additionalProperties,t):void 0;for(let[d,p]of Object.entries(i)){let f=Xt(p,t);xt(n,d,s.has(d)?f:f.optional())}if(e.patternProperties){let d=e.patternProperties,p=Object.keys(d),f=[];for(let g of p){let w=Xt(d[g],t),v=z.string().regex(new RegExp(g));f.push(z.looseRecord(v,w))}let m=[];if(Object.keys(n).length>0&&m.push(z.object(n).passthrough()),m.push(...f),m.length===0)o=z.object({}).passthrough();else if(m.length===1)o=m[0];else{let g=z.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)g=z.intersection(g,m[w]);o=g}if(e.additionalProperties===!1){let g=Object.keys(n),w=p.map(b=>new RegExp(b)),v=o;o=o.check(b=>{if(!Dr(b.value))return;let x=[];for(let E of Object.keys(b.value))g.includes(E)||w.some(T=>T.test(E))||x.push(E);x.length&&b.issues.push({code:"unrecognized_keys",keys:x,input:b.value,inst:v})})}}else{let d=z.object(n);e.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=Xt(p,t)}o=Iee(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let s=typeof e.minItems=="number"?e.minItems:0,a=n.map(d=>Xt(d,t)),c=JU(a,s),u=Array.isArray(i)?void 0:GU(i,t),l=z.tuple(c);o=u?l.rest(u):l,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(Array.isArray(i)){let s=typeof e.minItems=="number"?e.minItems:0,a=i.map(d=>Xt(d,t)),c=JU(a,s),u=GU(e.additionalItems,t),l=z.tuple(c);o=u?l.rest(u):l,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(i!==void 0){let s=Xt(i,t),a=z.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),o=a}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=$ee(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Xt(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Xt(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r=XU(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Xt(u,t)),c=z.union(a);r=o?z.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Xt(u,t)),c=z.xor(a);r=o?z.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:z.any();else{let a=o?r:Xt(e.allOf[0],t),c=o?0:1;for(let u=c;u<e.allOf.length;u++)a=z.intersection(a,Xt(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=z.nullable(r)),e.readOnly===!0&&(r=z.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in e&&(n[a]=e[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in e&&(n[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Bd(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(n[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Bd(e.contains)&&(n.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(n[a]=e[a])}for(let a of Object.keys(e))See.has(a)||xt(n,a,e[a]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function YU(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=_ee(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??Et};return Xt(r,i)}var QU=Symbol("z.visit/resolving");function Hd(e,t){let r=typeof t=="function"?t:(s,a)=>{let c=t[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===QU)return new wd({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,QU);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let g=n(u[m]);g!==u[m]&&(d=!0),p[m]=g}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?Se(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:Se(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?Se(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:Se(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:Se(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?Se(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:Se(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:Se(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:Se(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:Se(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return Se(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(e)}function e4(e){return Hd(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Wc(r.options)}})}function Pee(e,t){if(!t?.length)return e;let r=e._zod.def;return Se(e,un(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function t4(e){return Pee(e.out,e.checks)}function Cee(e){return e.in._zod.traits.has("$ZodTransform")?t4(e):e.in}function r4(e){return Hd(e,{pipe:t=>Cee(t._zod.def),default:(t,r)=>r?aa(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function n4(e){return Hd(e,{pipe:t=>t4(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var l$={};Ce(l$,{bigint:()=>Dee,boolean:()=>Nee,date:()=>zee,number:()=>Oee,string:()=>Ree});function Ree(e){return RI(Vc,e)}function Oee(e){return jI(Bc,e)}function Nee(e){return KI(Hc,e)}function Dee(e){return qI(Kc,e)}function zee(e){return oA(Nd,e)}var Ug={name:"@tomato414941/foundation",version:"30.1.0",description:"Manage Foundation resources and use them in local commands.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&h.config({jitless:!0});function o4(e){let t=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(e.trim());if(!t)return null;try{let r=Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==t[1])return null;if(t[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(t[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(t[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var i4=h.string().trim().max(8192).refine(e=>o4(e)!==null,"Use an OpenSSH public key from a .pub file.");function s4(e){if(!o4(e))throw new Error("Use an OpenSSH public key from a .pub file.");let[t,r]=e.trim().split(/[ \t]+/);return{algorithm:t,key:r,publicKey:t+" "+r}}var e_e=h.string().max(32).regex(/^[a-z_][a-z0-9_-]*$/,"Use a lowercase account name."),a4=h.string().min(1).max(253).regex(/^[A-Za-z0-9_.:]+(?:-[A-Za-z0-9_.:]+)*$/,"Use a host name or IP address."),c4=h.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/);var f$=new TextEncoder,Mg=new TextDecoder,u4=new TextDecoder("utf-8",{fatal:!0}),jg=2**32;function fn(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function d$(e,t,r){if(t<0||t>=jg)throw new RangeError(`value must be >= 0 and <= ${jg-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function p$(e){let t=Math.floor(e/jg),r=e%jg,o=new Uint8Array(8);return d$(o,t,0),d$(o,r,4),o}function Lg(e){let t=new Uint8Array(4);return d$(t,e),t}var jee=/[^\x00-\x7f]/;function ei(e){if(typeof e=="string"&&e.length>=128){if(jee.test(e))throw new TypeError("non-ASCII string encountered in encode()");return f$.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=o}return t}function l4(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,o=[];for(let i=0;i<e.length;i+=r)o.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));let n=btoa(o.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function d4(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function Fg(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}var da=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Kd=class extends da{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pe=class extends da{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Vi=class extends da{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}},N=class extends da{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"};var Wd=class extends da{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var Mee="The input to be decoded is not correctly encoded.";function fa(e){try{return d4(typeof e=="string"?e:Mg.decode(e),!0)}catch(t){throw new TypeError(Mee,{cause:t})}}function it(e){return l4(typeof e=="string"?f$.encode(e):e,!0)}function pn(e,t){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be an instance of Uint8Array`)}function st(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Vg(...e){let t=new Set;for(let r of e)if(r)for(let o of Object.keys(r)){if(t.has(o))return!1;t.add(o)}return!0}function Yn(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}function mn(e,t,r){try{return fa(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function f4(e,t,r){try{return ei(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}function Bg(e,t,r){let o;try{o=JSON.parse(u4.decode(fa(e)))}catch{throw new t(r)}if(!st(o))throw new t(r);return o}var Hg={__proto__:null};function m$(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function p4(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Kg(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of o.crit){if(!(s in i))throw new Pe(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function Wg(e,t){let r,o;try{r=JSON.stringify(t),o=JSON.parse(r)}catch(n){throw new e("JOSE Header is not valid JSON",{cause:n})}if(!st(o))throw new e("JOSE Header is not a JSON object");return[o,r]}var Lee=e=>e[Symbol.toStringTag],Fee=(e,t,r)=>{let{alg:o}=e;if(t.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let n=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function pa(e,t,r){let{alg:o,secret:n}=e,i=r==="decrypt"||r==="sign";if(n&&t instanceof Uint8Array)return t;let s,a;if(st(t)){if(s=b$(t),typeof s.kty!="string")throw m4(o,t,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(Fee(e,s,r),s.kty==="oct")return fa(s.k);if(!Object.isFrozen(t)){let{key_ops:l}=t;Array.isArray(l)&&Object.freeze(l),Object.freeze(t)}}else{if(!y$(t))throw m4(o,t,n);let l=n?"secret":i?"private":"public";if(t.type!==l&&(n||["secret","public","private"].includes(t.type)))throw new TypeError(`${Lee(t)} instances must be of type "${l}" for the ${o} algorithm`);if(Bi(t))return t;if(a=t,a.type==="secret")return a.export()}h$||=new WeakMap;let c=t,u=h$.get(c);if(u?.[o])return u[o];if(u||h$.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Vee[a.asymmetricKeyDetails?.namedCurve],p=e.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[o]=a.toCryptoKey(p,l,e.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await Jc(e,s)}var h$,Vee={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function Jg(e){if(!Bi(e))throw new Error("CryptoKey instance expected")}var Bi=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},g$=e=>e?.[Symbol.toStringTag]==="KeyObject",y$=e=>Bi(e)||g$(e);function h4(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var ti=(e,...t)=>h4("Key must be ",e,...t);function m4(e,t,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(h4(`Key for the ${e} algorithm must be `,t,...o))}var qg=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function w$(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function g4(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function v$(e,t,r){let o=e.algorithm;if(o.name!==t.name)throw qg(t.name);if(t.hash&&o.hash?.name!==t.hash)throw qg(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw qg(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&o.length!==t.length)throw qg(t.length,"algorithm.length");w$(e,r)}function Zg(e){return{__proto__:null,...e}}function b$(e){let t=Zg(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=o}return t}function Gg(e){if(e!==void 0&&typeof e!="boolean")throw new TypeError('"extractable" option must be a boolean');return e}async function Jc(e,t,r){if(!e.kty.includes(t.kty))throw new Pe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),i={...t,ext:r??t.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,t.key_ops??e.usages[n?1:0])}async function ma(e,t,r,o=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,o,[r])),v$(e,t,r),e}var ha=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function Xg(e,t){let r=e.byteLength<<3;if(r!==t)throw new N(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var Bee=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function y4(e,t){if(t.length<<3!==e.ivBits)throw new N("Invalid Initialization Vector length")}async function w4(e,t,r){if(!(t instanceof Uint8Array))throw new TypeError(ti(t,"Uint8Array"));let o=e.cekBits>>1,n=await crypto.subtle.importKey("raw",t.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",t.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function v4(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function Hee(e,t,r,o,n){let[i,s,a]=await w4(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,t)),u=fn(n,o,c,p$(n.length*8)),l=await v4(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Kee(e,t){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,e);return crypto.subtle.verify(r,o,n,t)}async function Wee(e,t,r,o,n,i){let[s,a,c]=await w4(e,t,"decrypt"),u=fn(i,o,r,p$(i.length*8)),l=await v4(a,u,c);try{if(await Kee(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Vi}async function Yg(e,t,r,o,n){if(!Bi(r)&&!(r instanceof Uint8Array))throw new TypeError(ti(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?y4(e,o):o=Bee(e),r instanceof Uint8Array&&Xg(r,e.cekBits),e.cbc)return Hee(e,t,r,o,n);let i=await ma(r,e.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,t));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function Qg(e,t,r,o,n,i){if(!Bi(t)&&!(t instanceof Uint8Array))throw new TypeError(ti(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new N("JWE Initialization Vector missing");if(!n)throw new N("JWE Authentication Tag missing");if(!e.cbc&&n.length!==16)throw new N("Invalid Authentication Tag length");if(y4(e,o),t instanceof Uint8Array&&Xg(t,e.cekBits),e.cbc)return Wee(e,t,r,o,n,i);let s=await ma(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,fn(r,n)))}catch{throw new Vi}}function qd(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var qee=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Jee=[[],["deriveBits"]],ry=[[],[]];function ey(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:qee,ops:["wrapKey","unwrapKey"]}}function ty(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:t,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(t==="OKP")throw new Pe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Jee,ops:[void 0,"deriveBits"]}}function Zc(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:ry,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function S$(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:ry,ops:["deriveBits","deriveBits"]}}var ri=qd({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:ry,ops:["encrypt","decrypt"]},"RSA-OAEP":ey(1),"RSA-OAEP-256":ey(256),"RSA-OAEP-384":ey(384),"RSA-OAEP-512":ey(512),"ECDH-ES":ty("direct-key-agreement"),"ECDH-ES+A128KW":ty("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":ty("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":ty("key-agreement-with-key-wrapping"),A128KW:Zc(128),A192KW:Zc(192),A256KW:Zc(256),A128GCMKW:Zc(128,!0),A192GCMKW:Zc(192,!0),A256GCMKW:Zc(256,!0),"PBES2-HS256+A128KW":S$(),"PBES2-HS384+A192KW":S$(),"PBES2-HS512+A256KW":S$()}),Zee=["encrypt","decrypt"];function Gc(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:ry,ops:Zee,cekBits:e,ivBits:t?128:96,cbc:t}}var Gee=qd({A128GCM:Gc(128),A192GCM:Gc(192),A256GCM:Gc(256),"A128CBC-HS256":Gc(256,!0),"A192CBC-HS384":Gc(384,!0),"A256CBC-HS512":Gc(512,!0)});function b4(e,t){throw new Pe(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function hn(e){return(typeof e=="string"?ri[e]:void 0)??b4("alg","Algorithm")}function gn(e){return e.mode==="key-wrapping"||e.mode==="key-encryption"||e.mode==="key-agreement-with-key-wrapping"}function ga(e){return(typeof e=="string"?Gee[e]:void 0)??b4("enc","Encryption Algorithm")}function S4(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");w$(e,t)}async function Xee(e,t,r){let o=await ma(t,hn(e).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function Yee(e,t,r){let o=await ma(t,hn(e).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function x4(e,t,r){v$(t,hn(e).subtle,r),g4(e,t)}async function E4(e,t,r,o){if(!(e instanceof Uint8Array)||e.length<8)throw new N("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new N("PBES2 Count Input must be a positive integer");let n=fn(ei(t),Uint8Array.of(0),e),i=parseInt(t.slice(13,16),10),s={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await ma(o,hn(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function _$(e){return fn(Lg(e.length),e)}async function Qee(e,t,r){let o=t>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await Fg("sha256",fn(Lg(a),e,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function I4(e,t,r,o,n=new Uint8Array,i=new Uint8Array){S4(e),S4(t,"deriveBits");let s=fn(_$(ei(r)),_$(n),_$(i),Lg(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return Qee(a,o,s)}function A4(e){Jg(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new Pe("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ny(e,t){let r=e[t];if(r!==void 0){if(typeof r!="string")throw new N(`JOSE Header "${t}" (Agreement Party${t==="apu"?"U":"V"}Info) invalid`);return mn(r,t,N)}}function k4(e,t){if(!(e===void 0||t===void 0||e.byteLength!==t.byteLength)){for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return;throw new N('JOSE Header "apu" and "apv" values must be distinct')}}function ete(e){if(e===void 0)throw new N("JWE Encrypted Key missing")}function _4(e){if(e!==void 0)throw new N("Encountered unexpected JWE Encrypted Key")}function tte(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function $4(e,t,r,o,n,i){let{alg:s}=e,a=e.mode;if(a==="direct-encryption")return _4(o),r;let c=a==="direct-key-agreement";switch(c?_4(o):ete(o),e.subtle.name){case"ECDH":{let{epk:u}=n;if(!st(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new N('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');A4(r);let l=await Jc(e,u),d=ny(n,"apu"),p=ny(n,"apv");k4(d,p);let f=await I4(l,r,c?t.alg:s,c?t.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return Jg(r),x4(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new N('JOSE Header "p2c" (PBES2 Count) missing or invalid');tte(i);let u=i??1e4;if(n.p2c>u)throw new N('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new N('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=mn(n.p2s,"p2s",N);r=await E4(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new N('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new N('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=mn(n.iv,"iv",N),l=mn(n.tag,"tag",N);if(u.byteLength!==12)throw new N("Invalid Initialization Vector length");if(l.byteLength!==16)throw new N("Invalid Authentication Tag length");return Qg(ga(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Yee(s.slice(-6),r,o)}async function oy(e,t,r,o,n,i={}){let{alg:s,mode:a}=e,c=gn(e);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await pa(a==="direct-encryption"?t:e,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??ha(t):void 0;l&&Xg(l,t.cekBits);let d,p;switch(e.subtle.name){case"ECDH":{A4(u);let{apu:f,apv:m}=i;f!==void 0&&pn(f,'"apu"'),m!==void 0&&pn(m,'"apv"');let g=f??ny(o,"apu"),w=m??ny(o,"apv");k4(g,w);let v;i.epk!==void 0?v=await pa(e,i.epk,"decrypt"):v=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,x=v;if(!x.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await b.getPublicKey(v,[])}let{x:E,y:T,crv:R,kty:U}=await b.exportKey("jwk",x),j=a==="direct-key-agreement",Y=await I4(u,v,j?t.alg:s,j?t.cekBits:parseInt(s.slice(-5,-2),10),g,w),B={x:E,crv:R,kty:U};if(U==="EC"&&(B.y=T),p={epk:B},f!==void 0&&(p.apu=it(f)),m!==void 0&&(p.apv=it(m)),j)return[Y,void 0,p];u=Y;break}case"RSA-OAEP":{Jg(u),x4(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await E4(m,s,f,u),p={p2c:f,p2s:it(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await Yg(ga(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:it(m.iv),tag:it(m.tag)}}}if(d??=await Xee(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function iy(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new Pe('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new N('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function T4(e){if(typeof globalThis[e]>"u")throw new Pe(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function P4(e,t,r=1/0){let o=e.writable.getWriter();o.write(t).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=e.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new N("Decompressed plaintext exceeded the configured limit")}return fn(...n)}async function C4(e){return T4("CompressionStream"),P4(new CompressionStream("deflate-raw"),e)}async function R4(e,t){return T4("DecompressionStream"),P4(new DecompressionStream("deflate-raw"),e,t)}function O4(e){let{aad:t,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=e;if(o!==void 0&&(typeof o!="string"||!o))throw new N("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new N("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new N("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new N("JWE Protected Header incorrect type");if(t!==void 0&&(typeof t!="string"||!t))throw new N("JWE AAD incorrect type");if(s!==void 0&&!st(s))throw new N("JWE Shared Unprotected Header incorrect type");return{aad:t,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function N4(e){let t,r;try{let{header:o}=e;if(st(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),t=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else t=o;let{encrypted_key:n}=e;return[{encrypted_key:n,header:t},r]}catch(o){return[void 0,r,o]}}function D4(e){let{encrypted_key:t,header:r}=e;if(t!==void 0&&typeof t!="string")throw new N("JWE Encrypted Key incorrect type");if(r!==void 0&&!st(r))throw new N("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected===void 0&&r===void 0&&e.unprotected===void 0)throw new N("JOSE Header missing")}function x$(e){let{protected:t,ciphertext:r,iv:o,tag:n,aad:i}=e,s;return t!==void 0&&(s=Bg(t,N,"JWE Protected Header is invalid")),[s,mn(r,"ciphertext",N),o!==void 0?mn(o,"iv",N):void 0,n!==void 0?mn(n,"tag",N):void 0,f4((t??"")+(i!==void 0?`.${i}`:""),"aad",N)]}function sy(e){return[e&&m$("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&m$("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function E$(e,t,r,o=x$(e)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=e,p;if(u!==void 0||l!==void 0){if(!Vg(n,u,l))throw new N("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,g,w,v]=t,{encrypted_key:b}=e;Kg(N,Hg,g,n,p),iy(p,n);let{alg:x,enc:E}=p;if(typeof x!="string"||!x)throw new N("missing JWE Algorithm (alg) in JWE Header");let T=ri[x];if(b===""&&(!T||!gn(T)))throw new N("JWE Encrypted Key incorrect type");let R=T?.mode==="integrated-encryption";if(!R&&(typeof E!="string"||!E))throw new N("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(x)||!f&&x.startsWith("PBES2"))throw new Kd('"alg" (Algorithm) Header Parameter value not allowed');let U;if(R){if(E!==void 0)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new N("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new N("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(E))throw new Kd('"enc" (Encryption Algorithm) Header Parameter value not allowed');U=ga(E)}let j;if(b!==void 0)try{j=mn(b,"encrypted_key",N)}catch(le){if(!T||!gn(T))throw le;j=new Uint8Array}let Y=!1;typeof r=="function"&&(r=await r(n,e),Y=!0);let B=T??hn(x);gn(B)&&j===void 0&&(j=new Uint8Array);let ge=await pa(B.mode==="direct-encryption"?U:B,r,"decrypt"),me;if(B.mode==="integrated-encryption")me=await B.decrypt(ge,j,i,c,n,p);else{let le=U,F;try{F=await $4(B,le,ge,j,p,w),gn(B)&&F instanceof Uint8Array&&F.byteLength<<3!==le.cekBits&&(F=ha(le))}catch(Me){if(Me instanceof TypeError||Me instanceof N||Me instanceof Pe)throw Me;F=ha(le)}me=await Qg(le,F,i,s,a,c)}if(p.zip==="DEF"){let le=v??25e4;if(le===0)throw new Pe('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(le!==1/0&&(!Number.isSafeInteger(le)||le<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");me=await R4(me,le).catch(F=>{throw F instanceof N?F:new N("Failed to decompress plaintext",{cause:F})})}return{plaintext:me,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:mn(d,"aad",N)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Y&&{key:ge}}}async function z4(e,t,r){if(e instanceof Uint8Array&&(e=Mg.decode(e)),typeof e!="string")throw new N("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=e.split(".");if(c!==5)throw new N("Invalid Compact JWE");return E$({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},t,r)}async function Jd(e,t,r){return z4(e,sy(r),t)}async function I$(e,t,r){if(!st(e))throw new N("General JWE must be an object");let o=e.recipients;if(!Array.isArray(o))throw new N("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(st))throw new N("JWE Recipients missing or incorrect type");if(!n.length)throw new N("JWE Recipients has no members");let i,s,a;try{i=sy(r),s=O4(e),a=x$(s)}catch{throw new Vi}let c=n.map(u=>N4(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?ri[l]:void 0;if(d&&!gn(d))throw new N(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return D4(l),await E$(l,i,t,a)}catch{}throw new Vi}function ay(e,t,r){if(!Vg(e,t,r))throw new N("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function A$(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new N("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");t!==void 0&&(e[8]=t?.crit);let[,o,n,i,s,a,c,u,l]=e;if(s!==void 0&&pn(s,"JWE Additional Authenticated Data"),a!==void 0&&pn(a,"JWE Content Encryption Key"),c!==void 0&&pn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Wg(N,o)[0],e[1]=o),n!==void 0&&(n=Wg(N,n)[0],e[2]=n),!r&&i!==void 0&&(i=Wg(N,i)[0],e[3]=i),u!==void 0&&!st(u))throw new TypeError("JWE Key Management Parameters must be an object");ay(o,n,i);let d={...o,...n,...i};p4(N,o),Kg(N,Hg,l,o,d),iy(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new N('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=ri[p];if(m?.mode==="integrated-encryption"){if(f!==void 0)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,ga(f),m]}async function k$(e,t,r){let[o,n,i]=t,[s,a,c,u,l,d,p,f,,m]=e,g=a,w=c,v=i??hn(o.alg),b,x,E;v.mode==="integrated-encryption"?E=await pa(v,r,"encrypt"):[E,b,x]=await oy(v,n,r,o,d,f),x&&(m?w=w?{...w,...x}:x:g=g?{...g,...x}:x,ay(g,w,u));let T=g?it(JSON.stringify(g)):"",R=l?.byteLength?it(l):void 0,U=ei(R?`${T}.${R}`:T),j=s;o.zip==="DEF"&&(j=await C4(j).catch(le=>{throw new N("Failed to compress plaintext",{cause:le})}));let Y,B,ge;v.mode==="integrated-encryption"?[b,Y]=await v.encrypt(E,j,U,g,o,f):{ciphertext:Y,tag:B,iv:ge}=await Yg(n,j,E,p,U);let me={ciphertext:it(Y)};return ge&&(me.iv=it(ge)),B&&(me.tag=it(B)),b?.byteLength&&(me.encrypted_key=it(b)),R&&(me.aad=R),g&&(me.protected=T),u&&(me.unprotected=u),w&&(me.header=w),me}async function U4(e,t,r){return k$(e,A$(e,r),t)}function j4(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(".")}var $$=class{#e;state;constructor(t,r,o){this.#e=t,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(t){return Yn(this.state[0],"setUnprotectedHeader"),this.state[0]=t,this}setKeyManagementParameters(t){return Yn(this.state[1],"setKeyManagementParameters"),this.state[1]=t,this}addRecipient(...t){return this.#e.addRecipient(...t)}encrypt(...t){return this.#e.encrypt(...t)}done(){return this.#e}},Zd=class{#e;#t=[];#r;#n;#o;constructor(t){this.#e=t}addRecipient(t,r){let o=new $$(this,t,r?.crit);return this.#t.push(o),o}setProtectedHeader(t){return Yn(this.#r,"setProtectedHeader"),this.#r=t,this}setSharedUnprotectedHeader(t){return Yn(this.#n,"setSharedUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#o=t,this}async encrypt(){if(!this.#t.length)throw new N("at least one recipient must be added");pn(this.#e,"plaintext");let t=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[g,w,v,b]=m.state,x=[this.#e,o,g,n,this.#o,void 0,void 0,w,b,t],E=A$(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,E,v]);let[{alg:T,enc:R},,U]=E;if(t&&U&&!gn(U))throw new N(`"${T}" alg may only have a single recipient`);if(!r)r=R;else if(r!==R)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=hn(m[0].alg);let[s,a,c]=i[0],u=t?ha(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await k$(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[g,[w,v,b],x]=i[m],E=g[2],[,T,R]=await oy(b,v,x,w,u,g[7]),U={encrypted_key:it(T)};if(E||R){let j={...E,...R};R&&ay(g[1],j,g[3]),U.header=j}f.recipients.push(U)}return f}};var Gd=[["verify"],["sign"]];function T$(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Gd}}function Xc(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Gd,minRsaBits:2048}}function P$(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Gd}}function M4(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Gd}}function C$(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Gd}}var L4=qd({HS256:T$(256),HS384:T$(384),HS512:T$(512),RS256:Xc(256),RS384:Xc(384),RS512:Xc(512),PS256:Xc(256,32),PS384:Xc(384,48),PS512:Xc(512,64),ES256:P$("P-256",256),ES384:P$("P-384",384),ES512:P$("P-521",512),EdDSA:M4(),Ed25519:M4(),"ML-DSA-44":C$(44),"ML-DSA-65":C$(65),"ML-DSA-87":C$(87)});var Yc=class{#e;constructor(t){pn(t,"plaintext"),this.#e=[t]}setContentEncryptionKey(t){return Yn(this.#e[5],"setContentEncryptionKey"),this.#e[5]=t,this}setInitializationVector(t){return Yn(this.#e[6],"setInitializationVector"),this.#e[6]=t,this}setProtectedHeader(t){return Yn(this.#e[1],"setProtectedHeader"),this.#e[1]=t,this}setKeyManagementParameters(t){return Yn(this.#e[7],"setKeyManagementParameters"),this.#e[7]=t,this}async encrypt(t,r){return j4(await U4([...this.#e],t,r))}};var R$='"alg" (Algorithm)';function O$(e='JWK "alg" (Algorithm) Parameter'){throw new Pe(`Invalid or unsupported ${e} value`)}function Xd(e,t){return(typeof e=="string"?L4[e]??ri[e]:void 0)??O$(t)}async function Qc(e){if(g$(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:it(e)};if(!Bi(e))throw new TypeError(ti(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let t=await crypto.subtle.exportKey("jwk",e);delete t.ext,delete t.key_ops,delete t.use,t.kty!=="AKP"&&delete t.alg;for(let r of Object.keys(t))t[r]===void 0&&delete t[r];return t}var ni=(e,t)=>{if(typeof e!="string"||!e)throw new Wd(`${t} missing or invalid`)};async function N$(e,t){let r;if(st(e)){if(r=Zg(e),typeof r.kty!="string")throw new TypeError(ti(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(y$(e))r=Zg(await Qc(e));else throw new TypeError(ti(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":ni(r.alg,'"alg" (Algorithm) Parameter'),ni(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":ni(r.crv,'"crv" (Curve) Parameter'),ni(r.x,'"x" (X Coordinate) Parameter'),ni(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":ni(r.crv,'"crv" (Subtype of Key Pair) Parameter'),ni(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":ni(r.e,'"e" (Exponent) Parameter'),ni(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new Wd('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Pe('"kty" (Key Type) Parameter missing or unsupported')}let n=ei(JSON.stringify(o));return it(await Fg(t,n))}async function ya(e,t,r){if(!st(e))throw new TypeError("JWK must be an object");let o=b$(e),n=Gg(r?.extractable),{alg:i}=o;if(t??=i,o.kty!=="oct"&&!t)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return fa(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==i)throw new TypeError("JWK alg and alg option value mismatch");return Jc(Xd(t),o,n)}case"RSA":case"EC":case"OKP":return Jc(Xd(t),o,n);default:throw new Pe('Unsupported "kty" (Key Type) Parameter value')}}function D$(e){let t;if(typeof e=="string"){let o=e.split(".");(o.length===3||o.length===5)&&([t]=o)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof t!="string"||!t)throw new TypeError(r);return Bg(t,TypeError,r)}function rte(e){let t=e?.modulusLength??2048;if(typeof t!="number"||!Number.isInteger(t)||t<2048)throw new Pe("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function z$(e,t){let r=Gg(t?.extractable),o=Xd(e,R$);o.secret&&O$(R$);let n;if(o.resolve){let i=t?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Pe("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&t?.crv!==void 0&&t.crv!==o.crv)throw new Pe(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:rte(t)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var H4=h.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),K4=h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),F4=h.string().min(1).max(128),V4=h.string().min(1).max(16384),nte=h.discriminatedUnion("kind",[h.object({kind:h.literal("access_key"),accessKeyId:F4,secretAccessKey:V4}).strict(),h.object({kind:h.literal("session"),accessKeyId:F4,secretAccessKey:V4,sessionToken:h.string().min(1).max(16384),expiresAt:h.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),h.object({kind:h.literal("environment")}).strict()]),ote=h.object({arn:K4,externalId:h.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),wa=h.object({authentication:nte,region:H4,role:ote.optional()}).strict(),cy=h.object({accountId:h.string().regex(/^\d{12}$/),principalId:h.string().min(1).max(256),arn:h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),uy=wa.extend({sourceIdentity:cy.optional(),identity:cy.optional()}).strict();function eu(e){return e.includes(":assumed-role/")?e.slice(0,e.lastIndexOf("/")):e}function B4(e){return{...e,arn:eu(e.arn)}}function W4(e){return{authentication:e.authentication.kind,region:e.region,role:e.role??null,...e.sourceIdentity?{sourceIdentity:B4(e.sourceIdentity)}:{},...e.identity?{identity:B4(e.identity)}:{}}}var ly=h.object({authentication:h.enum(["access_key","session","environment"]),region:H4,sourceAccountId:h.string().regex(/^\d{12}$/).optional(),sourceArn:h.string().max(2e3).optional(),roleArn:K4.optional(),expiresAt:h.number().int().positive().optional()}).strict();function q4(e){return{authentication:e.authentication.kind,region:e.region,...e.sourceIdentity?{sourceAccountId:e.sourceIdentity.accountId,sourceArn:e.sourceIdentity.arn}:{},...e.role?{roleArn:e.role.arn}:{},...e.authentication.kind==="session"?{expiresAt:e.authentication.expiresAt}:{}}}typeof window<"u"&&h.config({jitless:!0});var $=h.uuid(),ce=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Re=h.iso.datetime(),ba=h.json(),It=h.record(h.string(),ba),Z4=h.enum(["ja","en"]),U$=h.enum(["read","create","update","delete","share","transfer","reveal","use","manage_credentials","export"]);var j$=h.enum(["variable","connection","service","method","app","object","ssh_key","ssh_host"]),yn=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),ite=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:$}).strict(),ef=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(e=>{try{return ite.safeParse(D$(e)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Qn=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:h.string().regex(/^[A-Za-z0-9_-]{1,64}$/),epk:yn.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),tu=h.object({id:$,name:ce,publicKey:yn}),ru=h.object({id:$,name:ce,owner:h.object({id:$,name:ce}).nullable(),createdAt:Re,permissions:h.array(U$),createKinds:h.array(j$),items:h.partialRecord(j$,h.array(U$)).optional(),publicKey:yn.nullable()}),G4=h.object({id:$,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:Re,lastUsedAt:Re.nullable(),expiresAt:Re.nullable(),canOpen:h.boolean()}),X4=h.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ste=h.object({subjectId:$,relation:X4,objectId:$}).strict(),Y4=h.enum(["principal",...j$.options]),Q4=ste.extend({objectType:Y4,subjectName:ce,objectName:ce,createdAt:Re}),pEe=h.object({error:h.object({code:h.string(),message:h.string(),details:ba.optional()})}),mEe=h.object({ok:h.literal(!0)}),ate=h.object({value:h.string().min(1).max(200),label:h.string().min(1).max(200),values:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).default({})}).strict(),fy=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),inputType:h.enum(["text","password","file"]).optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional(),choices:h.array(ate).min(1).max(100).optional(),defaultValue:h.string().max(1e3).optional(),when:h.object({field:h.string(),values:h.array(h.string()).min(1)}).strict().optional(),visibility:h.enum(["application","connection"]).optional()}).superRefine((e,t)=>{let r=e.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&t.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),M$=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),cte=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.union([h.string(),h.array(h.union([h.string().max(8192),h.object({pointer:h.string().max(1e3)}).strict()])).min(1).max(32)])),L$=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),required:h.array(h.string()).optional(),separator:h.string().default(" "),docs:h.url().optional()}),va=h.string().min(1).max(4096),dy=h.union([h.string(),h.array(h.string()).min(1)]),ur="urn:ietf:params:oauth:grant-type:device_code",ute=h.object({browserTokenExchange:h.enum(["available","unavailable","unknown"]).optional(),application:h.enum(["required","implicit"]).default("required"),grantType:h.enum(["authorization_code","client_credentials",ur]).optional(),issuer:h.url().optional(),registrationUrl:h.url().optional(),authorizeUrl:va.optional(),deviceAuthorizationUrl:va.optional(),tokenUrl:va,identity:h.object({url:va.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:dy.default("/id"),name:dy.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:L$.default({default:[],separator:" "}),fields:h.array(fy).default([]),outputs:M$.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}).refine(e=>e.grantType==="client_credentials"||e.grantType===ur||!!e.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}).refine(e=>e.grantType!==ur||!!e.deviceAuthorizationUrl,{path:["deviceAuthorizationUrl"],message:"A device flow requires a device authorization URL."}),lte=h.object({fields:h.array(fy).min(1),outputs:cte,resolver:h.literal("vultr-role").optional(),bindFields:h.boolean().optional(),constants:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).optional(),files:h.array(h.string().regex(/^[A-Z_][A-Z0-9_]*$/)).max(32).optional(),account:h.object({field:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),pointer:h.string().max(1e3)}).strict().optional(),identity:h.object({url:va,headers:h.record(h.string(),h.string()),id:dy,name:dy}).strict().optional(),console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}).superRefine((e,t)=>{e.files?.some(r=>!Object.hasOwn(e.outputs,r))&&t.addIssue({code:"custom",path:["files"],message:"Deliver only declared outputs as files."}),e.account&&!e.fields.some(r=>r.name===e.account.field)&&t.addIssue({code:"custom",path:["account"],message:"Read the account from a declared field."})}),F$=h.enum(["oauth","token","aws","ovh","approval"]),dte=h.object({hint:h.string().optional()}).strict(),fte=h.object({authorization:h.enum(["api_key","consumer_key"]),apiBaseUrl:va,fields:h.array(fy).min(1),scopes:L$.default({default:[],separator:`
|
|
122
|
-
`}),outputs:M$,hint:h.string().optional()}).strict(),tf={name:ce,docs:h.url().optional(),console:va.optional(),preparation:h.object({scopeSelection:h.enum(["optional","required","hidden"]).default("optional"),instructions:h.array(h.union([h.string().max(2e3),h.object({ja:h.string().max(2e3),en:h.string().max(2e3)}).strict()])).max(10).default([]),docs:h.boolean().default(!1)}).strict().optional()},py=h.object({...tf,kind:h.literal("oauth"),config:ute}).strict(),my=h.object({...tf,kind:h.literal("token"),config:lte}).strict(),hy=h.object({...tf,kind:h.literal("aws"),config:dte}).strict(),gy=h.object({...tf,kind:h.literal("ovh"),config:fte}).strict(),yy=h.object({...tf,kind:h.literal("approval"),config:h.object({adapter:h.literal("runpod-flash"),fields:h.array(fy).default([]),scopes:L$.default({default:[],separator:" "}),outputs:M$,hint:h.string().optional()}).strict()}).strict(),nu=h.discriminatedUnion("kind",[py,my,hy,gy,yy]),Yd={id:h.string().min(1),builtin:h.boolean(),availability:h.enum(["ready","app-required","unavailable"]),defaultName:ce,registration:h.object({kind:h.enum(["input","authorization"]),device:h.enum(["browser","cli"]),browserExchange:h.enum(["available","unavailable","unknown"]),tokenAlternatives:h.array(h.string())}).strict()},oi=h.discriminatedUnion("kind",[py.extend(Yd),my.extend(Yd),hy.extend(Yd),gy.extend(Yd),yy.extend(Yd)]),Qd=h.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),V$=h.object({name:ce,logo:h.string().regex(/^[a-z0-9-]+$/).optional(),api:h.url().optional(),docs:h.url().optional(),console:h.url().optional(),targets:h.array(h.object({id:Qd,name:ce,api:h.url().optional(),methods:h.array(Qd).min(1)}).strict()).max(32).optional()}).strict(),pte=V$.extend({methods:h.record(Qd,h.string().min(1))}).strict(),ej=V$.extend({methods:h.record(Qd,h.union([h.string().min(1),nu]))}).strict(),tj=V$.extend({id:h.string(),builtin:h.boolean(),methods:h.record(Qd,oi)}),mte=h.object({id:$,output:h.string().min(1).max(100).optional()}).strict(),rj=e=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(e),nj=h.object({name:h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:mte,format:h.enum(["text","file","json"]).optional(),pointer:h.string().optional()}).strict(),Hi={id:$,ownerId:$,name:ce,createdAt:Re,updatedAt:Re,version:h.number().int().positive(),permissions:h.array(U$)},hte=h.object({...Hi,kind:h.literal("variable"),data:h.object({bytes:h.number().int().nonnegative()})}),gte=h.object({...Hi,kind:h.literal("connection"),data:h.object({methodId:h.string(),fields:h.record(h.string(),h.string()).default({}),settings:h.array(h.object({name:h.string(),label:h.string(),value:h.string()})).default([]),methodName:h.string(),methodKind:F$,services:h.array(h.object({id:h.string(),name:ce})).default([]),account:h.string(),accountId:h.string().nullable().default(null),accountVerified:h.boolean().default(!1),scopes:h.array(h.string()),scopesStatus:h.enum(["unknown","requested","reported"]).default("unknown"),outputs:h.array(h.string()),state:h.enum(["ready","reconnect","disconnecting","uncertain"]),appId:$.nullable(),generation:$.optional(),aws:ly.optional()})}),yte=h.object({...Hi,kind:h.literal("service"),data:pte}),wte=h.object({...Hi,kind:h.literal("method"),data:nu}),vte=h.object({...Hi,kind:h.literal("app"),data:h.object({methodId:h.string(),clientId:h.string(),fields:h.record(h.string(),h.string()).default({}),generation:$.optional()})}),bte=h.object({...Hi,kind:h.literal("object"),data:h.object({size:h.number().int().nonnegative(),contentType:h.string()})}),Ste=h.object({publicKey:i4,algorithm:h.string(),fingerprint:c4,purpose:h.string().max(500),privateKeyId:$.nullable()}),_te=h.object({...Hi,kind:h.literal("ssh_key"),data:Ste}),xte=h.object({address:a4,port:h.number().int().min(1).max(65535)}),Ete=h.object({...Hi,kind:h.literal("ssh_host"),data:xte}),ze=h.discriminatedUnion("kind",[hte,gte,yte,wte,vte,bte,_te,Ete]),hEe=h.discriminatedUnion("kind",[h.object({kind:h.literal("service"),name:ce,definition:ej}).strict(),h.object({kind:h.literal("method"),name:ce,definition:nu}).strict()]),gEe=h.object({version:h.number().int().positive(),name:ce.optional(),definition:h.union([ej,nu]).optional()}).strict(),eo=h.object({name:h.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:It}).strict(),B$=eo.extend({inputs:h.array(h.object({pointer:h.string(),label:h.string().min(1).max(100),secret:h.boolean().default(!1),multiline:h.boolean().default(!1),site:h.url().optional()}).strict()).max(16).default([])}),wy=h.object({ja:h.string(),en:h.string()}).strict(),J4=h.object({id:$,name:ce}),oj=h.object({kind:h.literal("transfer"),item:J4,to:J4}),yEe=h.object({id:$,name:ce,publicKey:yn,state:h.enum(["pending","approving","approved"]),principalId:$.nullable(),createdAt:Re,expiresAt:Re}),wEe=h.object({id:h.string(),actorId:$.nullable(),action:h.string(),targetId:$.nullable(),createdAt:Re,details:It}),vEe=h.object({returnUrl:h.url().optional(),refreshUrl:h.url().optional()}).strict(),pt=e=>h.object({items:h.array(e),next:h.string().nullable().default(null)}),bEe=h.object({id:$}),Ite=h.object({limit:h.coerce.number().int().min(1).max(200).default(100),after:h.string().optional()}),SEe=Ite.extend({object:$.optional(),subject:$.optional(),relation:X4.optional(),objectType:Y4.optional()}).refine(e=>!!e.object!=!!e.subject,"Choose the object or the subject of the lines.");var Ate=h.object({requestedAt:Re,readyAt:Re}).strict(),kte=h.object({email:h.boolean(),storage:h.boolean()}),vy=h.object({principal:ru.nullable(),credentialId:$.nullable(),wrappedKey:ef.nullable(),requestId:$.nullable(),keyReset:Ate.nullable(),server:h.object({name:ce}),features:kte,principals:h.array(ru)}),IEe=h.object({email:h.email().max(254),returnTo:h.string().max(2048).optional(),locale:Z4.default("ja"),principalId:$.optional()}).strict(),AEe=h.object({intent:h.enum(["register","authenticate"]),name:ce.optional(),principalId:$.optional(),credentialId:$.optional(),returnTo:h.string().max(2048).optional()}).strict(),kEe=h.object({challengeId:$,credential:h.json(),publicKey:yn.optional(),wrappedKey:ef.optional()}).strict(),$Ee=h.object({publicKey:yn,wrappedKey:ef}).strict();var $te=new TextEncoder,Tte=new TextDecoder,rf="ECDH-ES+A256KW",H$="A256GCM",at=e=>$te.encode(e),lr=e=>Tte.decode(e);function nf(e){let t="";for(let r=0;r<e.length;r+=8192)t+=String.fromCharCode(...e.subarray(r,r+8192));return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ij(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}async function K$(){let e=await z$(rf,{crv:"P-256",extractable:!0});return{publicKey:yn.parse(await Qc(e.publicKey)),privateKey:await Qc(e.privateKey)}}var Pte=yn.extend({d:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}),of=h.object({encryption:Pte});async function sj(){return of.parse({encryption:(await K$()).privateKey})}function ou(e){return yn.parse({kty:e.kty,crv:e.crv,x:e.x,y:e.y})}function Sr(e){return N$(ou(e),"sha256")}async function by(e,t,r){if(!t.length||new Set(t.map(n=>n.id)).size!==t.length)throw new Error("Recipients must be distinct and nonempty.");let o=new Zd(e).setProtectedHeader({enc:H$});r!==void 0&&o.setAdditionalAuthenticatedData(at(r));for(let n of t)o.addRecipient(await ya(n.publicKey,rf)).setUnprotectedHeader({alg:rf,kid:n.id});return Qn.parse(await o.encrypt())}async function Ki(e,t,r,o){if(o!==void 0&&e.aad!==nf(at(o)))throw new Error("The encrypted content belongs to a different item.");let n=e.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=t instanceof CryptoKey?t:await ya(t,rf);return(await I$({...e,recipients:[n]},i,{keyManagementAlgorithms:[rf],contentEncryptionAlgorithms:[H$]})).plaintext}async function Cte(e){let t=await crypto.subtle.importKey("raw",new Uint8Array(e),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:at("Foundation"),info:at("passkey encryption key")},t,256))}async function aj(e,t,r){let o=await Jd(e,await Cte(t),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[H$]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(lr(o.plaintext))}var cj=h.string().regex(/^[A-Za-z0-9_-]{43}$/);function Be(e){if(e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&!/[\uD800-\uDFFF]/u.test(e))return JSON.stringify(e);if(Array.isArray(e))return"["+Array.from(e,Be).join(",")+"]";if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype)return"{"+Object.keys(e).sort().map(t=>{if(/[\uD800-\uDFFF]/u.test(t))throw new Error("Use Unicode property names.");return JSON.stringify(t)+":"+Be(e[t])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Sy(e){return nf(new Uint8Array(await crypto.subtle.digest("SHA-256",at(Be(e)))))}var Sa=class extends Error{constructor(r,o,n,i,s){super(n);this.code=r;this.status=o;this.details=i;this.origin=s}code;status;details;origin},iu=class extends Error{constructor(r,o,n){super("Foundation answered "+o+" in a form this CLI does not read.");this.origin=r;this.path=o;this.error=n}origin;path;error},sf=class{constructor(t){this.identity=t}identity;async response(t,r={}){if(!t.startsWith("/api/")||t.includes("\\")||/[\u0000-\u001f]/.test(t))throw new Error("Use a path beginning with /api/.");let o=new URL(t,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=h.object({error:h.object({code:h.string(),message:h.string(),details:h.unknown().optional()})}).parse(await n.json())}catch{throw new Sa("http_error",n.status,"Foundation returned HTTP "+n.status+".",void 0,this.identity.origin)}throw new Sa(i.error.code,n.status,i.error.message,i.error.details,this.identity.origin)}return n}async json(t,r={},o){let n=await this.response(t,r),i=n.status===204?null:await n.json();if(!o)return i;let s=o.safeParse(i);if(!s.success)throw new iu(this.identity.origin,t,s.error);return s.data}async session(){return this.json("/api/session",{},vy)}};import{chmod as Rte,lstat as Ote,mkdir as Nte,open as W$,readFile as lj,rename as Dte,rm as zte}from"node:fs/promises";import{dirname as Ute,join as q$,resolve as jte}from"node:path";import{homedir as Mte}from"node:os";import{randomUUID as Lte}from"node:crypto";var J$=h.object({origin:h.url(),principalId:h.uuid(),token:h.string().min(20),keys:of.nullable()}),dj=h.object({current:h.uuid(),identities:h.array(J$).min(1)}).strict().refine(e=>e.identities.some(t=>t.principalId===e.current),"The current identity is missing.");function ii(){return q$(process.env.XDG_CONFIG_HOME||q$(Mte(),".config"),"foundation","identity.json")}function su(e=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let t;try{t=new URL(e)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return t.origin}async function Z$(){try{let e=ii(),t=await Ote(e);if(!t.isFile()||t.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&t.mode&63&&await Rte(e,384),dj.parse(JSON.parse(await lj(e,"utf8")))}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function fj(){let e=await Z$();return(e?.identities??[]).map(t=>({...t,current:t.principalId===e.current}))}async function pj(e){let t=await Z$();if(!t?.identities.some(r=>r.principalId===e))throw new Error("No saved identity has principal "+e+". Run foundation identity list.");await si(ii(),JSON.stringify({...t,current:e},null,2)+`
|
|
121
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&e.reused==="ref"&&i(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function hz(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;hz(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var gz=new Set(["type","properties","required","additionalProperties"]),pz=["oneOf","anyOf"];function mz(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function mA(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!gz.has(s))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of t){let l=u.properties?.[s]??mz(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:mA(a)??{allOf:a};xt(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of t){let a=mz(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function iee(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of gz)if(n in e)return;let r=t.filter(n=>pz.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=mA(t);else{let n=r[0],i=pz.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=t.filter(c=>c!==n),a=n[i].map(c=>mA([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete e.allOf,Td(e,o))}function Ui(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=e.seen.get(d),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Td(u,m),Td(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&f.def)for(let w in u)w==="$ref"||w==="allOf"||w in f.def&&JSON.stringify(u[w])===JSON.stringify(f.def[w])&&delete u[w]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=e.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())o(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())hz(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])iee(u)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Td(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,xt(s,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Uc(t,"input",e.processors),output:Uc(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Gt(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Gt(o.element,r);if(o.type==="set")return Gt(o.valueType,r);if(o.type==="lazy")return Gt(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Gt(o.innerType,r);if(o.type==="intersection")return Gt(o.left,r)||Gt(o.right,r);if(o.type==="record"||o.type==="map")return Gt(o.keyType,r)||Gt(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Gt(o.in,r)||Gt(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Gt(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Gt(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Gt(n,r))return!0;return!!(o.rest&&Gt(o.rest,r))}return!1}var hA=(e,t={})=>r=>{let o=Di({...r,processors:t});return xe(e,o),zi(o,e),Ui(o,e)},Uc=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Di({...n??{},target:i,io:t,processors:r});return xe(e,s),zi(s,e),Ui(s,e)};var jc=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Mc=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},yz=(e,t)=>{jc(e,"minimum",t),Mc(e,"maximum",t)},Sz=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},_z=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},xz=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Ez=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},wz=(e,t)=>jc(e,"minimum",t.minimum),vz=(e,t)=>Mc(e,"maximum",t.maximum),bz=e=>(t,r)=>{Ez(t,r.format);let[o,n]=e[r.format];jc(t,"minimum",o),Mc(t,"maximum",n)},see={greater_than:(e,t)=>jc(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Mc(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Sz(e,t.value),number_format:bz(Gl),bigint_format:bz(Xl),min_length:wz,max_length:vz,length_equals:(e,t)=>yz(e,t.length),min_size:wz,max_size:vz,size_equals:(e,t)=>yz(e,t.size),string_format:(e,t)=>{Ez(e,t.format),t.pattern&&_z(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>xz(e,t.mime)};function ot(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)see[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&jc(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&jc(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Mc(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Mc(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&Sz(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&xz(t,n.mime);for(let i of n.patterns??[])_z(t,i);return t}var aee={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},cee=new Map([[ch,Sx],[md,_x]]),Iz=e=>cee.get(e)??e,wA=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=ot(e);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=aee[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(Iz);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},vA=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=ot(e);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let v of a)Number.isFinite(v)&&v!==0?m.add(Math.abs(v)):nt(e,t,n,o,`A multipleOf divisor of ${v} cannot be represented in JSON Schema`);let[g,...w]=m;g!==void 0&&(n.multipleOf=g),w.length&&(n.allOf=[...n.allOf??[],...w.map(v=>({multipleOf:v}))])}},bA=(e,t,r,o)=>{r.type="boolean"},SA=(e,t,r,o)=>{nt(e,t,r,o,"BigInt cannot be represented in JSON Schema")},_A=(e,t,r,o)=>{nt(e,t,r,o,"Symbols cannot be represented in JSON Schema")},xA=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},EA=(e,t,r,o)=>{nt(e,t,r,o,"Undefined cannot be represented in JSON Schema")},IA=(e,t,r,o)=>{nt(e,t,r,o,"Void cannot be represented in JSON Schema")},AA=(e,t,r,o)=>{r.not={}},kA=(e,t,r,o)=>{},$A=(e,t,r,o)=>{},TA=(e,t,r,o)=>{nt(e,t,r,o,"Date cannot be represented in JSON Schema")},PA=(e,t,r,o)=>{let n=e._zod.def,i=uc(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},CA=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(nt(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(nt(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},RA=(e,t,r,o)=>{nt(e,t,r,o,"NaN cannot be represented in JSON Schema")},OA=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},NA=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=ot(e);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},DA=(e,t,r,o)=>{r.type="boolean"},zA=(e,t,r,o)=>{nt(e,t,r,o,"Custom types cannot be represented in JSON Schema")},UA=(e,t,r,o)=>{nt(e,t,r,o,"Function types cannot be represented in JSON Schema")},jA=(e,t,r,o)=>{nt(e,t,r,o,"Transforms cannot be represented in JSON Schema")},MA=(e,t,r,o)=>{nt(e,t,r,o,"Map cannot be represented in JSON Schema")},LA=(e,t,r,o)=>{nt(e,t,r,o,"Set cannot be represented in JSON Schema")},FA=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=ot(e);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=xe(i.element,t,{...o,path:[...o.path,"items"]})};function Pd(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Pd(t.out):t.type==="catch"?Pd(t.innerType):e._zod.optin}var VA=(e,t,r,o)=>{let n=r,i=e._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&nt(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)xt(n.properties,u,xe(s[u],t,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(t.io==="input"?Pd(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=xe(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},ig=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>xe(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},BA=(e,t,r,o)=>{let n=e._zod.def,i=xe(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=xe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,t.intersections.push(c)},HA=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((g,w)=>xe(g,t,{...o,path:[...o.path,s,w]})),u=i.rest?xe(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let g=i.items[l-1];if(!(t.io==="input"?Pd(g)!==void 0:g._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):t.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=ot(e);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function gA(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let g=gA(e,m,r);return g===m?t:g}for(let m of["anyOf","oneOf"]){let g=t[m];if(!Array.isArray(g))continue;let w=g.map(v=>gA(e,v,r));w.some((v,b)=>v!==g[b])&&(t={...t,[m]:w})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=t;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?Xo:ad).source)),f}var yA=new WeakMap;function uee(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of yA.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=gA(t,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var KA=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,a=ot(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=xe(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)xt(n.patternProperties,Iz(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=xe(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let l=yA.get(t);l||(l=[],yA.set(t,l),t.deferred.push(()=>uee(t))),l.push(e)}n.additionalProperties=xe(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=t.io==="input"&&Pd(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},WA=(e,t,r,o)=>{let n=e._zod.def,i=xe(n.innerType,t,o),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},qA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},JA=Symbol();function Az(e,t,r,o,n){let i=!1,s=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(nt(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),JA):JSON.parse(s)}var ZA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s=Az(n.defaultValue,e,t,r,o);s!==JA&&(r.default=s)},GA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let s=Az(n.defaultValue,e,t,r,o);s!==JA&&(r._prefault=s)},XA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{nt(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},YA=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;xe(s,t,o);let a=t.seen.get(e);a.ref=s},QA=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},ek=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},sg=(e,t,r,o)=>{let n=e._zod.def;xe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},tk=(e,t,r,o)=>{let n=e._zod.innerType;xe(n,t,o);let i=t.seen.get(e);i.ref=n},og={string:wA,number:vA,boolean:bA,bigint:SA,symbol:_A,null:xA,undefined:EA,void:IA,never:AA,any:kA,unknown:$A,date:TA,enum:PA,literal:CA,nan:RA,template_literal:OA,file:NA,success:DA,custom:zA,function:UA,transform:jA,map:MA,set:LA,array:FA,object:VA,union:ig,intersection:BA,tuple:HA,record:KA,nullable:WA,nonoptional:qA,default:ZA,prefault:GA,catch:XA,pipe:YA,readonly:QA,promise:ek,optional:sg,lazy:tk};function ag(e,t){if("_idmap"in e){let o=e,n=Di({...t,processors:og}),i={};for(let c of o._idmap.entries()){let[u,l]=c;xe(l,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;zi(n,l),xt(s,u,Ui(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Di({...t,processors:og});return xe(e,r),zi(r,e),Ui(r,e)}var cg=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Di({processors:og,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return xe(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,zi(this.ctx,t);let o=Ui(this.ctx,t),{"~standard":n,...i}=o;return i}};var kz={};var qc={};Ce(qc,{ZodAny:()=>xk,ZodArray:()=>kk,ZodBase64:()=>kg,ZodBase64URL:()=>$g,ZodBigInt:()=>Kc,ZodBigIntFormat:()=>Cg,ZodBoolean:()=>Hc,ZodCIDRv4:()=>Ig,ZodCIDRv6:()=>Ag,ZodCUID:()=>wg,ZodCUID2:()=>vg,ZodCatch:()=>Jk,ZodCodec:()=>Ld,ZodCreditCard:()=>hk,ZodCustom:()=>Fd,ZodCustomStringFormat:()=>ua,ZodDate:()=>Nd,ZodDefault:()=>Vk,ZodDiscriminatedUnion:()=>Tk,ZodE164:()=>Tg,ZodEmail:()=>mg,ZodEmoji:()=>gg,ZodEnum:()=>Fc,ZodExactOptional:()=>Dg,ZodFile:()=>jk,ZodFunction:()=>o$,ZodGUID:()=>hg,ZodIBAN:()=>gk,ZodIPv4:()=>xg,ZodIPv6:()=>Eg,ZodISODate:()=>Mi,ZodISODateTime:()=>ji,ZodISODuration:()=>Fi,ZodISOTime:()=>Li,ZodInstanceOf:()=>a$,ZodIntersection:()=>Pk,ZodJWT:()=>Pg,ZodKSUID:()=>_g,ZodLazy:()=>t$,ZodLiteral:()=>Uk,ZodMAC:()=>mk,ZodMap:()=>Dk,ZodNaN:()=>Gk,ZodNanoID:()=>yg,ZodNever:()=>Ik,ZodNonOptional:()=>zg,ZodNull:()=>Sk,ZodNullable:()=>Fk,ZodNumber:()=>Bc,ZodNumberFormat:()=>la,ZodObject:()=>zd,ZodOptional:()=>jd,ZodPipe:()=>Md,ZodPrefault:()=>Hk,ZodPreprocess:()=>Xk,ZodPromise:()=>n$,ZodReadonly:()=>Yk,ZodRecord:()=>Lc,ZodSet:()=>zk,ZodString:()=>Vc,ZodStringFormat:()=>Ee,ZodSuccess:()=>qk,ZodSymbol:()=>vk,ZodTemplateLiteral:()=>e$,ZodTransform:()=>Mk,ZodTuple:()=>Rk,ZodType:()=>te,ZodULID:()=>bg,ZodURL:()=>Od,ZodUUID:()=>Xn,ZodUndefined:()=>bk,ZodUnion:()=>Ud,ZodUnknown:()=>Ek,ZodVoid:()=>Ak,ZodXID:()=>Sg,ZodXor:()=>$k,_ZodString:()=>pg,_default:()=>Bk,_function:()=>MU,any:()=>gU,array:()=>Dd,base64:()=>Gz,base64url:()=>Xz,bigint:()=>dU,boolean:()=>wk,catch:()=>Zk,check:()=>LU,cidrv4:()=>Jz,cidrv6:()=>Zz,codec:()=>DU,creditCard:()=>Qz,cuid:()=>Lz,cuid2:()=>Fz,currencyCode:()=>iU,custom:()=>FU,date:()=>wU,describe:()=>VU,discriminatedUnion:()=>EU,e164:()=>Yz,email:()=>Pz,emoji:()=>jz,enum:()=>Og,exactOptional:()=>Lk,file:()=>CU,float32:()=>aU,float64:()=>cU,function:()=>MU,guid:()=>Cz,hash:()=>sU,hex:()=>oU,hostname:()=>nU,httpUrl:()=>Uz,iban:()=>eU,instanceof:()=>HU,int:()=>dg,int32:()=>uU,int64:()=>fU,intersection:()=>Ck,invertCodec:()=>zU,ipv4:()=>Kz,ipv6:()=>qz,json:()=>WU,jwt:()=>tU,keyof:()=>vU,ksuid:()=>Hz,lazy:()=>r$,literal:()=>PU,looseObject:()=>_U,looseRecord:()=>AU,mac:()=>Wz,map:()=>kU,meta:()=>BU,nan:()=>NU,nanoid:()=>Mz,nativeEnum:()=>TU,never:()=>Rg,nonoptional:()=>Wk,null:()=>_k,nullable:()=>Rd,nullish:()=>RU,number:()=>yk,object:()=>bU,optional:()=>aa,partialRecord:()=>IU,pipe:()=>fg,prefault:()=>Kk,preprocess:()=>qU,promise:()=>jU,readonly:()=>Qk,record:()=>Nk,refine:()=>i$,set:()=>$U,strictObject:()=>SU,string:()=>Cd,stringFormat:()=>rU,stringbool:()=>KU,success:()=>OU,superRefine:()=>s$,symbol:()=>mU,templateLiteral:()=>UU,transform:()=>Ng,tuple:()=>Ok,uint32:()=>lU,uint64:()=>pU,ulid:()=>Vz,undefined:()=>hU,union:()=>Wc,unknown:()=>sa,url:()=>zz,uuid:()=>Rz,uuidv4:()=>Oz,uuidv6:()=>Nz,uuidv7:()=>Dz,void:()=>yU,xid:()=>Bz,xor:()=>xU});var ug={};Ce(ug,{endsWith:()=>Tc,gt:()=>Zn,gte:()=>br,includes:()=>kc,length:()=>oa,lowercase:()=>Ic,lt:()=>Jn,lte:()=>vr,maxLength:()=>na,maxSize:()=>Ni,mime:()=>Cc,minLength:()=>Yo,minSize:()=>Gn,multipleOf:()=>Oi,negative:()=>eg,nonnegative:()=>rg,nonpositive:()=>tg,normalize:()=>Rc,overwrite:()=>dn,positive:()=>Qh,properties:()=>Pc,property:()=>ng,regex:()=>Ec,size:()=>ra,slugify:()=>zc,startsWith:()=>$c,toLowerCase:()=>Nc,toUpperCase:()=>Dc,trim:()=>Oc,uppercase:()=>Ac});var $z=new WeakSet([Object.prototype,Error.prototype]);function lg(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Tz=(e,t)=>{tx.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);$z.has(r)||($z.add(r),lg(r,"format",o=>n=>nd(o,n)),lg(r,"flatten",o=>n=>rd(o,n)),lg(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,lc,2)}),lg(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,lc,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},dee=S("ZodError",Tz),cr=S("ZodError",Tz,void 0,{Parent:Error});var rk=hc(cr),nk=gc(cr),ok=yc(cr),ik=wc(cr),sk=Mm(cr),ak=Lm(cr),ck=Fm(cr),uk=Vm(cr),lk=Bm(cr),dk=Hm(cr),fk=Km(cr),pk=Wm(cr);function pee(){ft.localeError||Ke(Eh())}function ca(){ft.memoizer||Ke({memoizer:Sd()})}var te=S("ZodType",(e,t)=>(pee(),X.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(I.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Se(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(i$(e,t))},superRefine(e,t){return this.check(s$(e,t))},overwrite(e){return this.check(dn(e))},optional(){return aa(this)},exactOptional(){return Lk(this)},nullable(){return Rd(this)},nullish(){return aa(Rd(this))},nonoptional(e){return Wk(this,e)},array(){return Dd(this)},or(e){return Wc([this,e])},and(e){return Ck(this,e)},transform(e){return fg(this,Ng(e))},default(e){return Bk(this,e)},prefault(e){return Kk(this,e)},catch(e){return Zk(this,e)},pipe(e){return fg(this,e)},readonly(){return Qk(this)},describe(e){let t=this.clone();return Et.add(t,{description:e}),t},meta(...e){if(e.length===0)return Et.get(this);let t=this.clone();return Et.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return I.hide(this,"~standard",{...nh(this),jsonSchema:{input:Uc(this,"input"),output:Uc(this,"output")}})},set"~standard"(e){I.own(this,"~standard",e)},parse:function e(t,r){return rk(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await nk(this,t,r,{callee:e})},safeParse(e,t){return ok(this,e,t)},async safeParseAsync(e,t){return ik(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){I.own(this,"spa",e)},validate(e,t){return od(this,e,t)},validateAsync(e,t){return id(this,e,t)},encode:function e(t,r){return sk(this,t,r,{callee:e})},decode:function e(t,r){return ak(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await ck(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await uk(this,t,r,{callee:e})},safeEncode(e,t){return lk(this,e,t)},safeDecode(e,t){return dk(this,e,t)},async safeEncodeAsync(e,t){return fk(this,e,t)},async safeDecodeAsync(e,t){return pk(this,e,t)},toJSONSchema(e){return hA(this,{})(e)},get description(){return Et.get(this)?.description},get _def(){return this._zod.def}}),pg=S("_ZodString",(e,t)=>{Ys.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wA(e,r,o,n)},I.derived({format:e=>ot(e).format??null,minLength:e=>ot(e).minimum??null,maxLength:e=>ot(e).maximum??null},{regex(...e){return this.check(Ec(...e))},includes(...e){return this.check(kc(...e))},startsWith(...e){return this.check($c(...e))},endsWith(...e){return this.check(Tc(...e))},min(...e){return this.check(Yo(...e))},max(...e){return this.check(na(...e))},length(...e){return this.check(oa(...e))},nonempty(...e){return this.check(Yo(1,...e))},lowercase(e){return this.check(Ic(e))},uppercase(e){return this.check(Ac(e))},trim(){return this.check(Oc())},normalize(...e){return this.check(Rc(...e))},toLowerCase(){return this.check(Nc())},toUpperCase(){return this.check(Dc())},slugify(){return this.check(zc())}})),Vc=S("ZodString",(e,t)=>{Ys.init(e,t),pg.init(e,t)},{email(e){return this.check(Rh(mg,e))},url(e){return this.check(Ed(Od,e))},jwt(e){return this.check(Yh(Pg,e))},emoji(e){return this.check(jh(gg,e))},guid(e){return this.check(Oh(hg,e))},uuid(e){return this.check(Nh(Xn,e))},uuidv4(e){return this.check(Dh(Xn,e))},uuidv6(e){return this.check(zh(Xn,e))},uuidv7(e){return this.check(Uh(Xn,e))},nanoid(e){return this.check(Mh(yg,e))},cuid(e){return this.check(Lh(wg,e))},cuid2(e){return this.check(Fh(vg,e))},ulid(e){return this.check(Vh(bg,e))},base64(e){return this.check(Zh(kg,e))},base64url(e){return this.check(Gh($g,e))},xid(e){return this.check(Bh(Sg,e))},ksuid(e){return this.check(Hh(_g,e))},ipv4(e){return this.check(Kh(xg,e))},ipv6(e){return this.check(Wh(Eg,e))},cidrv4(e){return this.check(qh(Ig,e))},cidrv6(e){return this.check(Jh(Ag,e))},e164(e){return this.check(Xh(Tg,e))},datetime(e){return this.check(Id(ji,e))},date(e){return this.check(Ad(Mi,e))},time(e){return this.check(kd(Li,e))},duration(e){return this.check($d(Fi,e))}});function Cd(e){return CI(Vc,e)}var Ee=S("ZodStringFormat",(e,t)=>{_e.init(e,t),pg.init(e,t)}),ji=S("ZodISODateTime",(e,t)=>{SE.init(e,t),Ee.init(e,t)}),Mi=S("ZodISODate",(e,t)=>{_E.init(e,t),Ee.init(e,t)}),Li=S("ZodISOTime",(e,t)=>{xE.init(e,t),Ee.init(e,t)}),Fi=S("ZodISODuration",(e,t)=>{EE.init(e,t),Ee.init(e,t)}),mg=S("ZodEmail",(e,t)=>{lE.init(e,t),Ee.init(e,t)});function Pz(e){return Rh(mg,e)}var hg=S("ZodGUID",(e,t)=>{cE.init(e,t),Ee.init(e,t)});function Cz(e){return Oh(hg,e)}var Xn=S("ZodUUID",(e,t)=>{uE.init(e,t),Ee.init(e,t)});function Rz(e){return Nh(Xn,e)}function Oz(e){return Dh(Xn,e)}function Nz(e){return zh(Xn,e)}function Dz(e){return Uh(Xn,e)}var Od=S("ZodURL",(e,t)=>{pE.init(e,t),Ee.init(e,t)});function zz(e){return Ed(Od,e)}function Uz(e){return Ed(Od,{protocol:sd,hostname:Ex,...I.normalizeParams(e)})}var gg=S("ZodEmoji",(e,t)=>{mE.init(e,t),Ee.init(e,t)});function jz(e){return jh(gg,e)}var yg=S("ZodNanoID",(e,t)=>{hE.init(e,t),Ee.init(e,t)});function Mz(e){return Mh(yg,e)}var wg=S("ZodCUID",(e,t)=>{gE.init(e,t),Ee.init(e,t)});function Lz(e){return Lh(wg,e)}var vg=S("ZodCUID2",(e,t)=>{yE.init(e,t),Ee.init(e,t)});function Fz(e){return Fh(vg,e)}var bg=S("ZodULID",(e,t)=>{wE.init(e,t),Ee.init(e,t)});function Vz(e){return Vh(bg,e)}var Sg=S("ZodXID",(e,t)=>{vE.init(e,t),Ee.init(e,t)});function Bz(e){return Bh(Sg,e)}var _g=S("ZodKSUID",(e,t)=>{bE.init(e,t),Ee.init(e,t)});function Hz(e){return Hh(_g,e)}var xg=S("ZodIPv4",(e,t)=>{IE.init(e,t),Ee.init(e,t)});function Kz(e){return Kh(xg,e)}var mk=S("ZodMAC",(e,t)=>{kE.init(e,t),Ee.init(e,t)});function Wz(e){return OI(mk,e)}var Eg=S("ZodIPv6",(e,t)=>{AE.init(e,t),Ee.init(e,t)});function qz(e){return Wh(Eg,e)}var Ig=S("ZodCIDRv4",(e,t)=>{$E.init(e,t),Ee.init(e,t)});function Jz(e){return qh(Ig,e)}var Ag=S("ZodCIDRv6",(e,t)=>{TE.init(e,t),Ee.init(e,t)});function Zz(e){return Jh(Ag,e)}var kg=S("ZodBase64",(e,t)=>{PE.init(e,t),Ee.init(e,t)});function Gz(e){return Zh(kg,e)}var $g=S("ZodBase64URL",(e,t)=>{CE.init(e,t),Ee.init(e,t)});function Xz(e){return Gh($g,e)}var Tg=S("ZodE164",(e,t)=>{RE.init(e,t),Ee.init(e,t)});function Yz(e){return Xh(Tg,e)}var hk=S("ZodCreditCard",(e,t)=>{OE.init(e,t),Ee.init(e,t)});function Qz(e){return NI(hk,e)}var gk=S("ZodIBAN",(e,t)=>{NE.init(e,t),Ee.init(e,t)});function eU(e){return DI(gk,e)}var Pg=S("ZodJWT",(e,t)=>{DE.init(e,t),Ee.init(e,t)});function tU(e){return Yh(Pg,e)}var ua=S("ZodCustomStringFormat",(e,t)=>{zE.init(e,t),Ee.init(e,t)});function rU(e,t,r={}){return ia(ua,e,t,r)}function nU(e){return ia(ua,"hostname",xx,e)}function oU(e){return ia(ua,"hex",jx,e)}function iU(e){return ia(ua,"currency_code",Ax,e)}function sU(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ur[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return ia(ua,o,n,t)}var Bc=S("ZodNumber",(e,t)=>{ph.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vA(e,r,o,n),e.isFinite=!0},I.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ot(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ot(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ot(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ot(e).format??null},{gt(e,t){return this.check(Zn(e,t))},gte(e,t){return this.check(br(e,t))},min(e,t){return this.check(br(e,t))},lt(e,t){return this.check(Jn(e,t))},lte(e,t){return this.check(vr(e,t))},max(e,t){return this.check(vr(e,t))},int(e){return this.check(dg(e))},safe(e){return this.check(dg(e))},positive(e){return this.check(Zn(0,e))},nonnegative(e){return this.check(br(0,e))},negative(e){return this.check(Jn(0,e))},nonpositive(e){return this.check(vr(0,e))},multipleOf(e,t){return this.check(Oi(e,t))},step(e,t){return this.check(Oi(e,t))},finite(){return this}}));function yk(e){return UI(Bc,e)}var la=S("ZodNumberFormat",(e,t)=>{UE.init(e,t),Bc.init(e,t)});function dg(e){return MI(la,e)}function aU(e){return LI(la,e)}function cU(e){return FI(la,e)}function uU(e){return VI(la,e)}function lU(e){return BI(la,e)}var Hc=S("ZodBoolean",(e,t)=>{hd.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bA(e,r,o,n)});function wk(e){return HI(Hc,e)}var Kc=S("ZodBigInt",(e,t)=>{mh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>SA(e,r,o,n)},I.derived({minValue:e=>ot(e).minimum??null,maxValue:e=>ot(e).maximum??null,format:e=>ot(e).format??null},{gte(e,t){return this.check(br(e,t))},min(e,t){return this.check(br(e,t))},gt(e,t){return this.check(Zn(e,t))},lt(e,t){return this.check(Jn(e,t))},lte(e,t){return this.check(vr(e,t))},max(e,t){return this.check(vr(e,t))},positive(e){return this.check(Zn(BigInt(0),e))},negative(e){return this.check(Jn(BigInt(0),e))},nonpositive(e){return this.check(vr(BigInt(0),e))},nonnegative(e){return this.check(br(BigInt(0),e))},multipleOf(e,t){return this.check(Oi(e,t))}}));function dU(e){return WI(Kc,e)}var Cg=S("ZodBigIntFormat",(e,t)=>{jE.init(e,t),Kc.init(e,t)});function fU(e){return JI(Cg,e)}function pU(e){return ZI(Cg,e)}var vk=S("ZodSymbol",(e,t)=>{ME.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_A(e,r,o,n)});function mU(e){return GI(vk,e)}var bk=S("ZodUndefined",(e,t)=>{LE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>EA(e,r,o,n)});function hU(e){return XI(bk,e)}var Sk=S("ZodNull",(e,t)=>{FE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xA(e,r,o,n)});function _k(e){return YI(Sk,e)}var xk=S("ZodAny",(e,t)=>{VE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kA(e,r,o,n)});function gU(){return QI(xk)}var Ek=S("ZodUnknown",(e,t)=>{BE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$A(e,r,o,n)});function sa(){return eA(Ek)}var Ik=S("ZodNever",(e,t)=>{HE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>AA(e,r,o,n)});function Rg(e){return tA(Ik,e)}var Ak=S("ZodVoid",(e,t)=>{KE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>IA(e,r,o,n)});function yU(e){return rA(Ak,e)}var Nd=S("ZodDate",(e,t)=>{WE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>TA(e,r,o,n),e.min=(r,o)=>e.check(br(r,o)),e.max=(r,o)=>e.check(vr(r,o))},I.derived({minDate:e=>{let{minimum:t}=ot(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ot(e);return t?new Date(t):null}},{}));function wU(e){return nA(Nd,e)}var kk=S("ZodArray",(e,t)=>{ca(),JE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>FA(e,r,o,n),e.element=t.element},{min(e,t){return this.check(Yo(e,t))},nonempty(e){return this.check(Yo(1,e))},max(e,t){return this.check(na(e,t))},length(e,t){return this.check(oa(e,t))},unwrap(){return this.element}});function Dd(e,t){return sA(kk,e,t)}function vU(e){let t=e._zod.def.shape;return Og(Object.keys(t))}var zd=S("ZodObject",(e,t)=>{ca(),ZE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>VA(e,r,o,n),I.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Og(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(I.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(I.mergeDefs(this._zod.def,{catchall:sa()}))},loose(){return this.clone(I.mergeDefs(this._zod.def,{catchall:sa()}))},strict(){return this.clone(I.mergeDefs(this._zod.def,{catchall:Rg()}))},strip(){return this.clone(I.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return I.extend(this,e)},safeExtend(e){return I.safeExtend(this,e)},merge(e){return I.merge(this,e)},pick(e){return I.pick(this,e)},omit(e){return I.omit(this,e)},partial(...e){return I.partial(jd,this,e[0])},exactPartial(...e){return I.partial(Dg,this,e[0],"exactPartial")},required(...e){return I.required(zg,this,e[0])}});function bU(e,t){let r={type:"object",shape:e??{},...I.normalizeParams(t)};return new zd(r)}function SU(e,t){return new zd({type:"object",shape:e,catchall:Rg(),...I.normalizeParams(t)})}function _U(e,t){return new zd({type:"object",shape:e,catchall:sa(),...I.normalizeParams(t)})}var Ud=S("ZodUnion",(e,t)=>{gd.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ig(e,r,o,n),e.options=t.options});function Wc(e,t){return new Ud({type:"union",options:e,...I.normalizeParams(t)})}var $k=S("ZodXor",(e,t)=>{Ud.init(e,t),GE.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ig(e,r,o,n),e.options=t.options});function xU(e,t){return new $k({type:"union",options:e,inclusive:!1,...I.normalizeParams(t)})}var Tk=S("ZodDiscriminatedUnion",(e,t)=>{Ud.init(e,t),YE.init(e,t)});function EU(e,t,r){return new Tk({type:"union",options:t,discriminator:e,...I.normalizeParams(r)})}var Pk=S("ZodIntersection",(e,t)=>{QE.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>BA(e,r,o,n)});function Ck(e,t){return new Pk({type:"intersection",left:e,right:t})}var Rk=S("ZodTuple",(e,t)=>{ca(),hh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>HA(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new jd({type:"optional",innerType:t}))})}});function Ok(e,t,r){let o=t instanceof X,n=o?r:t,i=o?t:null;return new Rk({type:"tuple",items:e,rest:i,...I.normalizeParams(n)})}var Lc=S("ZodRecord",(e,t)=>{ca(),eI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>KA(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Nk(e,t,r){return!t||!t._zod?new Lc({type:"record",keyType:Cd(),valueType:e,...I.normalizeParams(t)}):new Lc({type:"record",keyType:e,valueType:t,...I.normalizeParams(r)})}function IU(e,t,r){return new Lc({type:"record",keyType:e,valueType:t,...I.normalizeParams(r),partial:!0})}function AU(e,t,r){return new Lc({type:"record",keyType:e,valueType:t,mode:"loose",...I.normalizeParams(r)})}var Dk=S("ZodMap",(e,t)=>{ca(),tI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>MA(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Gn(...r)),e.nonempty=r=>e.check(Gn(1,r)),e.max=(...r)=>e.check(Ni(...r)),e.size=(...r)=>e.check(ra(...r))});function kU(e,t,r){return new Dk({type:"map",keyType:e,valueType:t,...I.normalizeParams(r)})}var zk=S("ZodSet",(e,t)=>{ca(),rI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>LA(e,r,o,n),e.min=(...r)=>e.check(Gn(...r)),e.nonempty=r=>e.check(Gn(1,r)),e.max=(...r)=>e.check(Ni(...r)),e.size=(...r)=>e.check(ra(...r))});function $U(e,t){return new zk({type:"set",valueType:e,...I.normalizeParams(t)})}var Fc=S("ZodEnum",(e,t)=>{nI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(o,n,i)=>PA(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Fc({...t,checks:[],...I.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Fc({...t,checks:[],...I.normalizeParams(n),entries:i})}});function Og(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Fc({type:"enum",entries:r,...I.normalizeParams(t)})}function TU(e,t){return new Fc({type:"enum",entries:e,...I.normalizeParams(t)})}var Uk=S("ZodLiteral",(e,t)=>{oI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>CA(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function PU(e,t){return new Uk({type:"literal",values:Array.isArray(e)?e:[e],...I.normalizeParams(t)})}var jk=S("ZodFile",(e,t)=>{iI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>NA(e,r,o,n),e.min=(r,o)=>e.check(Gn(r,o)),e.max=(r,o)=>e.check(Ni(r,o)),e.mime=(r,o)=>e.check(Cc(Array.isArray(r)?r:[r],o))});function CU(e){return aA(jk,e)}var Mk=S("ZodTransform",(e,t)=>{ca(),sI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jA(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Ci(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(I.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=e),r.issues.push(I.issue(s))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function Ng(e){return new Mk({type:"transform",transform:e})}var jd=S("ZodOptional",(e,t)=>{gh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sg(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function aa(e){return new jd({type:"optional",innerType:e})}var Dg=S("ZodExactOptional",(e,t)=>{aI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sg(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Lk(e){return new Dg({type:"optional",innerType:e})}var Fk=S("ZodNullable",(e,t)=>{cI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>WA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Rd(e){return new Fk({type:"nullable",innerType:e})}function RU(e){return aa(Rd(e))}var Vk=S("ZodDefault",(e,t)=>{uI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ZA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bk(e,t){return new Vk({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():I.shallowClone(t)}})}var Hk=S("ZodPrefault",(e,t)=>{lI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>GA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Kk(e,t){return new Hk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():I.shallowClone(t)}})}var zg=S("ZodNonOptional",(e,t)=>{dI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Wk(e,t){return new zg({type:"nonoptional",innerType:e,...I.normalizeParams(t)})}var qk=S("ZodSuccess",(e,t)=>{fI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>DA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function OU(e){return new qk({type:"success",innerType:e})}var Jk=S("ZodCatch",(e,t)=>{pI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>XA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Zk(e,t){return new Jk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:I.constantCatch(t)})}var Gk=S("ZodNaN",(e,t)=>{mI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>RA(e,r,o,n)});function NU(e){return iA(Gk,e)}var Md=S("ZodPipe",(e,t)=>{yh.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>YA(e,r,o,n),e.in=t.in,e.out=t.out});function fg(e,t){return new Md({type:"pipe",in:e,out:t})}var Ld=S("ZodCodec",(e,t)=>{Md.init(e,t),yd.init(e,t)});function DU(e,t,r){return new Ld({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function zU(e){let t=e._zod.def;return new Ld({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Xk=S("ZodPreprocess",(e,t)=>{Md.init(e,t),hI.init(e,t)}),Yk=S("ZodReadonly",(e,t)=>{gI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>QA(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Qk(e){return new Yk({type:"readonly",innerType:e})}var e$=S("ZodTemplateLiteral",(e,t)=>{yI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>OA(e,r,o,n)});function UU(e,t){return new e$({type:"template_literal",parts:e,...I.normalizeParams(t)})}var t$=S("ZodLazy",(e,t)=>{wd.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>tk(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function r$(e){return new t$({type:"lazy",getter:e})}var n$=S("ZodPromise",(e,t)=>{vI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ek(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function jU(e){return new n$({type:"promise",innerType:e})}var o$=S("ZodFunction",(e,t)=>{wI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>UA(e,r,o,n)});function MU(e){return new o$({type:"function",input:Array.isArray(e?.input)?Ok(e?.input):e?.input??Dd(sa()),output:e?.output??sa()})}var Fd=S("ZodCustom",(e,t)=>{bI.init(e,t),te.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zA(e,r,o,n)});function LU(e){let t=new Ae({check:"custom"});return t._zod.check=e,t}function FU(e,t){return cA(Fd,e??(()=>!0),t)}function i$(e,t={}){return uA(Fd,e,t)}function s$(e,t){return lA(e,t)}var VU=dA,BU=fA,a$=S("ZodInstanceOf",(e,t)=>{Fd.init(e,t)},{properties(e,t){return this.check(Pc(e,t))}});function HU(e,t={}){let r=new a$({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...I.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var KU=(...e)=>pA({Codec:Ld,Boolean:Hc,String:Vc},...e);function WU(e){let t=r$(()=>Wc([Cd(e),yk(),wk(),_k(),Dd(t),Nk(Cd(),t)]));return t}function qU(e,t){return new Xk({type:"pipe",in:Ng(e),out:t})}var mee={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function hee(e){Ke({customError:e})}function gee(){return Ke().customError}var c$;c$||(c$={});var Vd={};Ce(Vd,{ZodISODate:()=>Mi,ZodISODateTime:()=>ji,ZodISODuration:()=>Fi,ZodISOTime:()=>Li,date:()=>wee,datetime:()=>yee,duration:()=>bee,time:()=>vee});function yee(e){return Id(ji,e)}function wee(e){return Ad(Mi,e)}function vee(e){return kd(Li,e)}function bee(e){return $d(Fi,e)}var z={...qc,...ug,iso:Vd},See=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function _ee(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function JU(e,t){return e.map((r,o)=>o<t?r:r.optional())}function xee(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Eee(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:xee(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function Iee(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let s of i){let a=t.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(e)}function u$(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let s of e){let a=u$(s,t);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let s=u$(e[i],t);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var Aee=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),kee=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Bd(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Bd):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>Aee.has(t)?Bd(r):!kee.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Bd))}function ZU(e){return e===1?"element":"elements"}function $ee(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=u$(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,s=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(t.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${ZU(i)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${ZU(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function GU(e,t){if(e!==!1)return e===void 0||e===!0?z.any():Xt(e,t)}var Tee=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function XU(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return z.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=Eee(n,t),s=Xt(i,t);return t.refs.set(n,s),t.processing.delete(n),s}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return z.null();if(n.length===0)return z.never();if(n.length===1)return z.literal(n[0]);if(n.every(s=>typeof s=="string"))return z.enum(n);let i=n.map(s=>z.literal(s));return i.length<2?i[0]:z.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return z.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...e,type:i};return XU(s,t)});return n.length===0?z.never():n.length===1?n[0]:z.union(n)}if(!r)return z.any();let o;switch(r){case"string":{let n=z.string();if(e.format){let i=e.format;i==="email"?n=n.check(z.email()):i==="uri"||i==="uri-reference"?n=n.check(z.url()):i==="uuid"||i==="guid"?n=n.check(z.uuid()):i==="date-time"?n=n.check(z.iso.datetime({offset:!0})):i==="date"?n=n.check(z.iso.date()):i==="time"?n=n.check(z.regex(Tee)):i==="duration"?n=n.check(z.iso.duration()):i==="hostname"?n=n.check(z.hostname()):i==="ipv4"?n=n.check(z.ipv4()):i==="ipv6"?n=n.check(z.ipv6()):i==="mac"?n=n.check(z.mac()):i==="cidr"?n=n.check(z.cidrv4()):i==="cidr-v6"?n=n.check(z.cidrv6()):i==="base64"?n=n.check(z.base64()):i==="base64url"?n=n.check(z.base64url()):i==="e164"?n=n.check(z.e164()):i==="credit_card"?n=n.check(z.creditCard()):i==="iban"?n=n.check(z.iban()):i==="jwt"?n=n.check(z.jwt()):i==="emoji"?n=n.check(z.emoji()):i==="nanoid"?n=n.check(z.nanoid()):i==="cuid"?n=n.check(z.cuid()):i==="cuid2"?n=n.check(z.cuid2()):i==="ulid"?n=n.check(z.ulid()):i==="xid"?n=n.check(z.xid()):i==="ksuid"&&(n=n.check(z.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?z.number().int():z.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=z.boolean();break}case"null":{o=z.null();break}case"object":{let n={},i=e.properties||{},s=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Xt(e.additionalProperties,t):void 0;for(let[d,p]of Object.entries(i)){let f=Xt(p,t);xt(n,d,s.has(d)?f:f.optional())}if(e.patternProperties){let d=e.patternProperties,p=Object.keys(d),f=[];for(let g of p){let w=Xt(d[g],t),v=z.string().regex(new RegExp(g));f.push(z.looseRecord(v,w))}let m=[];if(Object.keys(n).length>0&&m.push(z.object(n).passthrough()),m.push(...f),m.length===0)o=z.object({}).passthrough();else if(m.length===1)o=m[0];else{let g=z.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)g=z.intersection(g,m[w]);o=g}if(e.additionalProperties===!1){let g=Object.keys(n),w=p.map(b=>new RegExp(b)),v=o;o=o.check(b=>{if(!Dr(b.value))return;let x=[];for(let E of Object.keys(b.value))g.includes(E)||w.some(T=>T.test(E))||x.push(E);x.length&&b.issues.push({code:"unrecognized_keys",keys:x,input:b.value,inst:v})})}}else{let d=z.object(n);e.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=Xt(p,t)}o=Iee(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let s=typeof e.minItems=="number"?e.minItems:0,a=n.map(d=>Xt(d,t)),c=JU(a,s),u=Array.isArray(i)?void 0:GU(i,t),l=z.tuple(c);o=u?l.rest(u):l,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(Array.isArray(i)){let s=typeof e.minItems=="number"?e.minItems:0,a=i.map(d=>Xt(d,t)),c=JU(a,s),u=GU(e.additionalItems,t),l=z.tuple(c);o=u?l.rest(u):l,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(i!==void 0){let s=Xt(i,t),a=z.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),o=a}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=$ee(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Xt(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Xt(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r=XU(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Xt(u,t)),c=z.union(a);r=o?z.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Xt(u,t)),c=z.xor(a);r=o?z.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:z.any();else{let a=o?r:Xt(e.allOf[0],t),c=o?0:1;for(let u=c;u<e.allOf.length;u++)a=z.intersection(a,Xt(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=z.nullable(r)),e.readOnly===!0&&(r=z.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in e&&(n[a]=e[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in e&&(n[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Bd(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(n[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Bd(e.contains)&&(n.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(n[a]=e[a])}for(let a of Object.keys(e))See.has(a)||xt(n,a,e[a]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function YU(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=_ee(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??Et};return Xt(r,i)}var QU=Symbol("z.visit/resolving");function Hd(e,t){let r=typeof t=="function"?t:(s,a)=>{let c=t[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===QU)return new wd({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,QU);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let g=n(u[m]);g!==u[m]&&(d=!0),p[m]=g}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?Se(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:Se(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?Se(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:Se(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:Se(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?Se(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:Se(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:Se(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:Se(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:Se(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return Se(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(e)}function e4(e){return Hd(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Wc(r.options)}})}function Pee(e,t){if(!t?.length)return e;let r=e._zod.def;return Se(e,un(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function t4(e){return Pee(e.out,e.checks)}function Cee(e){return e.in._zod.traits.has("$ZodTransform")?t4(e):e.in}function r4(e){return Hd(e,{pipe:t=>Cee(t._zod.def),default:(t,r)=>r?aa(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function n4(e){return Hd(e,{pipe:t=>t4(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var l$={};Ce(l$,{bigint:()=>Dee,boolean:()=>Nee,date:()=>zee,number:()=>Oee,string:()=>Ree});function Ree(e){return RI(Vc,e)}function Oee(e){return jI(Bc,e)}function Nee(e){return KI(Hc,e)}function Dee(e){return qI(Kc,e)}function zee(e){return oA(Nd,e)}var Ug={name:"@tomato414941/foundation",version:"30.1.1",description:"Manage Foundation resources and use them in local commands.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&h.config({jitless:!0});function o4(e){let t=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(e.trim());if(!t)return null;try{let r=Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==t[1])return null;if(t[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(t[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(t[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var i4=h.string().trim().max(8192).refine(e=>o4(e)!==null,"Use an OpenSSH public key from a .pub file.");function s4(e){if(!o4(e))throw new Error("Use an OpenSSH public key from a .pub file.");let[t,r]=e.trim().split(/[ \t]+/);return{algorithm:t,key:r,publicKey:t+" "+r}}var e_e=h.string().max(32).regex(/^[a-z_][a-z0-9_-]*$/,"Use a lowercase account name."),a4=h.string().min(1).max(253).regex(/^[A-Za-z0-9_.:]+(?:-[A-Za-z0-9_.:]+)*$/,"Use a host name or IP address."),c4=h.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/);var f$=new TextEncoder,Mg=new TextDecoder,u4=new TextDecoder("utf-8",{fatal:!0}),jg=2**32;function fn(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function d$(e,t,r){if(t<0||t>=jg)throw new RangeError(`value must be >= 0 and <= ${jg-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function p$(e){let t=Math.floor(e/jg),r=e%jg,o=new Uint8Array(8);return d$(o,t,0),d$(o,r,4),o}function Lg(e){let t=new Uint8Array(4);return d$(t,e),t}var jee=/[^\x00-\x7f]/;function ei(e){if(typeof e=="string"&&e.length>=128){if(jee.test(e))throw new TypeError("non-ASCII string encountered in encode()");return f$.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=o}return t}function l4(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,o=[];for(let i=0;i<e.length;i+=r)o.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));let n=btoa(o.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function d4(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function Fg(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}var da=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Kd=class extends da{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pe=class extends da{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Vi=class extends da{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}},N=class extends da{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"};var Wd=class extends da{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var Mee="The input to be decoded is not correctly encoded.";function fa(e){try{return d4(typeof e=="string"?e:Mg.decode(e),!0)}catch(t){throw new TypeError(Mee,{cause:t})}}function it(e){return l4(typeof e=="string"?f$.encode(e):e,!0)}function pn(e,t){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be an instance of Uint8Array`)}function st(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Vg(...e){let t=new Set;for(let r of e)if(r)for(let o of Object.keys(r)){if(t.has(o))return!1;t.add(o)}return!0}function Yn(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}function mn(e,t,r){try{return fa(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function f4(e,t,r){try{return ei(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}function Bg(e,t,r){let o;try{o=JSON.parse(u4.decode(fa(e)))}catch{throw new t(r)}if(!st(o))throw new t(r);return o}var Hg={__proto__:null};function m$(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function p4(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Kg(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of o.crit){if(!(s in i))throw new Pe(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function Wg(e,t){let r,o;try{r=JSON.stringify(t),o=JSON.parse(r)}catch(n){throw new e("JOSE Header is not valid JSON",{cause:n})}if(!st(o))throw new e("JOSE Header is not a JSON object");return[o,r]}var Lee=e=>e[Symbol.toStringTag],Fee=(e,t,r)=>{let{alg:o}=e;if(t.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let n=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function pa(e,t,r){let{alg:o,secret:n}=e,i=r==="decrypt"||r==="sign";if(n&&t instanceof Uint8Array)return t;let s,a;if(st(t)){if(s=b$(t),typeof s.kty!="string")throw m4(o,t,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(Fee(e,s,r),s.kty==="oct")return fa(s.k);if(!Object.isFrozen(t)){let{key_ops:l}=t;Array.isArray(l)&&Object.freeze(l),Object.freeze(t)}}else{if(!y$(t))throw m4(o,t,n);let l=n?"secret":i?"private":"public";if(t.type!==l&&(n||["secret","public","private"].includes(t.type)))throw new TypeError(`${Lee(t)} instances must be of type "${l}" for the ${o} algorithm`);if(Bi(t))return t;if(a=t,a.type==="secret")return a.export()}h$||=new WeakMap;let c=t,u=h$.get(c);if(u?.[o])return u[o];if(u||h$.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Vee[a.asymmetricKeyDetails?.namedCurve],p=e.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[o]=a.toCryptoKey(p,l,e.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await Jc(e,s)}var h$,Vee={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function Jg(e){if(!Bi(e))throw new Error("CryptoKey instance expected")}var Bi=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},g$=e=>e?.[Symbol.toStringTag]==="KeyObject",y$=e=>Bi(e)||g$(e);function h4(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var ti=(e,...t)=>h4("Key must be ",e,...t);function m4(e,t,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(h4(`Key for the ${e} algorithm must be `,t,...o))}var qg=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function w$(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function g4(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function v$(e,t,r){let o=e.algorithm;if(o.name!==t.name)throw qg(t.name);if(t.hash&&o.hash?.name!==t.hash)throw qg(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw qg(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&o.length!==t.length)throw qg(t.length,"algorithm.length");w$(e,r)}function Zg(e){return{__proto__:null,...e}}function b$(e){let t=Zg(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=o}return t}function Gg(e){if(e!==void 0&&typeof e!="boolean")throw new TypeError('"extractable" option must be a boolean');return e}async function Jc(e,t,r){if(!e.kty.includes(t.kty))throw new Pe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),i={...t,ext:r??t.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,t.key_ops??e.usages[n?1:0])}async function ma(e,t,r,o=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,o,[r])),v$(e,t,r),e}var ha=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function Xg(e,t){let r=e.byteLength<<3;if(r!==t)throw new N(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var Bee=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function y4(e,t){if(t.length<<3!==e.ivBits)throw new N("Invalid Initialization Vector length")}async function w4(e,t,r){if(!(t instanceof Uint8Array))throw new TypeError(ti(t,"Uint8Array"));let o=e.cekBits>>1,n=await crypto.subtle.importKey("raw",t.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",t.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function v4(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function Hee(e,t,r,o,n){let[i,s,a]=await w4(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,t)),u=fn(n,o,c,p$(n.length*8)),l=await v4(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Kee(e,t){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,e);return crypto.subtle.verify(r,o,n,t)}async function Wee(e,t,r,o,n,i){let[s,a,c]=await w4(e,t,"decrypt"),u=fn(i,o,r,p$(i.length*8)),l=await v4(a,u,c);try{if(await Kee(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Vi}async function Yg(e,t,r,o,n){if(!Bi(r)&&!(r instanceof Uint8Array))throw new TypeError(ti(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?y4(e,o):o=Bee(e),r instanceof Uint8Array&&Xg(r,e.cekBits),e.cbc)return Hee(e,t,r,o,n);let i=await ma(r,e.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,t));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function Qg(e,t,r,o,n,i){if(!Bi(t)&&!(t instanceof Uint8Array))throw new TypeError(ti(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new N("JWE Initialization Vector missing");if(!n)throw new N("JWE Authentication Tag missing");if(!e.cbc&&n.length!==16)throw new N("Invalid Authentication Tag length");if(y4(e,o),t instanceof Uint8Array&&Xg(t,e.cekBits),e.cbc)return Wee(e,t,r,o,n,i);let s=await ma(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,fn(r,n)))}catch{throw new Vi}}function qd(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var qee=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Jee=[[],["deriveBits"]],ry=[[],[]];function ey(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:qee,ops:["wrapKey","unwrapKey"]}}function ty(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:t,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(t==="OKP")throw new Pe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Jee,ops:[void 0,"deriveBits"]}}function Zc(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:ry,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function S$(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:ry,ops:["deriveBits","deriveBits"]}}var ri=qd({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:ry,ops:["encrypt","decrypt"]},"RSA-OAEP":ey(1),"RSA-OAEP-256":ey(256),"RSA-OAEP-384":ey(384),"RSA-OAEP-512":ey(512),"ECDH-ES":ty("direct-key-agreement"),"ECDH-ES+A128KW":ty("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":ty("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":ty("key-agreement-with-key-wrapping"),A128KW:Zc(128),A192KW:Zc(192),A256KW:Zc(256),A128GCMKW:Zc(128,!0),A192GCMKW:Zc(192,!0),A256GCMKW:Zc(256,!0),"PBES2-HS256+A128KW":S$(),"PBES2-HS384+A192KW":S$(),"PBES2-HS512+A256KW":S$()}),Zee=["encrypt","decrypt"];function Gc(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:ry,ops:Zee,cekBits:e,ivBits:t?128:96,cbc:t}}var Gee=qd({A128GCM:Gc(128),A192GCM:Gc(192),A256GCM:Gc(256),"A128CBC-HS256":Gc(256,!0),"A192CBC-HS384":Gc(384,!0),"A256CBC-HS512":Gc(512,!0)});function b4(e,t){throw new Pe(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function hn(e){return(typeof e=="string"?ri[e]:void 0)??b4("alg","Algorithm")}function gn(e){return e.mode==="key-wrapping"||e.mode==="key-encryption"||e.mode==="key-agreement-with-key-wrapping"}function ga(e){return(typeof e=="string"?Gee[e]:void 0)??b4("enc","Encryption Algorithm")}function S4(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");w$(e,t)}async function Xee(e,t,r){let o=await ma(t,hn(e).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function Yee(e,t,r){let o=await ma(t,hn(e).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function x4(e,t,r){v$(t,hn(e).subtle,r),g4(e,t)}async function E4(e,t,r,o){if(!(e instanceof Uint8Array)||e.length<8)throw new N("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new N("PBES2 Count Input must be a positive integer");let n=fn(ei(t),Uint8Array.of(0),e),i=parseInt(t.slice(13,16),10),s={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await ma(o,hn(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function _$(e){return fn(Lg(e.length),e)}async function Qee(e,t,r){let o=t>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await Fg("sha256",fn(Lg(a),e,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function I4(e,t,r,o,n=new Uint8Array,i=new Uint8Array){S4(e),S4(t,"deriveBits");let s=fn(_$(ei(r)),_$(n),_$(i),Lg(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return Qee(a,o,s)}function A4(e){Jg(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new Pe("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ny(e,t){let r=e[t];if(r!==void 0){if(typeof r!="string")throw new N(`JOSE Header "${t}" (Agreement Party${t==="apu"?"U":"V"}Info) invalid`);return mn(r,t,N)}}function k4(e,t){if(!(e===void 0||t===void 0||e.byteLength!==t.byteLength)){for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return;throw new N('JOSE Header "apu" and "apv" values must be distinct')}}function ete(e){if(e===void 0)throw new N("JWE Encrypted Key missing")}function _4(e){if(e!==void 0)throw new N("Encountered unexpected JWE Encrypted Key")}function tte(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function $4(e,t,r,o,n,i){let{alg:s}=e,a=e.mode;if(a==="direct-encryption")return _4(o),r;let c=a==="direct-key-agreement";switch(c?_4(o):ete(o),e.subtle.name){case"ECDH":{let{epk:u}=n;if(!st(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new N('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');A4(r);let l=await Jc(e,u),d=ny(n,"apu"),p=ny(n,"apv");k4(d,p);let f=await I4(l,r,c?t.alg:s,c?t.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return Jg(r),x4(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new N('JOSE Header "p2c" (PBES2 Count) missing or invalid');tte(i);let u=i??1e4;if(n.p2c>u)throw new N('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new N('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=mn(n.p2s,"p2s",N);r=await E4(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new N('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new N('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=mn(n.iv,"iv",N),l=mn(n.tag,"tag",N);if(u.byteLength!==12)throw new N("Invalid Initialization Vector length");if(l.byteLength!==16)throw new N("Invalid Authentication Tag length");return Qg(ga(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Yee(s.slice(-6),r,o)}async function oy(e,t,r,o,n,i={}){let{alg:s,mode:a}=e,c=gn(e);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await pa(a==="direct-encryption"?t:e,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??ha(t):void 0;l&&Xg(l,t.cekBits);let d,p;switch(e.subtle.name){case"ECDH":{A4(u);let{apu:f,apv:m}=i;f!==void 0&&pn(f,'"apu"'),m!==void 0&&pn(m,'"apv"');let g=f??ny(o,"apu"),w=m??ny(o,"apv");k4(g,w);let v;i.epk!==void 0?v=await pa(e,i.epk,"decrypt"):v=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,x=v;if(!x.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await b.getPublicKey(v,[])}let{x:E,y:T,crv:R,kty:U}=await b.exportKey("jwk",x),j=a==="direct-key-agreement",Y=await I4(u,v,j?t.alg:s,j?t.cekBits:parseInt(s.slice(-5,-2),10),g,w),B={x:E,crv:R,kty:U};if(U==="EC"&&(B.y=T),p={epk:B},f!==void 0&&(p.apu=it(f)),m!==void 0&&(p.apv=it(m)),j)return[Y,void 0,p];u=Y;break}case"RSA-OAEP":{Jg(u),x4(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await E4(m,s,f,u),p={p2c:f,p2s:it(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await Yg(ga(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:it(m.iv),tag:it(m.tag)}}}if(d??=await Xee(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function iy(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new Pe('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new N('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function T4(e){if(typeof globalThis[e]>"u")throw new Pe(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function P4(e,t,r=1/0){let o=e.writable.getWriter();o.write(t).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=e.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new N("Decompressed plaintext exceeded the configured limit")}return fn(...n)}async function C4(e){return T4("CompressionStream"),P4(new CompressionStream("deflate-raw"),e)}async function R4(e,t){return T4("DecompressionStream"),P4(new DecompressionStream("deflate-raw"),e,t)}function O4(e){let{aad:t,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=e;if(o!==void 0&&(typeof o!="string"||!o))throw new N("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new N("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new N("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new N("JWE Protected Header incorrect type");if(t!==void 0&&(typeof t!="string"||!t))throw new N("JWE AAD incorrect type");if(s!==void 0&&!st(s))throw new N("JWE Shared Unprotected Header incorrect type");return{aad:t,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function N4(e){let t,r;try{let{header:o}=e;if(st(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),t=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else t=o;let{encrypted_key:n}=e;return[{encrypted_key:n,header:t},r]}catch(o){return[void 0,r,o]}}function D4(e){let{encrypted_key:t,header:r}=e;if(t!==void 0&&typeof t!="string")throw new N("JWE Encrypted Key incorrect type");if(r!==void 0&&!st(r))throw new N("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected===void 0&&r===void 0&&e.unprotected===void 0)throw new N("JOSE Header missing")}function x$(e){let{protected:t,ciphertext:r,iv:o,tag:n,aad:i}=e,s;return t!==void 0&&(s=Bg(t,N,"JWE Protected Header is invalid")),[s,mn(r,"ciphertext",N),o!==void 0?mn(o,"iv",N):void 0,n!==void 0?mn(n,"tag",N):void 0,f4((t??"")+(i!==void 0?`.${i}`:""),"aad",N)]}function sy(e){return[e&&m$("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&m$("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function E$(e,t,r,o=x$(e)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=e,p;if(u!==void 0||l!==void 0){if(!Vg(n,u,l))throw new N("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,g,w,v]=t,{encrypted_key:b}=e;Kg(N,Hg,g,n,p),iy(p,n);let{alg:x,enc:E}=p;if(typeof x!="string"||!x)throw new N("missing JWE Algorithm (alg) in JWE Header");let T=ri[x];if(b===""&&(!T||!gn(T)))throw new N("JWE Encrypted Key incorrect type");let R=T?.mode==="integrated-encryption";if(!R&&(typeof E!="string"||!E))throw new N("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(x)||!f&&x.startsWith("PBES2"))throw new Kd('"alg" (Algorithm) Header Parameter value not allowed');let U;if(R){if(E!==void 0)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new N("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new N("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(E))throw new Kd('"enc" (Encryption Algorithm) Header Parameter value not allowed');U=ga(E)}let j;if(b!==void 0)try{j=mn(b,"encrypted_key",N)}catch(le){if(!T||!gn(T))throw le;j=new Uint8Array}let Y=!1;typeof r=="function"&&(r=await r(n,e),Y=!0);let B=T??hn(x);gn(B)&&j===void 0&&(j=new Uint8Array);let ge=await pa(B.mode==="direct-encryption"?U:B,r,"decrypt"),me;if(B.mode==="integrated-encryption")me=await B.decrypt(ge,j,i,c,n,p);else{let le=U,F;try{F=await $4(B,le,ge,j,p,w),gn(B)&&F instanceof Uint8Array&&F.byteLength<<3!==le.cekBits&&(F=ha(le))}catch(Me){if(Me instanceof TypeError||Me instanceof N||Me instanceof Pe)throw Me;F=ha(le)}me=await Qg(le,F,i,s,a,c)}if(p.zip==="DEF"){let le=v??25e4;if(le===0)throw new Pe('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(le!==1/0&&(!Number.isSafeInteger(le)||le<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");me=await R4(me,le).catch(F=>{throw F instanceof N?F:new N("Failed to decompress plaintext",{cause:F})})}return{plaintext:me,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:mn(d,"aad",N)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Y&&{key:ge}}}async function z4(e,t,r){if(e instanceof Uint8Array&&(e=Mg.decode(e)),typeof e!="string")throw new N("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=e.split(".");if(c!==5)throw new N("Invalid Compact JWE");return E$({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},t,r)}async function Jd(e,t,r){return z4(e,sy(r),t)}async function I$(e,t,r){if(!st(e))throw new N("General JWE must be an object");let o=e.recipients;if(!Array.isArray(o))throw new N("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(st))throw new N("JWE Recipients missing or incorrect type");if(!n.length)throw new N("JWE Recipients has no members");let i,s,a;try{i=sy(r),s=O4(e),a=x$(s)}catch{throw new Vi}let c=n.map(u=>N4(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?ri[l]:void 0;if(d&&!gn(d))throw new N(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return D4(l),await E$(l,i,t,a)}catch{}throw new Vi}function ay(e,t,r){if(!Vg(e,t,r))throw new N("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function A$(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new N("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");t!==void 0&&(e[8]=t?.crit);let[,o,n,i,s,a,c,u,l]=e;if(s!==void 0&&pn(s,"JWE Additional Authenticated Data"),a!==void 0&&pn(a,"JWE Content Encryption Key"),c!==void 0&&pn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Wg(N,o)[0],e[1]=o),n!==void 0&&(n=Wg(N,n)[0],e[2]=n),!r&&i!==void 0&&(i=Wg(N,i)[0],e[3]=i),u!==void 0&&!st(u))throw new TypeError("JWE Key Management Parameters must be an object");ay(o,n,i);let d={...o,...n,...i};p4(N,o),Kg(N,Hg,l,o,d),iy(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new N('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=ri[p];if(m?.mode==="integrated-encryption"){if(f!==void 0)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,ga(f),m]}async function k$(e,t,r){let[o,n,i]=t,[s,a,c,u,l,d,p,f,,m]=e,g=a,w=c,v=i??hn(o.alg),b,x,E;v.mode==="integrated-encryption"?E=await pa(v,r,"encrypt"):[E,b,x]=await oy(v,n,r,o,d,f),x&&(m?w=w?{...w,...x}:x:g=g?{...g,...x}:x,ay(g,w,u));let T=g?it(JSON.stringify(g)):"",R=l?.byteLength?it(l):void 0,U=ei(R?`${T}.${R}`:T),j=s;o.zip==="DEF"&&(j=await C4(j).catch(le=>{throw new N("Failed to compress plaintext",{cause:le})}));let Y,B,ge;v.mode==="integrated-encryption"?[b,Y]=await v.encrypt(E,j,U,g,o,f):{ciphertext:Y,tag:B,iv:ge}=await Yg(n,j,E,p,U);let me={ciphertext:it(Y)};return ge&&(me.iv=it(ge)),B&&(me.tag=it(B)),b?.byteLength&&(me.encrypted_key=it(b)),R&&(me.aad=R),g&&(me.protected=T),u&&(me.unprotected=u),w&&(me.header=w),me}async function U4(e,t,r){return k$(e,A$(e,r),t)}function j4(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(".")}var $$=class{#e;state;constructor(t,r,o){this.#e=t,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(t){return Yn(this.state[0],"setUnprotectedHeader"),this.state[0]=t,this}setKeyManagementParameters(t){return Yn(this.state[1],"setKeyManagementParameters"),this.state[1]=t,this}addRecipient(...t){return this.#e.addRecipient(...t)}encrypt(...t){return this.#e.encrypt(...t)}done(){return this.#e}},Zd=class{#e;#t=[];#r;#n;#o;constructor(t){this.#e=t}addRecipient(t,r){let o=new $$(this,t,r?.crit);return this.#t.push(o),o}setProtectedHeader(t){return Yn(this.#r,"setProtectedHeader"),this.#r=t,this}setSharedUnprotectedHeader(t){return Yn(this.#n,"setSharedUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#o=t,this}async encrypt(){if(!this.#t.length)throw new N("at least one recipient must be added");pn(this.#e,"plaintext");let t=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[g,w,v,b]=m.state,x=[this.#e,o,g,n,this.#o,void 0,void 0,w,b,t],E=A$(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,E,v]);let[{alg:T,enc:R},,U]=E;if(t&&U&&!gn(U))throw new N(`"${T}" alg may only have a single recipient`);if(!r)r=R;else if(r!==R)throw new N('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=hn(m[0].alg);let[s,a,c]=i[0],u=t?ha(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await k$(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[g,[w,v,b],x]=i[m],E=g[2],[,T,R]=await oy(b,v,x,w,u,g[7]),U={encrypted_key:it(T)};if(E||R){let j={...E,...R};R&&ay(g[1],j,g[3]),U.header=j}f.recipients.push(U)}return f}};var Gd=[["verify"],["sign"]];function T$(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Gd}}function Xc(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Gd,minRsaBits:2048}}function P$(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Gd}}function M4(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Gd}}function C$(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Gd}}var L4=qd({HS256:T$(256),HS384:T$(384),HS512:T$(512),RS256:Xc(256),RS384:Xc(384),RS512:Xc(512),PS256:Xc(256,32),PS384:Xc(384,48),PS512:Xc(512,64),ES256:P$("P-256",256),ES384:P$("P-384",384),ES512:P$("P-521",512),EdDSA:M4(),Ed25519:M4(),"ML-DSA-44":C$(44),"ML-DSA-65":C$(65),"ML-DSA-87":C$(87)});var Yc=class{#e;constructor(t){pn(t,"plaintext"),this.#e=[t]}setContentEncryptionKey(t){return Yn(this.#e[5],"setContentEncryptionKey"),this.#e[5]=t,this}setInitializationVector(t){return Yn(this.#e[6],"setInitializationVector"),this.#e[6]=t,this}setProtectedHeader(t){return Yn(this.#e[1],"setProtectedHeader"),this.#e[1]=t,this}setKeyManagementParameters(t){return Yn(this.#e[7],"setKeyManagementParameters"),this.#e[7]=t,this}async encrypt(t,r){return j4(await U4([...this.#e],t,r))}};var R$='"alg" (Algorithm)';function O$(e='JWK "alg" (Algorithm) Parameter'){throw new Pe(`Invalid or unsupported ${e} value`)}function Xd(e,t){return(typeof e=="string"?L4[e]??ri[e]:void 0)??O$(t)}async function Qc(e){if(g$(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:it(e)};if(!Bi(e))throw new TypeError(ti(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let t=await crypto.subtle.exportKey("jwk",e);delete t.ext,delete t.key_ops,delete t.use,t.kty!=="AKP"&&delete t.alg;for(let r of Object.keys(t))t[r]===void 0&&delete t[r];return t}var ni=(e,t)=>{if(typeof e!="string"||!e)throw new Wd(`${t} missing or invalid`)};async function N$(e,t){let r;if(st(e)){if(r=Zg(e),typeof r.kty!="string")throw new TypeError(ti(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(y$(e))r=Zg(await Qc(e));else throw new TypeError(ti(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":ni(r.alg,'"alg" (Algorithm) Parameter'),ni(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":ni(r.crv,'"crv" (Curve) Parameter'),ni(r.x,'"x" (X Coordinate) Parameter'),ni(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":ni(r.crv,'"crv" (Subtype of Key Pair) Parameter'),ni(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":ni(r.e,'"e" (Exponent) Parameter'),ni(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new Wd('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Pe('"kty" (Key Type) Parameter missing or unsupported')}let n=ei(JSON.stringify(o));return it(await Fg(t,n))}async function ya(e,t,r){if(!st(e))throw new TypeError("JWK must be an object");let o=b$(e),n=Gg(r?.extractable),{alg:i}=o;if(t??=i,o.kty!=="oct"&&!t)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return fa(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==i)throw new TypeError("JWK alg and alg option value mismatch");return Jc(Xd(t),o,n)}case"RSA":case"EC":case"OKP":return Jc(Xd(t),o,n);default:throw new Pe('Unsupported "kty" (Key Type) Parameter value')}}function D$(e){let t;if(typeof e=="string"){let o=e.split(".");(o.length===3||o.length===5)&&([t]=o)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof t!="string"||!t)throw new TypeError(r);return Bg(t,TypeError,r)}function rte(e){let t=e?.modulusLength??2048;if(typeof t!="number"||!Number.isInteger(t)||t<2048)throw new Pe("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function z$(e,t){let r=Gg(t?.extractable),o=Xd(e,R$);o.secret&&O$(R$);let n;if(o.resolve){let i=t?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Pe("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&t?.crv!==void 0&&t.crv!==o.crv)throw new Pe(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:rte(t)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var H4=h.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),K4=h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),F4=h.string().min(1).max(128),V4=h.string().min(1).max(16384),nte=h.discriminatedUnion("kind",[h.object({kind:h.literal("access_key"),accessKeyId:F4,secretAccessKey:V4}).strict(),h.object({kind:h.literal("session"),accessKeyId:F4,secretAccessKey:V4,sessionToken:h.string().min(1).max(16384),expiresAt:h.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),h.object({kind:h.literal("environment")}).strict()]),ote=h.object({arn:K4,externalId:h.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),wa=h.object({authentication:nte,region:H4,role:ote.optional()}).strict(),cy=h.object({accountId:h.string().regex(/^\d{12}$/),principalId:h.string().min(1).max(256),arn:h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),uy=wa.extend({sourceIdentity:cy.optional(),identity:cy.optional()}).strict();function eu(e){return e.includes(":assumed-role/")?e.slice(0,e.lastIndexOf("/")):e}function B4(e){return{...e,arn:eu(e.arn)}}function W4(e){return{authentication:e.authentication.kind,region:e.region,role:e.role??null,...e.sourceIdentity?{sourceIdentity:B4(e.sourceIdentity)}:{},...e.identity?{identity:B4(e.identity)}:{}}}var ly=h.object({authentication:h.enum(["access_key","session","environment"]),region:H4,sourceAccountId:h.string().regex(/^\d{12}$/).optional(),sourceArn:h.string().max(2e3).optional(),roleArn:K4.optional(),expiresAt:h.number().int().positive().optional()}).strict();function q4(e){return{authentication:e.authentication.kind,region:e.region,...e.sourceIdentity?{sourceAccountId:e.sourceIdentity.accountId,sourceArn:e.sourceIdentity.arn}:{},...e.role?{roleArn:e.role.arn}:{},...e.authentication.kind==="session"?{expiresAt:e.authentication.expiresAt}:{}}}typeof window<"u"&&h.config({jitless:!0});var $=h.uuid(),ce=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Re=h.iso.datetime(),ba=h.json(),It=h.record(h.string(),ba),Z4=h.enum(["ja","en"]),U$=h.enum(["read","create","update","delete","share","transfer","reveal","use","manage_credentials","export"]);var j$=h.enum(["variable","connection","service","method","app","object","ssh_key","ssh_host"]),yn=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),ite=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:$}).strict(),ef=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(e=>{try{return ite.safeParse(D$(e)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Qn=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:h.string().regex(/^[A-Za-z0-9_-]{1,64}$/),epk:yn.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),tu=h.object({id:$,name:ce,publicKey:yn}),ru=h.object({id:$,name:ce,owner:h.object({id:$,name:ce}).nullable(),createdAt:Re,permissions:h.array(U$),createKinds:h.array(j$),items:h.partialRecord(j$,h.array(U$)).optional(),publicKey:yn.nullable()}),G4=h.object({id:$,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:Re,lastUsedAt:Re.nullable(),expiresAt:Re.nullable(),canOpen:h.boolean()}),X4=h.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ste=h.object({subjectId:$,relation:X4,objectId:$}).strict(),Y4=h.enum(["principal",...j$.options]),Q4=ste.extend({objectType:Y4,subjectName:ce,objectName:ce,createdAt:Re}),pEe=h.object({error:h.object({code:h.string(),message:h.string(),details:ba.optional()})}),mEe=h.object({ok:h.literal(!0)}),ate=h.object({value:h.string().min(1).max(200),label:h.string().min(1).max(200),values:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).default({})}).strict(),fy=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),inputType:h.enum(["text","password","file"]).optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional(),choices:h.array(ate).min(1).max(100).optional(),defaultValue:h.string().max(1e3).optional(),when:h.object({field:h.string(),values:h.array(h.string()).min(1)}).strict().optional(),visibility:h.enum(["application","connection"]).optional()}).superRefine((e,t)=>{let r=e.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&t.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),M$=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),cte=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.union([h.string(),h.array(h.union([h.string().max(8192),h.object({pointer:h.string().max(1e3)}).strict()])).min(1).max(32)])),L$=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),required:h.array(h.string()).optional(),separator:h.string().default(" "),docs:h.url().optional()}),va=h.string().min(1).max(4096),dy=h.union([h.string(),h.array(h.string()).min(1)]),ur="urn:ietf:params:oauth:grant-type:device_code",ute=h.object({browserTokenExchange:h.enum(["available","unavailable","unknown"]).optional(),application:h.enum(["required","implicit"]).default("required"),grantType:h.enum(["authorization_code","client_credentials",ur]).optional(),issuer:h.url().optional(),registrationUrl:h.url().optional(),authorizeUrl:va.optional(),deviceAuthorizationUrl:va.optional(),tokenUrl:va,identity:h.object({url:va.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:dy.default("/id"),name:dy.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:L$.default({default:[],separator:" "}),fields:h.array(fy).default([]),outputs:M$.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}).refine(e=>e.grantType==="client_credentials"||e.grantType===ur||!!e.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}).refine(e=>e.grantType!==ur||!!e.deviceAuthorizationUrl,{path:["deviceAuthorizationUrl"],message:"A device flow requires a device authorization URL."}),lte=h.object({fields:h.array(fy).min(1),outputs:cte,resolver:h.literal("vultr-role").optional(),bindFields:h.boolean().optional(),constants:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).optional(),files:h.array(h.string().regex(/^[A-Z_][A-Z0-9_]*$/)).max(32).optional(),account:h.object({field:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),pointer:h.string().max(1e3)}).strict().optional(),identity:h.object({url:va,headers:h.record(h.string(),h.string()),id:dy,name:dy}).strict().optional(),console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}).superRefine((e,t)=>{e.files?.some(r=>!Object.hasOwn(e.outputs,r))&&t.addIssue({code:"custom",path:["files"],message:"Deliver only declared outputs as files."}),e.account&&!e.fields.some(r=>r.name===e.account.field)&&t.addIssue({code:"custom",path:["account"],message:"Read the account from a declared field."})}),F$=h.enum(["oauth","token","aws","ovh","approval"]),dte=h.object({hint:h.string().optional()}).strict(),fte=h.object({authorization:h.enum(["api_key","consumer_key"]),apiBaseUrl:va,fields:h.array(fy).min(1),scopes:L$.default({default:[],separator:`
|
|
122
|
+
`}),outputs:M$,hint:h.string().optional()}).strict(),tf={name:ce,docs:h.url().optional(),console:va.optional(),preparation:h.object({scopeSelection:h.enum(["optional","required","hidden"]).default("optional"),instructions:h.array(h.union([h.string().max(2e3),h.object({ja:h.string().max(2e3),en:h.string().max(2e3)}).strict()])).max(10).default([]),docs:h.boolean().default(!1)}).strict().optional()},py=h.object({...tf,kind:h.literal("oauth"),config:ute}).strict(),my=h.object({...tf,kind:h.literal("token"),config:lte}).strict(),hy=h.object({...tf,kind:h.literal("aws"),config:dte}).strict(),gy=h.object({...tf,kind:h.literal("ovh"),config:fte}).strict(),yy=h.object({...tf,kind:h.literal("approval"),config:h.object({adapter:h.literal("runpod-flash"),fields:h.array(fy).default([]),scopes:L$.default({default:[],separator:" "}),outputs:M$,hint:h.string().optional()}).strict()}).strict(),nu=h.discriminatedUnion("kind",[py,my,hy,gy,yy]),Yd={id:h.string().min(1),builtin:h.boolean(),availability:h.enum(["ready","app-required","unavailable"]),defaultName:ce,registration:h.object({kind:h.enum(["input","authorization"]),device:h.enum(["browser","cli"]),browserExchange:h.enum(["available","unavailable","unknown"]),tokenAlternatives:h.array(h.string())}).strict()},oi=h.discriminatedUnion("kind",[py.extend(Yd),my.extend(Yd),hy.extend(Yd),gy.extend(Yd),yy.extend(Yd)]),Qd=h.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),V$=h.object({name:ce,logo:h.string().regex(/^[a-z0-9-]+$/).optional(),api:h.url().optional(),docs:h.url().optional(),console:h.url().optional(),targets:h.array(h.object({id:Qd,name:ce,api:h.url().optional(),methods:h.array(Qd).min(1)}).strict()).max(32).optional()}).strict(),pte=V$.extend({methods:h.record(Qd,h.string().min(1))}).strict(),ej=V$.extend({methods:h.record(Qd,h.union([h.string().min(1),nu]))}).strict(),tj=V$.extend({id:h.string(),builtin:h.boolean(),methods:h.record(Qd,oi)}),mte=h.object({id:$,output:h.string().min(1).max(100).optional()}).strict(),rj=e=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(e),nj=h.object({name:h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:mte,format:h.enum(["text","file","json"]).optional(),pointer:h.string().optional()}).strict(),Hi={id:$,ownerId:$,name:ce,createdAt:Re,updatedAt:Re,version:h.number().int().positive(),permissions:h.array(U$)},hte=h.object({...Hi,kind:h.literal("variable"),data:h.object({bytes:h.number().int().nonnegative()})}),gte=h.object({...Hi,kind:h.literal("connection"),data:h.object({methodId:h.string(),fields:h.record(h.string(),h.string()).default({}),settings:h.array(h.object({name:h.string(),label:h.string(),value:h.string()})).default([]),methodName:h.string(),methodKind:F$,services:h.array(h.object({id:h.string(),name:ce})).default([]),account:h.string(),accountId:h.string().nullable().default(null),accountVerified:h.boolean().default(!1),scopes:h.array(h.string()),scopesStatus:h.enum(["unknown","requested","reported"]).default("unknown"),outputs:h.array(h.string()),state:h.enum(["ready","reconnect","disconnecting","uncertain"]),appId:$.nullable(),generation:$.optional(),aws:ly.optional()})}),yte=h.object({...Hi,kind:h.literal("service"),data:pte}),wte=h.object({...Hi,kind:h.literal("method"),data:nu}),vte=h.object({...Hi,kind:h.literal("app"),data:h.object({methodId:h.string(),clientId:h.string(),fields:h.record(h.string(),h.string()).default({}),generation:$.optional()})}),bte=h.object({...Hi,kind:h.literal("object"),data:h.object({size:h.number().int().nonnegative(),contentType:h.string()})}),Ste=h.object({publicKey:i4,algorithm:h.string(),fingerprint:c4,purpose:h.string().max(500),privateKeyId:$.nullable()}),_te=h.object({...Hi,kind:h.literal("ssh_key"),data:Ste}),xte=h.object({address:a4,port:h.number().int().min(1).max(65535)}),Ete=h.object({...Hi,kind:h.literal("ssh_host"),data:xte}),ze=h.discriminatedUnion("kind",[hte,gte,yte,wte,vte,bte,_te,Ete]),hEe=h.discriminatedUnion("kind",[h.object({kind:h.literal("service"),name:ce,definition:ej}).strict(),h.object({kind:h.literal("method"),name:ce,definition:nu}).strict()]),gEe=h.object({version:h.number().int().positive(),name:ce.optional(),definition:h.union([ej,nu]).optional()}).strict(),eo=h.object({name:h.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:It}).strict(),B$=eo.extend({inputs:h.array(h.object({pointer:h.string(),label:h.string().min(1).max(100),secret:h.boolean().default(!1),multiline:h.boolean().default(!1),site:h.url().optional()}).strict()).max(16).default([])}),wy=h.object({ja:h.string(),en:h.string()}).strict(),J4=h.object({id:$,name:ce}),oj=h.object({kind:h.literal("transfer"),item:J4,to:J4}),yEe=h.object({id:$,name:ce,publicKey:yn,state:h.enum(["pending","approving","approved"]),principalId:$.nullable(),createdAt:Re,expiresAt:Re}),wEe=h.object({id:h.string(),actorId:$.nullable(),action:h.string(),targetId:$.nullable(),createdAt:Re,details:It}),vEe=h.object({returnUrl:h.url().optional(),refreshUrl:h.url().optional()}).strict(),pt=e=>h.object({items:h.array(e),next:h.string().nullable().default(null)}),bEe=h.object({id:$}),Ite=h.object({limit:h.coerce.number().int().min(1).max(200).default(100),after:h.string().optional()}),SEe=Ite.extend({object:$.optional(),subject:$.optional(),relation:X4.optional(),objectType:Y4.optional()}).refine(e=>!!e.object!=!!e.subject,"Choose the object or the subject of the lines.");var Ate=h.object({requestedAt:Re,readyAt:Re}).strict(),kte=h.object({email:h.boolean(),storage:h.boolean()}),vy=h.object({principal:ru.nullable(),credentialId:$.nullable(),wrappedKey:ef.nullable(),keyReset:Ate.nullable(),server:h.object({name:ce}),features:kte,principals:h.array(ru)}),IEe=h.object({email:h.email().max(254),returnTo:h.string().max(2048).optional(),locale:Z4.default("ja"),principalId:$.optional()}).strict(),AEe=h.object({intent:h.enum(["register","authenticate"]),name:ce.optional(),principalId:$.optional(),credentialId:$.optional(),returnTo:h.string().max(2048).optional()}).strict(),kEe=h.object({challengeId:$,credential:h.json(),publicKey:yn.optional(),wrappedKey:ef.optional()}).strict(),$Ee=h.object({publicKey:yn,wrappedKey:ef}).strict();var $te=new TextEncoder,Tte=new TextDecoder,rf="ECDH-ES+A256KW",H$="A256GCM",at=e=>$te.encode(e),lr=e=>Tte.decode(e);function nf(e){let t="";for(let r=0;r<e.length;r+=8192)t+=String.fromCharCode(...e.subarray(r,r+8192));return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ij(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}async function K$(){let e=await z$(rf,{crv:"P-256",extractable:!0});return{publicKey:yn.parse(await Qc(e.publicKey)),privateKey:await Qc(e.privateKey)}}var Pte=yn.extend({d:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}),of=h.object({encryption:Pte});async function sj(){return of.parse({encryption:(await K$()).privateKey})}function ou(e){return yn.parse({kty:e.kty,crv:e.crv,x:e.x,y:e.y})}function Sr(e){return N$(ou(e),"sha256")}async function by(e,t,r){if(!t.length||new Set(t.map(n=>n.id)).size!==t.length)throw new Error("Recipients must be distinct and nonempty.");let o=new Zd(e).setProtectedHeader({enc:H$});r!==void 0&&o.setAdditionalAuthenticatedData(at(r));for(let n of t)o.addRecipient(await ya(n.publicKey,rf)).setUnprotectedHeader({alg:rf,kid:n.id});return Qn.parse(await o.encrypt())}async function Ki(e,t,r,o){if(o!==void 0&&e.aad!==nf(at(o)))throw new Error("The encrypted content belongs to a different item.");let n=e.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=t instanceof CryptoKey?t:await ya(t,rf);return(await I$({...e,recipients:[n]},i,{keyManagementAlgorithms:[rf],contentEncryptionAlgorithms:[H$]})).plaintext}async function Cte(e){let t=await crypto.subtle.importKey("raw",new Uint8Array(e),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:at("Foundation"),info:at("passkey encryption key")},t,256))}async function aj(e,t,r){let o=await Jd(e,await Cte(t),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[H$]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(lr(o.plaintext))}var cj=h.string().regex(/^[A-Za-z0-9_-]{43}$/);function Be(e){if(e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&!/[\uD800-\uDFFF]/u.test(e))return JSON.stringify(e);if(Array.isArray(e))return"["+Array.from(e,Be).join(",")+"]";if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype)return"{"+Object.keys(e).sort().map(t=>{if(/[\uD800-\uDFFF]/u.test(t))throw new Error("Use Unicode property names.");return JSON.stringify(t)+":"+Be(e[t])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Sy(e){return nf(new Uint8Array(await crypto.subtle.digest("SHA-256",at(Be(e)))))}var Sa=class extends Error{constructor(r,o,n,i,s){super(n);this.code=r;this.status=o;this.details=i;this.origin=s}code;status;details;origin},iu=class extends Error{constructor(r,o,n){super("Foundation answered "+o+" in a form this CLI does not read.");this.origin=r;this.path=o;this.error=n}origin;path;error},sf=class{constructor(t){this.identity=t}identity;async response(t,r={}){if(!t.startsWith("/api/")||t.includes("\\")||/[\u0000-\u001f]/.test(t))throw new Error("Use a path beginning with /api/.");let o=new URL(t,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=h.object({error:h.object({code:h.string(),message:h.string(),details:h.unknown().optional()})}).parse(await n.json())}catch{throw new Sa("http_error",n.status,"Foundation returned HTTP "+n.status+".",void 0,this.identity.origin)}throw new Sa(i.error.code,n.status,i.error.message,i.error.details,this.identity.origin)}return n}async json(t,r={},o){let n=await this.response(t,r),i=n.status===204?null:await n.json();if(!o)return i;let s=o.safeParse(i);if(!s.success)throw new iu(this.identity.origin,t,s.error);return s.data}async session(){return this.json("/api/session",{},vy)}};import{chmod as Rte,lstat as Ote,mkdir as Nte,open as W$,readFile as lj,rename as Dte,rm as zte}from"node:fs/promises";import{dirname as Ute,join as q$,resolve as jte}from"node:path";import{homedir as Mte}from"node:os";import{randomUUID as Lte}from"node:crypto";var J$=h.object({origin:h.url(),principalId:h.uuid(),token:h.string().min(20),keys:of.nullable()}),dj=h.object({current:h.uuid(),identities:h.array(J$).min(1)}).strict().refine(e=>e.identities.some(t=>t.principalId===e.current),"The current identity is missing.");function ii(){return q$(process.env.XDG_CONFIG_HOME||q$(Mte(),".config"),"foundation","identity.json")}function su(e=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let t;try{t=new URL(e)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return t.origin}async function Z$(){try{let e=ii(),t=await Ote(e);if(!t.isFile()||t.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&t.mode&63&&await Rte(e,384),dj.parse(JSON.parse(await lj(e,"utf8")))}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function fj(){let e=await Z$();return(e?.identities??[]).map(t=>({...t,current:t.principalId===e.current}))}async function pj(e){let t=await Z$();if(!t?.identities.some(r=>r.principalId===e))throw new Error("No saved identity has principal "+e+". Run foundation identity list.");await si(ii(),JSON.stringify({...t,current:e},null,2)+`
|
|
123
123
|
`,!0)}async function mj(e,t){let r=process.env.FOUNDATION_TOKEN,o=t||(r?void 0:process.env.FOUNDATION_PRINCIPAL_ID),n=await Z$(),i;if(n){if(i=n.identities.find(a=>a.principalId===(o??n.current)),o&&!i&&!r)throw new Error("No saved identity has principal "+o+". Run foundation identity list.")}else if(o&&!r)throw new Error("Run foundation login to sign in on this machine.");let s=su(e||process.env.FOUNDATION_ORIGIN||i?.origin);if(r){if(e&&process.env.FOUNDATION_ORIGIN&&s!==su(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let a=process.env.FOUNDATION_PRINCIPAL_ID,c=process.env.FOUNDATION_PRIVATE_KEYS;if(!a)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return J$.parse({origin:s,principalId:a,token:r,keys:c?JSON.parse(Buffer.from(c,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!i)throw new Error("Run foundation login to sign in on this machine.");if(s!==su(i.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...i,origin:s}}async function G$(e){let t=ii(),r;try{r=dj.parse(JSON.parse(await lj(t,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=J$.parse(e),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await si(t,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
124
124
|
`,!!r)}async function uj(e){if(process.platform==="win32")return;let t=await W$(e,"r");try{await t.sync()}finally{await t.close()}}async function si(e,t,r){let o=jte(e),n=Ute(o);if(await Nte(n,{recursive:!0,mode:448}),!r){let s=await W$(o,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await uj(n);return}let i=q$(n,".foundation-"+Lte());try{let s=await W$(i,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await Dte(i,o),await uj(n)}finally{await zte(i,{force:!0})}}import{spawn as Fte}from"node:child_process";import{chmod as Vte,mkdtemp as Bte,rm as Hte,writeFile as Kte}from"node:fs/promises";import{tmpdir as Wte}from"node:os";import{join as hj}from"node:path";import{StringDecoder as qte}from"node:string_decoder";function Jte(e){return[...new Set(e.filter(Boolean).flatMap(t=>[t,encodeURIComponent(t),JSON.stringify(t).slice(1,-1),Buffer.from(t).toString("base64"),Buffer.from(t).toString("base64url")]))].sort((t,r)=>r.length-t.length)}var _y=class{constructor(t,r){this.secrets=t;this.output=r;this.max=Math.max(1,...t.map(o=>o.length))}secrets;output;pending="";decoder=new qte("utf8");max;write(t){this.pending+=this.decoder.write(t),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(t){let r=t?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};function Zte(e){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...e}}async function gj(e,t){if(!t.length)throw new Error("Put the command after --.");let r=await Bte(hj(Wte(),"foundation-"));await Vte(r,448);try{let o=Zte(e.environment),n=[...e.sensitive];for(let[i,s]of Object.entries(e.files)){let a=Buffer.from(s,"base64"),c=hj(r,i);await Kte(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=Fte(t[0],t.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=Jte(n),u=new _y(c,m=>process.stdout.write(m)),l=new _y(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,g)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(m??(g==="SIGINT"?130:g==="SIGTERM"?143:1))})})}finally{await Hte(r,{recursive:!0,force:!0})}}import{dirname as kye,join as a9}from"node:path";var wj=h.object({ownerId:$,name:ce,resourceId:$.optional(),version:h.number().int().positive().optional()}).strict(),vj=wj.extend({value:h.literal("").optional()}),X$=wj.extend({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}),tIe=h.object({ownerId:$,connectionId:$,version:h.number().int().positive(),users:h.array($).max(32)}).strict(),au=h.object({ownerId:$,methodId:h.string().min(1).max(200),connectionId:$.optional(),name:ce.optional(),appId:$.optional(),redirectUri:h.url().optional(),users:h.array($).max(32).optional(),scopes:h.array(h.string().min(1).max(1e3)).max(200).optional(),clientId:h.string().max(1e3).optional(),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}).strict(),rIe=h.object({name:eo.shape.name,title:wy,keyholder:h.boolean(),configure:h.array(h.string()),input:It}).strict(),bj=864e5,Sj=h.object({kind:h.literal("connection"),id:$}).strict(),_j=h.enum(["stopped","in_progress","succeeded","failed","uncertain","cancelled"]),dr=h.object({id:$,name:eo.shape.name,title:wy,input:It,keyholder:h.boolean(),configure:h.array(h.string()),ownerId:$.nullable(),actor:ru.pick({id:!0,name:!0}),request:h.object({id:$,position:h.number().int().nonnegative()}).strict().nullable(),state:_j,result:ba.nullable(),error:h.object({code:h.string(),message:h.string()}).strict().nullable(),continuation:Sj.nullable(),canPerform:h.boolean(),canCancel:h.boolean(),url:h.url(),createdAt:Re,updatedAt:Re,expiresAt:Re.nullable()}).strict(),nIe=eo.extend({id:$.optional(),proof:ba.optional(),continuation:Sj.optional()}).strict(),oIe=h.object({proof:ba.optional()}).strict(),Gte=B$.extend({title:wy,keyholder:h.boolean(),configure:h.array(h.string())}),yj=ru.pick({id:!0,name:!0}),Xte=h.enum(["pending","approved","declined","withdrawn","expired"]),wn=h.object({id:$,from:yj,to:yj.nullable(),message:h.string(),operations:h.array(Gte),proposal:oj.nullable(),state:Xte,createdAt:Re,expiresAt:Re,answeredAt:Re.nullable(),performed:h.array(h.object({position:h.number().int().nonnegative(),id:$,state:_j}).strict()),url:h.url(),code:h.string().optional(),returnUrl:h.url().nullable(),refreshUrl:h.url().nullable(),canAnswer:h.boolean(),canWithdraw:h.boolean()}).strict(),xj=h.object({id:$.optional(),to:$.optional(),message:h.string().max(1e3).default(""),operations:h.array(B$).min(1).max(8),expiresInMinutes:h.number().int().min(1).max(1440).default(30)}).strict(),iIe=h.object({values:h.array(h.record(h.string(),ba)).max(8).default([]),configuration:h.array(It).max(8).default([]),code:h.string().max(20).optional()}).strict();function Ue(e){switch(e.kind){case"oauth":let t=e.config.application;return{family:"oauth",application:t,requiresApp:t==="required",browserAuthorization:e.config.grantType!=="client_credentials",fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"ovh":{let r=e.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,fields:e.config.fields,outputs:Object.keys(e.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function Wi(e){let{id:t,builtin:r,availability:o,registration:n,defaultName:i,...s}=e;return s}function to(e,t){return[...new Set([...e.required??[],...t??e.default])]}function qi(e){return Ue(e).requiresApp}function Ej(e){return e.kind==="approval"?"unavailable":!Ue(e).browserAuthorization||e.kind==="ovh"||e.kind!=="oauth"?"available":e.config.browserTokenExchange??"unknown"}var ct=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function C(e,t,r,o){throw new ct(e,t,r,o)}var Yte=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountVerified","scopes","scopesStatus","outputs","state","methodKind"]),Ij=It.refine(e=>Object.keys(e).every(t=>!Yte.has(t)),"Keep method-specific facts separate from common facts."),_a=h.object({accountId:h.string().max(2e3).nullable(),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),authorization:Ij,details:Ij}).strict();function Y$(e){if(e.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let t="requestedScopes"in e?e.requestedScopes:void 0;return _a.parse({accountId:e.oauth?.account??"",accountVerified:e.oauth?.accountVerified??!1,scopes:t??e.oauth?.scopes??[],scopesStatus:t?"requested":e.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function cu(e){if(e.method.kind!=="token"&&e.method.kind!=="approval"||!e.fields)throw new Error("Use input credential material.");return"facts"in e&&e.facts?_a.parse(e.facts):_a.parse({accountId:null,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function Q$(e){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let t="requestedScopes"in e?e.requestedScopes:void 0;return _a.parse({accountId:null,accountVerified:!1,scopes:t??[],scopesStatus:t?"requested":"unknown",authorization:{},details:{}})}function e0(e){if(e.method.kind!=="aws"||!e.aws)throw new Error("Use AWS connection material.");return _a.parse({accountId:e.aws.identity?eu(e.aws.identity.arn):null,accountVerified:!!e.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:W4(e.aws)},details:{aws:q4(e.aws)}})}var Qte={oauth:Y$,token:cu,aws:e0,ovh:Q$,approval:cu};function Aj(e){return Qte[e.method.kind](e)}var fM=Ve(Jj(),1);var li=class extends Error{template;position;hint;constructor(e,t,r,o){super(`${o} (at position ${t}): ${r}`),this.template=e,this.position=t,this.hint=r,this.name="TemplateParseError"}},Ere=class extends li{constructor(e,t){super(e,t,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},Ire=class extends li{constructor(e,t){super(e,t,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},Are=class extends li{constructor(e,t){super(e,t,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},kre=class extends li{char;constructor(e,t,r){super(e,t,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},$re=class extends li{constructor(e,t){super(e,t,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},Tre=class extends li{operator;constructor(e,t,r){super(e,t,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},Pre=class extends li{operator;constructor(e,t,r){super(e,t,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},Oy=class extends li{varSpec;constructor(e,t,r,o,n){super(e,t,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},u0=class extends Oy{constructor(e,t){super(e,t,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},Cre=class extends Oy{offendingChar;constructor(e,t,r,o){super(e,t,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},Rre=class extends Oy{prefix;constructor(e,t,r,o){super(e,t,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},Zj=class extends Oy{constructor(e,t){super(e,t,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},Ore=class extends li{char;constructor(e,t,r){super(e,t,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},Nre=class extends Error{variableName;hint;constructor(e,t,r){super(`${r} for '${e}': ${t}`),this.variableName=e,this.hint=t,this.name="TemplateExpansionError"}},Dre=class extends Nre{prefix;valueType;constructor(e,t,r){super(e,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${t}' is not applicable to ${r} values`),this.prefix=t,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},zre=["","+",".","/",";","?","&","#"],rM={"":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!1},"+":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!0},".":{first:".",sep:".",named:!1,ifEmpty:"",allowReserved:!1},"/":{first:"/",sep:"/",named:!1,ifEmpty:"",allowReserved:!1},";":{first:";",sep:";",named:!0,ifEmpty:"",allowReserved:!1},"?":{first:"?",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"&":{first:"&",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"#":{first:"#",sep:",",named:!1,ifEmpty:"",allowReserved:!0}},Ure=new TextEncoder,Gj="0123456789ABCDEF",Xj=e=>Gi(Lt(48,57),Lt(65,70),Lt(97,102))(e.charCodeAt(0)),lf=(e,t)=>e[t]==="%"&&t+2<e.length&&Xj(e[t+1])&&Xj(e[t+2]);function l0(e,t){let r=e[t];return r==null?0:Gi(nM,oM,Ea("_"))(r)?1:lf(e,t)?3:0}function jre(e,t){if(lf(e,t))return 3;let{char:r,size:o}=df(e,t);return Lre(r)?o:0}function df(e,t){let r=e.codePointAt(t);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:e.slice(t,t+o),size:o}}var m0=e=>t=>{let r="";for(let o=0;o<t.length;){if(e&&lf(t,o)){r+=t.slice(o,o+3),o+=3;continue}let{char:n,size:i}=df(t,o);r+=Gi(iM,s=>e&&Mre(s))(n)?n:sM(n),o+=i}return r};function du(e){let t="";for(let r=0;r<e.length;){if(lf(e,r)){t+=e.slice(r,r+3),r+=3;continue}let{char:o,size:n}=df(e,r);t+=iM(o)?o:sM(o),r+=n}return t}function cf(e,t){let r="",o=0;for(let n=0;n<e.length&&o<t;o++){if(lf(e,n)){r+=e.slice(n,n+3),n+=3;continue}let{char:i,size:s}=df(e,n);r+=i,n+=s}return r}var nM=e=>Gi(Lt(65,90),Lt(97,122))(e.charCodeAt(0)),oM=e=>Lt(48,57)(e.charCodeAt(0)),iM=e=>Gi(nM,oM,t=>"-._~".includes(t))(e),Mre=e=>":/?#[]@!$&'()*+,;=".includes(e),Lre=e=>Fre(e.codePointAt(0)),Fre=e=>e!=null&&Gi(Ea(33),Lt(35,36),Ea(38),Lt(40,59),Ea(61),Lt(63,91),Ea(93),Ea(95),Lt(97,122),Ea(126),Vre,Bre)(e);function Vre(e){if(e<65536)return Gi(Lt(160,55295),Lt(63744,64975),Lt(65008,65519))(e);if(e>983037)return!1;let t=e%65536;return t<=65533&&(e<917504||t>=4096)}var Bre=e=>Gi(Lt(57344,63743),Lt(983040,1048573),Lt(1048576,1114109))(e),sM=e=>Array.from(Ure.encode(e)).map(t=>`%${Gj[t>>4]}${Gj[t&15]}`).join(""),Lt=(e,t)=>r=>e<=r&&r<=t,Ea=e=>t=>e===t,Gi=(...e)=>t=>e.some(r=>r(t));function aM(e,t,r){return e.map(o=>o.kind==="literal"?o.text:Hre(o.vars,o.operator,t,r)).join("")}function Hre(e,t,r,o){let n=rM[t],i=e.flatMap(s=>Kre(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function Kre(e,t,r,o){if(t==null)return[];if(Qre(t)){let n=Zre(t,r.allowReserved);return n.length<1?[]:Yj(e,"list",o)?qre(e,n,r):[]}if(Yre(t)){let n=Gre(t,r.allowReserved);return n.length<1?[]:Yj(e,"associative",o)?Jre(e,n,r):[]}return Wre(e,t,r)}function Wre(e,t,r){let o=String(t),n=e.prefix==null?o:cf(o,e.prefix),i=m0(r.allowReserved)(n);return r.named?[uf(du(e.name),i,r)]:[i]}function qre(e,t,r){let o=du(e.name);if(e.explode)return r.named?t.map(i=>uf(o,i,r)):[...t];let n=t.join(",");return r.named?[uf(o,n,r)]:[n]}function Jre(e,t,r){if(e.explode)return t.map(([n,i])=>uf(n,i,r));let o=t.flat(1).join(",");return r.named?[uf(du(e.name),o,r)]:[o]}var uf=(e,t,r)=>t===""?`${e}${r.ifEmpty}`:`${e}=${t}`,Zre=(e,t)=>e.filter(r=>r!=null).map(String).map(m0(t)),Gre=(e,t)=>Object.entries(e).map(([r,o])=>[r,Xre(o)]).filter(([,r])=>r!=null).map(r=>r.map(m0(t)));function Xre(e){if(e==null)return null;if(!Array.isArray(e))return String(e);let t=e.filter(r=>r!=null).map(String);return t.length<1?null:t.join(",")}var Yre=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qre=e=>Array.isArray(e);function Yj(e,t,{report:r,strict:o}){if(e.prefix==null)return!0;let n=new Dre(e.name,e.prefix,t);if(r(n),o)throw n;return!1}function ene(e,t,r){return d0(e,t,r,0,0,{})}function d0(e,t,r,o,n,i){if(o>=e.length){if(n!==t.length)return null;let a=kne(i);return aM(e,a,r)===t?a:null}let s=e[o];if(s.kind==="literal")return t.startsWith(s.text,n)?d0(e,t,r,o+1,n+s.text.length,i):null;for(let a of tne(e,t,o,n)){let c=t.slice(n,a);for(let u of nne(s.vars,s.operator,c)){let l=h0(i,u);if(l==null)continue;let d=d0(e,t,r,o+1,a,l);if(d!=null)return d}}return null}function*tne(e,t,r,o){let n=e.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*rne(t.length,o);return}for(let i=t.indexOf(n.text,o);i>=0;i=t.indexOf(n.text,i+1))yield i}function*rne(e,t){for(let r=e;r>=t;r--)yield r}function*nne(e,t,r){if(r===""){yield*one(e,t);return}let o=rM[t];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?pne(e,o,n):ine(e,o,n)}var one=(e,t)=>(t===""||t==="+")&&e.length===1?[Zi(e[0],"")]:[{}],ine=(e,t,r)=>f0(e,t,g0(r,t.sep),0,0);function*f0(e,t,r,o,n){if(o>=e.length){n>=r.length&&(yield{});return}let i=e[o];for(let s of sne(i,t,r,n))for(let a of f0(e,t,r,o+1,s.index)){let c=h0(s.bindings,a);c!=null&&(yield c)}yield*f0(e,t,r,o+1,n)}function*sne(e,t,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of ane(e,t,s))yield{bindings:a,index:o+i}}}function*ane(e,t,r){let o=cM(e,t,r.join(t.sep));if(e.prefix!=null){yield*o;return}e.explode&&r.length>0&&(yield*cne(e,t,r)),yield*o}function*cne(e,t,r){let o=uM(r,t.allowReserved);if(o==null)return;let n=une(r,t);n!=null&&(yield Zi(e,n)),yield Zi(e,o)}var une=(e,t)=>lne(e.join(t.sep),t);function lne(e,t){let r=[];for(let o=0;o<e.length;){let n=e.indexOf("=",o);if(n<0)return null;let i=n+1,s=dne(e,i,t.sep),a=ui(e.slice(o,n),t.allowReserved),c=ui(e.slice(i,s),t.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+t.sep.length}return r.length<1?null:Object.fromEntries(r)}function dne(e,t,r){for(let o=t;o<e.length;o++)if(fne(e,o,r))return o;return e.length}var fne=(e,t,r)=>{if(!e.startsWith(r,t))return!1;let o=t+r.length;for(let n=o;n<e.length;n++){if(e[n]==="=")return n>o;if(e.startsWith(r,n))return!1}return!1};function*cM(e,t,r){let o=ui(r,t.allowReserved);if(o==null)return;let n=Zi(e,o);if(e.prefix!=null){yield n;return}let i=g0(r,",");if(i.length<2){yield n;return}let s=uM(i,t.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?_ne(i,t.allowReserved):null;a!=null&&(yield Zi(e,a)),yield Zi(e,s),yield n}var pne=(e,t,r)=>p0(e,t,g0(r,t.sep).map(Sne),0,0);function*p0(e,t,r,o,n){if(o>=e.length){n>=r.length&&(yield{});return}let i=e[o];for(let s of mne(i,t,r,n,e))for(let a of p0(e,t,r,o+1,s.index)){let c=h0(s.bindings,a);c!=null&&(yield c)}yield*p0(e,t,r,o+1,n)}function*mne(e,t,r,o,n){if(!(o>=r.length)){if(e.explode&&e.prefix==null){yield*gne(e,t,r,o,n);return}yield*hne(e,t,r,o)}}function*hne(e,t,r,o){let n=r[o];if(n.name===du(e.name))for(let i of cM(e,t,n.value))yield{bindings:i,index:o+1}}function*gne(e,t,r,o,n){yield*yne(e,t,r,o),yield*vne(e,t,r,o,n)}function*yne(e,t,r,o){let n=[...wne(du(e.name),t,r,o)];n.length>0&&(yield{bindings:Zi(e,n),index:o+n.length})}function*wne(e,t,r,o){for(let n=o;n<r.length&&r[n].name===e;n++){let i=ui(r[n].value,t.allowReserved);if(i==null)return;yield i}}function*vne(e,t,r,o,n){let i=[...bne(t,r,o,new Set(n.map(s=>du(s.name))))];i.length>0&&(yield{bindings:Zi(e,Object.fromEntries(i)),index:o+i.length})}function*bne(e,t,r,o){for(let n=r;n<t.length;n++){let i=t[n];if(n>r&&o.has(i.name))return;let s=ui(i.name,e.allowReserved),a=ui(i.value,e.allowReserved);if(s==null||a==null)return;yield[s,a]}}function Sne(e){let t=e.indexOf("=");return t<0?{name:e,value:""}:{name:e.slice(0,t),value:e.slice(t+1)}}function _ne(e,t){let r=[];for(let o=0;o<e.length;o+=2){let n=ui(e[o],t),i=ui(e[o+1],t);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function uM(e,t){let r=[];for(let o of e){let n=ui(o,t);if(n==null)return null;r.push(n)}return r}function ui(e,t){if(t)return e;try{return decodeURIComponent(e)}catch{return null}}var Zi=({name:e,prefix:t},r)=>({[e]:{value:r,prefix:t}});function h0(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let i=r[o];if(i==null){r[o]=n;continue}let s=xne(i,n);if(s==null)return null;r[o]=s}return r}var xne=(e,t)=>Ry(e)||Ry(t)?Ene(e,t):Ine(e.value,t.value)?e:null;function Ene(e,t){let r=Qj(e.value),o=Qj(t.value);if(r==null||o==null)return null;let n=Ry(e),i=Ry(t);if(!n&&!i)return null;if(n&&!i)return cf(o,e.prefix)===r?t:null;if(!n&&i)return cf(r,t.prefix)===o?e:null;let s=e.prefix,a=t.prefix;return s<=a?cf(o,s)===r?t:null:cf(r,a)===o?e:null}var Ry=e=>e.prefix!=null,Qj=e=>typeof e=="string"?e:null;function Ine(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,o)=>r===t[o]):eM(e)?eM(t)&&Ane(Object.entries(e),Object.entries(t)):e===t}var Ane=(e,t)=>e.length===t.length&&e.every(([r,o],n)=>{let[i,s]=t[n];return r===i&&o===s}),eM=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kne=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value])),g0=(e,t)=>t===""?[e]:e.split(t),$ne=["=",",","!","@","|"];function Tne(e,t,r){let o=a=>{throw a};if(e.length<1)return o(new $re(t,r));let n=e[0];if(One(n))return o(new Tre(t,r+1,n));if(!tM(n)&&l0(e,0)<1)return o(new Pre(t,r+1,n));let i=tM(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:Pne(e,t,r+1,s)}}function Pne(e,t,r,o){if(o>=e.length)throw new u0(t,r+o);let n=[];for(let i=o;i<e.length;){if(e[i]===",")throw i===e.length-1?new Zj(t,r+i):new u0(t,r+i);let s=i,a=Cne(e,i);if(a===s)throw new u0(t,r+i);let c=e.slice(s,a);i=a;let u=Rne(e,t,r,i,c);if(i=u.index,i<e.length&&e[i]!==",")throw u.used?new Ore(t,r+i,e[i]):new Cre(t,r+i,c,e[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<e.length&&(i++,i>=e.length))throw new Zj(t,r+i-1)}return n}function Cne(e,t){let r=t,o=!0;for(;r<e.length;){let n=l0(e,r);if(n>0){r+=n,o=!1;continue}if(e[r]!=="."||o||l0(e,r+1)<1)break;r++,o=!0}return r}function Rne(e,t,r,o,n){if(e[o]==="*")return{explode:!0,index:o+1,used:!0};if(e[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<e.length&&Nne(e[s]);)s++;let a=e.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new Rre(t,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function tM(e){return zre.includes(e)&&e!==""}function One(e){return $ne.includes(e)}function Nne(e){let t=e.charCodeAt(0);return t>=48&&t<=57}function Dne(e,t){let{report:r}=t,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<e.length;){let s=e[i];if(s==="{"){let l=e.indexOf("}",i+1);if(l<0){r(new Ere(e,i)),n(e.slice(i));break}let d=e.indexOf("{",i+1);if(d>=0&&d<l){r(new Are(e,d)),n(e.slice(i,l+1)),i=l+1;continue}let p=e.slice(i+1,l);try{o.push(Tne(p,e,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(e.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new Ire(e,i)),n(s),i++;continue}let a=jre(e,i);if(a>0){n(e.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=df(e,i);r(new kre(e,i,c)),n(c),i+=u}return o}var lM=class dM{uriTemplate;options;#e;#t;constructor(t,r={}){this.uriTemplate=t,this.options=r,this.#t=Lne(r),this.#e=zne(Dne(t,this.#t)),Object.freeze(this)}static parse(t,r={}){return new dM(t,r)}get tokens(){return this.#e}expand=t=>aM(this.#e,t,this.#t);match=t=>ene(this.#e,t,this.#t);toString=()=>this.uriTemplate},zne=e=>Object.freeze(e.map(Une)),Une=e=>e.kind==="literal"?Object.freeze({kind:"literal",text:e.text}):Object.freeze({kind:"expression",operator:e.operator,vars:Object.freeze(e.vars.map(jne))}),jne=e=>Object.freeze({name:e.name,explode:e.explode,...e.prefix==null?{}:{prefix:e.prefix}}),Mne=()=>{},Lne=({strict:e,report:t})=>(t??=Mne,e??=!0,t=e?Fne(t):t,{strict:e,report:t}),Fne=e=>t=>{throw e(t),t};function Vne(e){if(e==="")return[];if(!e.startsWith("/")||/~(?![01])/u.test(e))throw new Error("Invalid JSON pointer.");let t=e.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(t.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return t}function vn(e,t){for(let r of Vne(t)){if(e===null||typeof e!="object"||!Object.hasOwn(e,r))return;e=e[r]}return e}function Xi(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);throw new Error("The selected value is not text.")}function Ny(e,t){return typeof t=="string"?Xi(vn(e,t)):t.map(r=>typeof r=="string"?r:Xi(vn(e,r.pointer))).join("")}var no=class extends Error{constructor(r,o){super(o);this.code=r}code};function Bne(e,t){return!e.when||t[e.when.field]===void 0||e.when.values.includes(t[e.when.field])}function Dy(e,t,r={}){let o=(i,s)=>{throw new no(i,s)},n={...r,...t};for(let i of e)n[i.name]===void 0&&i.defaultValue!==void 0&&(n[i.name]=i.defaultValue);for(let i of e){if(!Bne(i,n)){delete n[i.name];continue}i.required!==!1&&!n[i.name]&&o("missing_field","Complete the required service fields."),n[i.name]?.includes("\0")&&o("invalid_field","Check the service fields."),i.choices&&n[i.name]&&!i.choices.some(s=>s.value===n[i.name])&&o("invalid_field","Choose an available service setting."),i.pattern&&(i.pattern.length>200||!(0,fM.default)(i.pattern))&&o("invalid_pattern","Use a simple field validation pattern."),i.pattern&&n[i.name]&&!new RegExp(i.pattern,"u").test(n[i.name].slice(0,1e3))&&o("invalid_field","Check the service fields.")}return Object.keys(t).some(i=>!e.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function oo(e,t,r={}){let o=Dy(e,t,r),n={};for(let i of e){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(e.some(u=>u.name===a)||a in n&&n[a]!==c)throw new no("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function zy(e,t){for(let[r,o]of Object.entries(t)){let n=e.find(i=>i.name===r);if(!n)throw new no("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new no("encrypted_input_required","Supply private material directly with your encryption keys.")}return Dy(e.map(r=>({...r,required:!1,defaultValue:void 0})),t)}function io(e,t){return zy(e,Object.fromEntries(e.filter(r=>r.secret===!1&&t[r.name]).map(r=>[r.name,t[r.name]])))}function ff(e,t,r){zy(e,t);for(let[o,n]of Object.entries(t))if(n&&r[o]!==void 0&&r[o]!==n)throw new no("operation_changed","Use the service settings prepared by this operation.");return{...t,...r}}function Uy(e,t){let r;try{r=vn(JSON.parse(t[e.field]??""),e.pointer)}catch{r=void 0}if(typeof r!="string"||!r)throw new no("invalid_field","Enter the complete JSON document the service issued.");return r}var Yi=h.record(h.string().max(100),h.string().max(16384)),fr=h.object({format:h.literal(1),methodId:h.string().min(1),generation:$,clientId:h.string().max(1e3),clientSecret:h.string().max(16384).optional(),fields:Yi}).strict(),y0=h.object({accessToken:h.string().min(1).max(16384),refreshToken:h.string().min(1).max(16384).optional(),expiresAt:h.number().nullable(),refreshExpiresAt:h.number().optional(),scopes:h.array(h.string()),requestedScopes:h.array(h.string()).optional(),account:h.string(),accountVerified:h.boolean().optional(),scopesStatus:h.enum(["unknown","requested","reported"]).optional(),extra:Yi,facts:It}).strict(),pf={format:h.literal(3),methodId:h.string().min(1),method:nu,generation:$,appId:$.nullable(),appGeneration:$.nullable(),state:h.literal("reconnect").optional()},di=h.never().optional(),_r=h.union([h.object({...pf,method:py,oauth:y0.optional(),requestedScopes:h.array(h.string()).optional(),implicitApp:fr.optional(),fields:Yi.optional(),aws:di}).strict(),h.object({...pf,method:my,fields:Yi,facts:_a.optional(),oauth:di,aws:di}).strict(),h.object({...pf,method:yy,fields:Yi,oauth:di,aws:di}).strict(),h.object({...pf,method:gy,fields:Yi,requestedScopes:h.array(h.string()).optional(),oauth:di,aws:di}).strict(),h.object({...pf,method:hy,aws:uy,oauth:di,fields:di}).strict()]).superRefine((e,t)=>{if("implicitApp"in e&&e.implicitApp&&(e.method.kind!=="oauth"||e.method.config.application!=="implicit"||e.implicitApp.methodId!==e.methodId)&&t.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),e.method.kind==="oauth"&&e.fields)try{zy(e.method.config.fields,e.fields)}catch{t.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}qi(e.method)&&(!e.appId||!e.appGeneration)&&t.addIssue({code:"custom",message:"Bind the application required by this connection."}),!qi(e.method)&&e.appId!==null&&t.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!e.appId!=!!e.appGeneration&&t.addIssue({code:"custom",message:"Bind the application and its generation together."}),e.method.kind==="oauth"&&e.method.config.grantType==="client_credentials"&&!("requestedScopes"in e&&e.requestedScopes)&&!e.oauth?.requestedScopes&&t.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),eAe=h.object({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),generation:$,fields:Yi.optional()}).strict(),Hne=h.object({methodId:h.string().min(1).max(200),methodKind:F$,generation:$,appId:$.nullable(),accountId:h.string().max(2e3).nullable(),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),outputs:h.array(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:h.enum(["ready","reconnect"]),fields:Yi.optional(),aws:ly.optional()}).strict();async function fu(e,t=Aj(e)){let{outputs:r}=Ue(e.method),o=e.method.kind!=="aws"&&e.fields?io(e.method.config.fields,e.fields):{};return Hne.parse({methodId:e.methodId,methodKind:e.method.kind,generation:e.generation,appId:e.appId,accountId:t.accountVerified?t.accountId:null,accountVerified:t.accountVerified,scopes:t.scopes,scopesStatus:t.scopesStatus,outputs:r,state:e.state??"ready",...Object.keys(o).length?{fields:o}:{},...t.details})}var pM=h.object({account:h.string().max(2e3)}).strict();function mf(e){return{account:e.method.kind==="token"&&e.method.config.account&&e.fields?Uy(e.method.config.account,e.fields):""}}var tAe=h.array(h.object({name:h.string(),label:h.string(),value:h.string()}).strict());function hf(e){let{methodId:t,method:r,...o}=e;return It.parse(o)}var pu=e=>at(Be(hf(e)));function w0(e,t,r){let o=e&&typeof e=="object"&&!("methodId"in e)&&!("method"in e)?_r.safeParse({...e,methodId:t,method:r}):null;return o?.success||C(409,"reconnect_required","Reconnect this service with the current connection format."),o.data}var jy=(e,t,r)=>w0(JSON.parse(lr(e)),t.methodId,r);var Kne=1e6,mM={revision:h.number().int().positive(),updatedAt:Re,metadata:It,sealed:Qn},fi=h.object(mM).strict(),hM=h.object(mM);async function gf(e,t,r,o){if(e.byteLength>Kne)throw new Error("The content exceeds its storage limit.");let n=await by(e,await Promise.all(t.map(async i=>({id:await Sr(i.publicKey),publicKey:i.publicKey}))));return fi.parse({revision:r,updatedAt:new Date().toISOString(),metadata:o,sealed:n})}async function My(e,t){let r=await Sr(t);return e.sealed.recipients.some(o=>o.header.kid===r)}async function gM(e,t,r){return Ki(e.sealed,t,await Sr(r))}var Ly=["variable","connection","app"],yM=e=>Ly.includes(e);var yf=h.number().int().positive(),hAe=h.object({to:$,version:yf,content:fi.optional()}).strict(),v0=h.object({id:$,name:ce,kind:h.enum(Ly),ownerId:$,content:fi,labels:pM.optional(),version:yf.optional()}).strict(),wM=h.object({kind:h.enum(Ly),content:hM,version:yf}),vM=h.object({id:$}),gAe=h.record($,h.object({version:yf,content:fi}).strict()),bM=h.object({id:$,name:ce,version:yf,recipients:h.array(tu)}).strict(),mu=h.object({id:$,resource_id:$,renewer_id:$,expected_revision:h.number().int().positive(),state:h.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:h.string().regex(/^\d+$/),result:fi.nullable()}),yAe=h.object({id:$,resourceId:$,expectedRevision:h.number().int().positive()}).strict(),Wne=h.object({fence:h.string().regex(/^\d+$/)}).strict(),wAe=Wne.extend({content:fi}).strict(),vAe=h.object({id:$,operationId:$,stateDigest:cj,expiresAt:Re}).strict(),b0=h.object({id:$,operationId:$,context:h.string(),sealed:Qn.nullable(),expiresAt:Re,receivedAt:Re.nullable()}).strict(),SM=(e,t)=>"oauth-callback:"+e+":"+t;var hu=class extends Error{constructor(r,o){super(o);this.code=r}code},_M=(e,...t)=>!!e&&typeof e=="object"&&("code"in e&&t.includes(String(e.code))||"status"in e&&t.includes(Number(e.status)));var Fy=class{constructor(t,r,o,n){this.api=t;this.origin=r;this.principalId=o;this.keys=n}api;origin;principalId;keys;async latest(t){let r=await this.api.json("/api/resources/"+$.parse(t)+"/custody",{},wM);return{...r,opens:await My(r.content,this.keys.publicKey)}}async read(t){let{opens:r,...o}=await this.latest(t);if(!r)throw new hu("not_sealed_for_key","This item is not sealed for the current key of this identity yet. Ask someone who can open it to seal it again, or enter its value again.");return o}open(t){return gM(t,this.keys.privateKey,this.keys.publicKey)}async reveal(t){return this.open((await this.read(t)).content)}async connection(t){let{content:r}=await this.read(t),o=await this.open(r),n=Wi(await this.api.json("/api/connections/"+$.parse(t)+"/method",{},oi));return jy(o,r.metadata,n)}async recipients(t,r){return(await this.api.json(r?"/api/resources/"+$.parse(t.id)+"/recipients":"/api/principals/"+$.parse(t.ownerId)+"/recipients",{},pt(tu))).items}async seal(t,r,o,n){let i=(await this.api.json("/api/resources/"+$.parse(t)+"/recipients",{},pt(tu))).items;return gf(r,i,o,n)}async save(t,r,o,n={}){let{previous:i}=n,s=n.metadata??(t.kind==="variable"?{bytes:o.byteLength}:{});for(let a=1;;a++){let c=await gf(o,await this.recipients(t,!!i),(i?.content.revision??0)+1,s),u={id:t.id,name:r,kind:t.kind,ownerId:t.ownerId,content:c,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}};try{return n.commit?await n.commit(u):await this.api.json("/api/resources/"+$.parse(t.id)+"/custody",{method:"PUT",body:u},ze)}catch(l){if(a<3&&_M(l,"recipients_changed"))continue;throw l}}}async transferProtected(t,r){let o="/api/resources/"+t.id+"/transfer",n=await this.read(t.id);if(n.version!==t.version)throw new hu("changed","This item changed. Reload it before transferring it.");let i=await this.open(n.content);for(let s=1;;s++){let a=(await this.api.json(o+"-recipients?to="+encodeURIComponent(r),{},pt(tu))).items,c=await gf(i,a,n.content.revision+1,n.content.metadata);try{return await this.api.json(o,{method:"POST",body:{to:r,content:c,version:n.version}},h.union([ze,wn]))}catch(u){if(s<3&&_M(u,"recipients_changed"))continue;throw u}}}async sharing(t){let r=typeof t=="string"?(await this.api.json(t,{},pt(bM))).items:t,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version)throw new hu("changed","This item changed. Reload it before changing who opens it.");o[n.id]={version:n.version,content:await gf(await this.open(i.content),n.recipients,i.content.revision+1,i.content.metadata)}}return o}async pendingProtection(){return(await this.api.json("/api/principals/"+this.principalId+"/reprotection",{},pt(vM))).items}async reprotect(t){let r=await this.read(t),o=await this.api.json("/api/resources/"+$.parse(t),{},ze);if(!yM(o.kind))throw new hu("wrong_kind","Only sealed items are sealed again.");return this.save({id:t,ownerId:o.ownerId,kind:o.kind},o.name,await this.open(r.content),{metadata:r.content.metadata,previous:r})}async reprotectPending(t){let r=[],o=[],n=await this.pendingProtection(),i=0;t?.({completed:i,total:n.length});for(let s of n){try{await this.reprotect(s.id),r.push(s.id)}catch(a){o.push({id:s.id,code:a&&typeof a=="object"&&"code"in a&&typeof a.code=="string"?a.code:"failure"})}t?.({completed:++i,total:n.length})}return{done:r,failed:o}}async sourceContents(t){let r=new Map;for(let o of new Set(t))r.set(o,await this.read(o));for(let o of[...r.values()]){let n=o.content.metadata.appId;typeof n=="string"&&!r.has(n)&&r.set(n,await this.read(n))}return r}};import{lstat as qne,mkdir as xM,readFile as Jne,readdir as EM,rm as Zne}from"node:fs/promises";import{join as gu}from"node:path";var S0=h.string().regex(/^(refresh|checkpoint)_[A-Za-z0-9_-]{1,100}$/),IM=e=>S0.safeParse(e).success,Vy=class{constructor(t,r,o){this.directory=t;this.origin=r;this.device=o}directory;origin;device;indexing;context(t){return Be({purpose:"executor-journal",origin:this.origin,id:S0.parse(t)})}keyId(){return Sr(this.device.publicKey)}async read(t){let r=this.context(t),o=gu(this.directory,t+".json");try{let n=await qne(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The journal must use private regular files.");let i=h.string().max(32e6).parse(JSON.parse(await Jne(o,"utf8"))),s=this.device.privateKey instanceof CryptoKey?this.device.privateKey:await ya(this.device.privateKey,"ECDH-ES+A256KW"),a=await Jd(i,s,{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(a.protectedHeader.kid!==await this.keyId()||a.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let c=JSON.parse(lr(a.plaintext));if(c.context!==r)throw new Error("The journal entry belongs to another operation.");return c.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async writeEntry(t,r){let o=this.context(t),n=at(Be({context:o,value:r}));if(n.byteLength>2e7)throw new Error("The journal entry is too large.");let i=await new Yc(n).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:await this.keyId(),ctx:o}).encrypt(await ya(this.device.publicKey,"ECDH-ES+A256KW"));await xM(this.directory,{recursive:!0,mode:448}),await si(gu(this.directory,t+".json"),Be(i),!0)}delivery(t){return t.startsWith("refresh_")}delivered(t){return!!t&&typeof t=="object"&&"delivered"in t&&t.delivered===!0}async markPending(t){await xM(gu(this.directory,"pending"),{recursive:!0,mode:448}),await si(gu(this.directory,"pending",S0.parse(t)),"",!0)}index(){return this.indexing??=(async()=>{let t="checkpoint_pending_index";if(!await this.read(t)){for(let r of await this.keys("")){if(!this.delivery(r))continue;let o=await this.read(r);o&&!this.delivered(o)&&await this.markPending(r)}await this.writeEntry(t,{version:1})}})()}async write(t,r){await this.index();let o=this.delivered(r);this.delivery(t)&&!o&&await this.markPending(t),await this.writeEntry(t,r),this.delivery(t)&&o&&await Zne(gu(this.directory,"pending",t),{force:!0})}async pending(t){await this.index();let r;try{r=await EM(gu(this.directory,"pending"),{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(t)&&IM(o.name)).map(o=>o.name)}async keys(t){let r;try{r=await EM(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(t)&&o.name.endsWith(".json")&&IM(o.name.slice(0,-5))).map(o=>o.name.slice(0,-5))}};var By=class{api;constructor(t){this.api={async json(r,o={},n){try{return await t.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new ct(i.status,i.code,i.message):i}}}}connections(){let t=this.api;return{method:async r=>Wi(await t.json("/api/connections/"+r+"/method",{},oi)),prepare:(r,o,n)=>t.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},mu),dispatch:(r,o)=>t.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},mu),commit:(r,o,n)=>t.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},fi),uncertain:(r,o)=>t.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>t.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},mu),refused:(r,o)=>t.json("/api/connection-operations/"+r+"/refused",{method:"POST",body:{fence:o}},mu),state:r=>t.json("/api/connections/"+r+"/operation",{},mu.nullable())}}};import{randomUUID as Sye}from"node:crypto";var Ii=Ve(gG(),1);import{randomUUID as mge}from"node:crypto";function yG(e){let t=cy.safeParse({accountId:e.Account,arn:e.Arn,principalId:e.Arn?.includes(":assumed-role/")?e.UserId?.split(":")[0]:e.UserId});return(!t.success||t.data.arn.split(":")[4]!==t.data.accountId)&&C(502,"invalid_response","The AWS account could not be verified."),t.data}function wG(e,t){return e.accountId===t.accountId&&e.principalId===t.principalId&&eu(e.arn)===eu(t.arn)}function ON(e){e&&(!Number.isFinite(e.getTime())||e.getTime()<=Date.now())&&C(409,"reconnect_required","Reconnect with current AWS credentials.")}var l_=class{async obtain(t,r,o){let n=wa.parse({authentication:t.authentication,region:t.region,...t.role?{role:t.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};ON(s?.expiration);let a=new Ii.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();ON(d.expiration),c=new Ii.STSClient({region:n.region,credentials:d});let p=r?.sourceIdentity?yG(await c.send(new Ii.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&p&&!wG(p,r.sourceIdentity)&&C(409,"account_changed","Reconnect to approve the current AWS authentication source.");let f=d,m=p;if(n.role){l=!0;let v=(await c.send(new Ii.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+mge().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!v?.AccessKeyId||!v.SecretAccessKey||!v.SessionToken||!v.Expiration)&&C(502,"invalid_response","AWS did not return credentials."),f={accessKeyId:v.AccessKeyId,secretAccessKey:v.SecretAccessKey,sessionToken:v.SessionToken,expiration:v.Expiration},ON(f.expiration),r?.identity&&(c.destroy(),c=new Ii.STSClient({region:n.region,credentials:f}),m=yG(await c.send(new Ii.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&m&&!wG(m,r.identity)&&C(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:uy.parse({...n,sourceIdentity:p,identity:m}),credentials:{AWS_ACCESS_KEY_ID:f.accessKeyId,AWS_SECRET_ACCESS_KEY:f.secretAccessKey,AWS_SESSION_TOKEN:f.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof ct)throw d;o?.aborted&&C(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&C(409,"reconnect_required","Reconnect with current AWS credentials."),l&&C(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),C(502,"aws_authentication_failed","Check the AWS credentials available on this machine.")}finally{c?.destroy(),a.destroy()}}};var d_=class{constructor(t){this.aws=t}aws;facts=e0;needsRenewal(){return!1}async outputs(t,r,o){return(await this.aws.obtain(t.aws,t.aws,o)).credentials}};var NN;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(NN="oauth4webapi/v3.8.8");function g_(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var qo="ERR_INVALID_ARG_VALUE",Ai="ERR_INVALID_ARG_TYPE";function dt(e,t,r){let o=new TypeError(e,{cause:r});return Object.assign(o,{code:t}),o}var SG=Symbol(),hge=Symbol(),gge=Symbol(),BN=Symbol();var _m=Symbol();var yge=new TextEncoder,wge=new TextDecoder;function DN(e){return typeof e=="string"?yge.encode(e):wge.decode(e)}var zN;Uint8Array.prototype.toBase64?zN=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):zN=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let o=0;o<t.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,t.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var UN;Uint8Array.fromBase64?UN=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw dt("The input to be decoded is not correctly encoded.",qo,t)}}:UN=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}catch(t){throw dt("The input to be decoded is not correctly encoded.",qo,t)}};function jN(e){return typeof e=="string"?UN(e):zN(e)}var Ll=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=Gge,Error.captureStackTrace?.(this,this.constructor)}},xm=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function ne(e,t,r){return new xm(e,{code:t,cause:r})}function f_(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function _G(e){g_(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(NN&&!t.has("user-agent")&&t.set("user-agent",NN),t.has("authorization"))throw dt('"options.headers" must not include the "authorization" header name',qo);return t}function vge(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw dt('"options.signal" must return or be an instance of AbortSignal',Ai);return t}}function Fl(e,t,r,o,n){try{if(typeof e!="number"||!Number.isFinite(e))throw dt(`${r} must be a number`,Ai,n);if(e>0)return;if(t){if(e!==0)throw dt(`${r} must be a non-negative number`,qo,n);return}throw dt(`${r} must be a positive number`,qo,n)}catch(i){throw o?ne(i.message,o,n):i}}function rt(e,t,r,o){try{if(typeof e!="string")throw dt(`${t} must be a string`,Ai,o);if(e.length===0)throw dt(`${t} must not be empty`,qo,o)}catch(n){throw r?ne(n.message,r,o):n}}function xG(e){Sge(e,"application/json")}function bge(e,...t){let r='"response" content-type must be ';if(t.length>2){let o=t.pop();r+=`${t.join(", ")}, or ${o}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return ne(r,Yge,e)}function Sge(e,t){if(Dge(e)!==t)throw bge(e,t)}async function EG(e){return rt(e,"codeVerifier"),jN(await crypto.subtle.digest("SHA-256",DN(e)))}function IG(e){let t=e?.[hge];return typeof t=="number"&&Number.isFinite(t)?t:0}function AG(e){let t=e?.[gge];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function kG(){return Math.floor(Date.now()/1e3)}function Hs(e){if(typeof e!="object"||e===null)throw dt('"as" must be an object',Ai);rt(e.issuer,'"as.issuer"')}function Ks(e){if(typeof e!="object"||e===null)throw dt('"client" must be an object',Ai);rt(e.client_id,'"client.client_id"')}function vG(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function $G(e){return rt(e,'"clientSecret"'),(t,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",e)}}function TG(e){return rt(e,'"clientSecret"'),(t,r,o,n)=>{let i=vG(r.client_id),s=vG(e),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function PG(){return(e,t,r,o)=>{r.set("client_id",t.client_id)}}var _ge=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function xge(e,t){if(t&&e.protocol!=="https:")throw ne("only requests to HTTPS are allowed",eye,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw ne("only HTTP and HTTPS requests are allowed",tye,e)}function bG(e,t,r,o){let n;if(typeof e!="string"||!(n=_ge(e)))throw ne(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?rye:nye,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return xge(n,o),n}function CG(e,t,r,o){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?bG(e.mtls_endpoint_aliases[t],t,r,o):bG(e[t],t,r,o)}var MN=class extends Error{cause;code;error;status;error_description;response;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=Zge,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},Em=class extends Error{cause;code;error;error_description;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=Xge,this.cause=r.cause,this.error=r.cause.get("error"),this.error_description=r.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},LN=class extends Error{cause;code;response;status;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=Jge,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},p_="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Ege="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Ige='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Age="("+p_+")\\s*=\\s*"+Ige,kge="("+p_+")\\s*=\\s*("+p_+")",$ge=new RegExp("^[,\\s]*("+p_+")"),Tge=new RegExp("^[,\\s]*"+Age+"[,\\s]*(.*)"),Pge=new RegExp("^[,\\s]*"+kge+"[,\\s]*(.*)"),Cge=new RegExp("^("+Ege+")(?:$|[,\\s])(.*)");function Rge(e){if(!g_(e,Response))throw dt('"response" must be an instance of Response',Ai);let t=e.headers.get("www-authenticate");if(t===null)return;let r=[],o=t;for(;o;){let n=o.match($ge),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(Tge)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(Pge)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(Cge)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function Oge(e){if(e.status>399&&e.status<500){WN(e),xG(e);try{let t=await e.clone().json();if(f_(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function RG(e,t,r){if(e.status!==t){Uge(e);let o;throw(o=await Oge(e))?(await e.body?.cancel(),new MN("server responded with an error in the response body",{cause:o,response:e})):ne(`"response" is not a conform ${r} response (unexpected HTTP status code)`,Qge,e)}}function Nge(e){if(!HN.has(e))throw dt('"options.DPoP" is not a valid DPoPHandle',qo)}function Dge(e){return e.headers.get("content-type")?.split(";")[0]}async function OG(e,t,r,o,n,i,s){return await r(e,t,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[BN]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:vge(o,s?.signal)})}async function y_(e,t,r,o,n,i){let s=CG(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[SG]!==!0);n.set("grant_type",o);let a=_G(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(Nge(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await OG(e,t,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function NG(e,t,r,o,n){Hs(e),Ks(t),rt(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),y_(e,t,r,"refresh_token",i,n)}var DG=new WeakMap,zge=new WeakMap;function zG(e){if(!e.id_token)return;let t=DG.get(e);if(!t)throw dt('"ref" was already garbage collected or did not resolve from the proper sources',qo);return t}async function Im(e,t,r,o,n,i){if(Hs(e),Ks(t),!g_(r,Response))throw dt('"response" must be an instance of Response',Ai);await RG(r,200,"Token Endpoint"),WN(r);let s=await XG(r);if(rt(s.access_token,'"response" body "access_token" property',pe,{body:s}),rt(s.token_type,'"response" body "token_type" property',pe,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;Fl(a,!0,'"response" body "expires_in" property',pe,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&rt(s.refresh_token,'"response" body "refresh_token" property',pe,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw ne('"response" body "scope" property must be a string',pe,{body:s});if(s.id_token!==void 0){rt(s.id_token,'"response" body "id_token" property',pe,{body:s});let a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(Fl(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await Bge(e,t,s.id_token,a,n);Kge(t,c),Hge(c),zge.set(r,u),DG.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new Ll("unsupported `token_type` value",{cause:{body:s}});return s}function Uge(e){let t;if(t=Rge(e))throw new LN("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function UG(e,t,r,o){return Im(e,t,r,void 0,o?.[_m],o?.recognizedTokenTypes)}function jge(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw ne('unexpected JWT "aud" (audience) claim value',Vl,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw ne('unexpected JWT "aud" (audience) claim value',Vl,{expected:e,claims:t.claims,claim:"aud"});return t}function Mge(e,t){let r=e[cye]?.(t)??e.issuer;if(t.claims.iss!==r)throw ne('unexpected JWT "iss" (issuer) claim value',Vl,{expected:r,claims:t.claims,claim:"iss"});return t}var HN=new WeakSet;function Lge(e){return HN.add(e),e}var KN=Symbol();async function jG(e,t,r,o,n,i,s){if(Hs(e),Ks(t),!HN.has(o))throw dt('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',qo);rt(n,'"redirectUri"');let a=ic(o,"code");if(!a)throw ne('no authorization code in "callbackParameters"',pe);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==KN&&(rt(i,'"codeVerifier"'),c.set("code_verifier",i)),y_(e,t,r,"authorization_code",c,s)}var MG={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Fge(e,t){for(let r of e)if(t.claims[r]===void 0)throw ne(`JWT "${r}" (${MG[r]}) claim missing`,pe,{claims:t.claims});return t}function Vge(e,t){if(typeof t.claims[e]!="string")throw ne(`unexpected JWT "${e}" (${MG[e]}) claim type`,pe,{claims:t.claims});return t}function Bge(e,t,r,o,n){return oye(r,iye.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),IG(t),AG(t),n).then(Fge.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(Mge.bind(void 0,e)).then(jge.bind(void 0,t.client_id)).then(Vge.bind(void 0,"sub"))}function LG(e,t){if(t===h_)return t;let r=t===void 0;return r&&(t=e.default_max_age),t===void 0?h_:(Fl(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function Hge(e){e.auth_time!==void 0&&Fl(e.auth_time,!0,'ID Token "auth_time" (authentication time)',pe,{claims:e})}function FG(e,t,r){if(r===h_)return;let o=kG()+IG(e),n=AG(e);if(t.auth_time+r<o-n)throw ne("too much time has elapsed since the last End-User authentication",VN,{claims:t,now:o,tolerance:n,claim:"auth_time"})}function VG(e,t){let r=t===m_?void 0:t;if(e.nonce!==r)throw ne('unexpected ID Token "nonce" claim value',Vl,{expected:r,claims:e,claim:"nonce"})}function Kge(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw ne('ID Token "aud" (audience) claim includes additional untrusted audiences',Vl,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw ne('unexpected ID Token "azp" (authorized party) claim value',Vl,{expected:e.client_id,claims:t,claim:"azp"})}}var m_=Symbol(),h_=Symbol();async function BG(e,t,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?Wge(e,t,r,o.expectedNonce,o.maxAge,o[_m],o.recognizedTokenTypes):qge(e,t,r,o?.maxAge,o?.[_m],o?.recognizedTokenTypes)}async function Wge(e,t,r,o,n,i,s){let a=[];switch(o){case void 0:o=m_;break;case m_:break;default:rt(o,'"expectedNonce" argument'),a.push("nonce")}n=LG(t,n),n!==h_&&a.push("auth_time");let c=await Im(e,t,r,a,i,s);rt(c.id_token,'"response" body "id_token" property',pe,{body:c});let u=zG(c);return FG(t,u,n),VG(u,o),c}async function qge(e,t,r,o,n,i){let s=await Im(e,t,r,void 0,n,i),a=zG(s);return a&&(FG(t,a,LG(t,o)),VG(a,m_)),s}var Jge="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Zge="OAUTH_RESPONSE_BODY_ERROR",Gge="OAUTH_UNSUPPORTED_OPERATION",Xge="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var FN="OAUTH_PARSE_ERROR",pe="OAUTH_INVALID_RESPONSE";var Yge="OAUTH_RESPONSE_IS_NOT_JSON",Qge="OAUTH_RESPONSE_IS_NOT_CONFORM",eye="OAUTH_HTTP_REQUEST_FORBIDDEN",tye="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",VN="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Vl="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var rye="OAUTH_MISSING_SERVER_METADATA",nye="OAUTH_INVALID_SERVER_METADATA";async function HG(e,t,r,o,n){return Hs(e),Ks(t),y_(e,t,r,"client_credentials",new URLSearchParams(o),n)}async function KG(e,t,r,o){return Im(e,t,r,void 0,o?.[_m],o?.recognizedTokenTypes)}function WN(e){if(e.bodyUsed)throw dt('"response" body has been used already',qo)}async function oye(e,t,r,o,n){let{0:i,1:s,length:a}=e.split(".");if(a===5)if(n!==void 0)e=await n(e),{0:i,1:s,length:a}=e.split(".");else throw new Ll("JWE decryption is not configured",{cause:e});if(a!==3)throw ne("Invalid JWT",pe,e);let c;try{c=JSON.parse(DN(jN(i)))}catch(d){throw ne("failed to parse JWT Header body as base64url encoded JSON",FN,d)}if(!f_(c))throw ne("JWT Header must be a top level object",pe,e);if(t(c),c.crit!==void 0)throw new Ll('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(DN(jN(s)))}catch(d){throw ne("failed to parse JWT Payload body as base64url encoded JSON",FN,d)}if(!f_(u))throw ne("JWT Payload must be a top level object",pe,e);let l=kG()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw ne('unexpected JWT "exp" (expiration time) claim type',pe,{claims:u});if(u.exp<=l-o)throw ne('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',VN,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw ne('unexpected JWT "iat" (issued at) claim type',pe,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw ne('unexpected JWT "iss" (issuer) claim type',pe,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw ne('unexpected JWT "nbf" (not before) claim type',pe,{claims:u});if(u.nbf>l+o)throw ne('unexpected JWT "nbf" (not before) claim value',VN,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw ne('unexpected JWT "aud" (audience) claim type',pe,{claims:u});return{header:c,claims:u,jwt:e}}function iye(e,t,r,o){if(e!==void 0){if(typeof e=="string"?o.alg!==e:!e.includes(o.alg))throw ne('unexpected JWT "alg" header parameter',pe,{header:o,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(o.alg))throw ne('unexpected JWT "alg" header parameter',pe,{header:o,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw ne('unexpected JWT "alg" header parameter',pe,{header:o,expected:r,reason:"default value"});return}throw ne('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function ic(e,t){let{0:r,length:o}=e.getAll(t);if(o>1)throw ne(`"${t}" parameter must be provided only once`,pe);return r}var sye=Symbol(),aye=Symbol();function WG(e,t,r,o){if(Hs(e),Ks(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw dt('"parameters" must be an instance of URLSearchParams, or URL',Ai);if(ic(r,"response"))throw ne('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',pe,{parameters:r});let n=ic(r,"iss"),i=ic(r,"state");if(!n&&e.authorization_response_iss_parameter_supported)throw ne('response parameter "iss" (issuer) missing',pe,{parameters:r});if(n&&n!==e.issuer)throw ne('unexpected "iss" (issuer) response parameter value',pe,{expected:e.issuer,parameters:r});switch(o){case void 0:case aye:if(i!==void 0)throw ne('unexpected "state" response parameter encountered',pe,{expected:void 0,parameters:r});break;case sye:break;default:if(rt(o,'"expectedState" argument'),i!==o)throw ne(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',pe,{expected:o,parameters:r})}if(ic(r,"error"))throw new Em("authorization response from the server is an error",{cause:r});let a=ic(r,"id_token"),c=ic(r,"token");if(a!==void 0||c!==void 0)throw new Ll("implicit and hybrid flows are not supported");return Lge(new URLSearchParams(r))}async function qG(e,t,r,o,n){Hs(e),Ks(t);let i=CG(e,"device_authorization_endpoint",t.use_mtls_endpoint_aliases,n?.[SG]!==!0),s=new URLSearchParams(o);s.set("client_id",t.client_id);let a=_G(n?.headers);return a.set("accept","application/json"),OG(e,t,r,i,s,a,n)}async function JG(e,t,r){if(Hs(e),Ks(t),!g_(r,Response))throw dt('"response" must be an instance of Response',Ai);await RG(r,200,"Device Authorization Endpoint"),WN(r);let o=await XG(r);rt(o.device_code,'"response" body "device_code" property',pe,{body:o}),rt(o.user_code,'"response" body "user_code" property',pe,{body:o}),rt(o.verification_uri,'"response" body "verification_uri" property',pe,{body:o});let n=typeof o.expires_in!="number"?parseFloat(o.expires_in):o.expires_in;return Fl(n,!0,'"response" body "expires_in" property',pe,{body:o}),o.expires_in=n,o.verification_uri_complete!==void 0&&rt(o.verification_uri_complete,'"response" body "verification_uri_complete" property',pe,{body:o}),o.interval!==void 0&&Fl(o.interval,!1,'"response" body "interval" property',pe,{body:o}),o}async function ZG(e,t,r,o,n){Hs(e),Ks(t),rt(o,'"deviceCode"');let i=new URLSearchParams(n?.additionalParameters);return i.set("device_code",o),y_(e,t,r,"urn:ietf:params:oauth:grant-type:device_code",i,n)}async function GG(e,t,r,o){return Im(e,t,r,void 0,o?.[_m],o?.recognizedTokenTypes)}async function XG(e,t=xG){let r;try{r=await e.json()}catch(o){throw t(e),ne('failed to parse "response" body as JSON',FN,o)}if(!f_(r))throw ne('"response" body must be a top level object',pe,{body:r});return r}var cye=Symbol();var Bl=Ve(QG(),1);var lye=Bl.default.IPv6.parseCIDR("2000::/3"),dye=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function b_(e){if(!Bl.default.isValid(e)||e.includes("%"))return!1;let t=Bl.default.parse(e);return dye.has(t.range())&&(!(t instanceof Bl.default.IPv6)||t.match(lye))}function Nr(e,t){let r;try{r=new URL(e)}catch{C(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===t)&&C(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||Bl.default.isValid(o)&&!b_(o))&&C(400,"private_destination","Choose a public HTTPS destination."),r}function Wn(e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.body))}catch{C(502,"invalid_response","The service returned an invalid response.")}return(!t||typeof t!="object"||Array.isArray(t))&&C(502,"invalid_response","The service returned an invalid response."),t}var v_=class{constructor(t){this.origin=t}origin;async send(t){let r=Nr(t.url,this.origin),o=t.maxBytes??1048576;t.body&&(typeof t.body=="string"?new TextEncoder().encode(t.body).length:t.body.length)>o&&C(413,"body_limit","The request body is too large.");let n;try{n=await fetch(r,{method:t.method??"GET",headers:t.headers,body:typeof t.body=="string"?t.body:t.body?new Uint8Array(t.body):void 0,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]])})}catch{t.signal?.aborted&&C(409,"cancelled","The operation was cancelled."),C(409,"browser_exchange_unavailable","Restart authorization using the CLI on this device.")}let i=n.body?.getReader(),s=[],a=0;if(i)try{for(;;){let l=await i.read();if(l.done)break;a+=l.value.length,a>o&&C(413,"body_limit","The response body is too large."),s.push(l.value)}}finally{await i.cancel()}let c=new Uint8Array(a),u=0;for(let l of s)c.set(l,u),u+=l.length;return{status:n.status,headers:Object.fromEntries(n.headers),body:c}}};var e9=Object.assign(Object.create(null),{dpop:()=>C(502,"invalid_response","The service returned an unsupported token.")}),fye={redirectUri:e=>e.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),e9,{"user access token":()=>{}})},pye={authorize(e,t){delete e.response_type,delete e.client_id,delete e.redirect_uri,e.callback_url=t,e.key_label="Foundation"},async exchange({spec:e,transport:t,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&C(400,"invalid_state","Start the connection again."),t.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},mye={tokenParameters(e){let t=e.get("redirect_uri");t!==null&&(e.set("redirect_url",t),e.delete("redirect_uri"))}};function ki(e,t){let r=t?new URL(t):void 0;return{recognizedTokenTypes:e9,...e.adapter==="github"?{normalizeToken(o){typeof o.scope=="string"&&(o.scope=o.scope.split(",").map(n=>n.trim()).join(e.scopes.separator))}}:{},...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(o){o.token_type===void 0&&(o.token_type="bearer")},...e.grantType==="client_credentials"?{clientCredentialsParameters(){return{...e.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(o){o.refresh_token===null&&delete o.refresh_token}}:{},...e.adapter==="ebay"?fye:e.adapter==="openrouter"?pye:e.adapter==="vultr"?mye:{}}}function $i(e,t){try{return Nr(new lM(e).expand(t)).href}catch{C(400,"invalid_service_url","Check the service URL and its required fields.")}}var t9=(e,t=" ")=>typeof e=="string"?[...new Set(e.split(t).filter(Boolean))].sort():[],sc=e=>{let t=typeof e=="number"||typeof e=="string"?Number(e):NaN;return(!Number.isSafeInteger(t)||t<=0||t>315576e3)&&C(502,"invalid_response","The service returned an invalid expiry."),t};var Am=h.object({deviceCode:h.string().min(1).max(16384),userCode:h.string().min(1).max(1e3),verificationUri:h.url(),verificationUriComplete:h.url().optional(),expiresAt:h.number().int().positive(),intervalSeconds:h.number().int().positive(),nextPollAt:h.number().int().positive()}).strict();var Jo=class{constructor(t){this.transport=t}transport;appValues(t,r){try{return{...oo(t.fields,r.fields,t.defaults),clientId:r.clientId}}catch(o){throw o instanceof no&&C(400,o.code,o.message),o}}async authorize(t,r,o,n,i,s){(t.grantType==="client_credentials"||t.grantType===ur||!t.authorizeUrl)&&C(400,"wrong_grant","Choose an authorization code connection method.");let a=new URL($i(t.authorizeUrl,this.appValues(t,r))),c={...t.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:ki(t).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(t.scopes.separator)),t.pkce&&(c.code_challenge=await EG(n),c.code_challenge_method="S256"),ki(t).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(t,r){let o={issuer:t.issuer??new URL($i(t.grantType==="client_credentials"||t.grantType===ur?t.tokenUrl:t.authorizeUrl,this.appValues(t,r))).origin,token_endpoint:$i(t.tokenUrl,this.appValues(t,r))};return t.issuer&&Nr(t.issuer),{server:o,client:{client_id:r.clientId}}}authentication(t,r){return r==="none"?PG():(t.clientSecret||C(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?TG(t.clientSecret):$G(t.clientSecret))}options(t){let r=t?.tokenFormat??"form";return{[BN]:async(o,{body:n,headers:i,method:s,signal:a})=>{let c=new URLSearchParams(n);t&&ki(t).tokenParameters?.(c);let u=await this.transport.send({url:o,method:s,headers:r==="json"?{...i,"content-type":"application/json"}:i,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(t){return Wn({status:t.status,headers:{},body:new Uint8Array(await t.arrayBuffer())})}checkResponse(t,r,o,n=!1){return(r>=400||o.error||t.okPointer&&vn(o,t.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&C(409,"reconnect_required","Reconnect this service to renew access."),r===429&&C(503,"service_rate_limit","The service is busy. Try again later."),C(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(t,r,o,n=!1){o.status===429&&C(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(t,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(t,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,ki(t,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=sc(u.expires_in));try{let d=await(n?UG:t.grantType==="client_credentials"?KG:t.grantType===ur?GG:BG)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:ki(t,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof ct)throw l;C(502,"invalid_response","The service did not return a valid access token.")}}token(t,r,o,n,i=!1){let s=r[ki(t).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&C(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+sc(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&C(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of t.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?t9(r.scope,t.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+sc(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(t,r,o,n,i,s,a,c){(t.grantType==="client_credentials"||t.grantType===ur)&&C(400,"wrong_grant","Choose an authorization code connection method.");let u,l=ki(t);if(l.exchange){let p=await l.exchange({spec:t,app:r,transport:this.transport,url:()=>$i(t.tokenUrl,this.appValues(t,r)),authorization:o,verifier:n});u=this.checkResponse(t,p.status,Wn(p))}else{let{server:p,client:f}=this.configuration(t,r),m;try{let g=WG(p,f,o.parameters,o.state);m=await jG(p,f,this.authentication(r,t.clientAuth),g,l.redirectUri?.(r,i)??i,t.pkce?n:KN,{...this.options(t),additionalParameters:t.tokenParams})}catch(g){throw(g instanceof xm||g instanceof Em)&&C(400,"invalid_state","Start the connection again."),g}u=await this.tokenResponse(t,r,m)}let d=this.token(t,u,s,a);return await c?.(d,u),d}async deviceAuthorization(t,r,o){(t.grantType!==ur||!t.deviceAuthorizationUrl)&&C(400,"wrong_grant","Choose a device authorization connection method.");let{server:n,client:i}=this.configuration(t,r),s={...n,device_authorization_endpoint:$i(t.deviceAuthorizationUrl,this.appValues(t,r))},a=await qG(s,i,this.authentication(r,t.clientAuth),{...t.authorizeParams,...o.length?{scope:o.join(t.scopes.separator)}:{}},this.options(t)),c=await this.json(a);[200,400].includes(a.status)&&c.error==="device_flow_disabled"&&C(409,"device_flow_disabled","Enable device authorization in the service application settings.");let u=this.checkResponse(t,a.status,c),l;try{l=await JG(s,i,Response.json(u,{status:a.status}))}catch{C(502,"invalid_response","The service did not return a valid device authorization.")}let d=Date.now(),p=sc(l.interval??5);return Am.parse({deviceCode:l.device_code,userCode:l.user_code,verificationUri:Nr(l.verification_uri).href,...l.verification_uri_complete?{verificationUriComplete:Nr(l.verification_uri_complete).href}:{},expiresAt:d+sc(l.expires_in)*1e3,intervalSeconds:p,nextPollAt:d+p*1e3})}async deviceToken(t,r,o,n){t.grantType!==ur&&C(400,"wrong_grant","Choose a device authorization connection method.");let{server:i,client:s}=this.configuration(t,r),a=await ZG(i,s,this.authentication(r,t.clientAuth),o,{...this.options(t),additionalParameters:t.tokenParams}),c=await this.json(a);return[200,400].includes(a.status)&&["authorization_pending","slow_down"].includes(String(c.error))?{kind:"pending",slowDown:c.error==="slow_down",...c.interval!==void 0?{intervalSeconds:sc(c.interval)}:{}}:([200,400].includes(a.status)&&(c.error==="access_denied"&&C(409,"device_access_denied","Device authorization was declined."),c.error==="expired_token"&&C(409,"device_code_expired","The device code expired. Start the connection again."),c.error==="device_flow_disabled"&&C(409,"device_flow_disabled","Enable device authorization in the service application settings.")),{kind:"connected",token:this.token(t,await this.tokenResponse(t,r,Response.json(c,{status:a.status})),n)})}async clientCredentials(t,r,o,n,i){t.grantType!=="client_credentials"&&C(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(t,r),c=ki(t,s.token_endpoint),u={...t.tokenParams,...o.length?{scope:o.join(t.scopes.separator)}:{}},l=await HG(s,a,this.authentication(r,t.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(t)),d=await this.tokenResponse(t,r,l),p={...this.token(t,d,o,n,!!n),requestedScopes:o};return await i?.(p,d),p}async refresh(t,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(t.grantType==="client_credentials")return o.requestedScopes||C(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(t,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&C(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(t,r),c=await NG(s,a,this.authentication(r,t.clientAuth),o.refreshToken,{...this.options(t),additionalParameters:t.tokenParams}),u=await this.tokenResponse(t,r,c,!0);i=this.token(t,u,o.scopes,o,!0),await n?.(i,u)}return i}outputs(t,r,o){let n={...this.appValues(t,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(t.outputs).map(([i,s])=>[i,Xi(vn(n,s))]))}};function r9(e){if(e.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return e.method.config}function n9(e){return e||C(409,"app_required","Choose an OAuth application."),e}function hye(e){return{token:y0.parse(e.token),response:It.parse(e.response)}}var S_=class{constructor(t){this.transport=t}transport;facts=Y$;oauth(t){return new Jo({send:r=>this.transport.send({...r,...t?{signal:AbortSignal.any([t,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(t){return!t.oauth||t.oauth.expiresAt!==null&&t.oauth.expiresAt<Date.now()+6e4}async renew(t){let r=t.material,o=r9(r),n=n9(t.app),i=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>t.receive({token:c,response:u}),a=o.grantType==="client_credentials"?await this.oauth(t.signal).clientCredentials(o,n,i??to(o.scopes),r.oauth,s):await this.oauth(t.signal).refresh(o,n,r.oauth,s);return _r.parse({...t.material,oauth:a})}async recover(t,r,o){let i=hye(o).token;return _r.parse({...t,oauth:i})}async outputs(t,r){return this.oauth().outputs(r9(t),n9(r),t.oauth)}};function gye(e){if(e.method.kind!=="token"&&e.method.kind!=="approval")throw new Error("Use an input credential provider.");return e.method.config}var km=class{facts=cu;needsRenewal(){return!1}async outputs(t){let r=gye(t),o=oo(r.fields,t.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,i])=>[n,Ny(o,i)]))}};function __(e){if(e.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return e.method.config}var x_=class{facts=Q$;values(t,r){let o=__(t),n=o.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&C(409,"app_required","Choose an OVHcloud API application with its key and secret.");let i=n?r.fields:t.fields;return oo(o.fields,i)}credentials(t,r){if(__(t).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:t.fields.consumerKey};let o=this.values(t,r);return{applicationKey:o.applicationKey,applicationSecret:o.applicationSecret,consumerKey:o.consumerKey}}needsRenewal(){return!1}async outputs(t,r){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let o=__(t).authorization==="consumer_key"?{...this.values(t,r),...this.credentials(t,r)}:this.values(t,r);return Object.fromEntries(Object.entries(__(t).outputs).map(([n,i])=>[n,Xi(vn(o,i))]))}};import{readFile as yye}from"node:fs/promises";var wye=h.object({accessToken:h.string().min(1).max(16384).regex(/^\S+$/),expiresAt:h.number().int().positive()}).strict();async function vye(e,t){if(e==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,i=n?await yye(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!i||i.length>16384)&&C(409,"authentication_required","Provide the current OIDC token on this machine."),i.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([t,AbortSignal.timeout(3e3)])});r.ok||C(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let o=(await r.text()).trim();return(!o||o.length>16384)&&C(502,"invalid_response","The instance did not return a valid identity token."),o}function o9(e){if(e.method.kind!=="token"||e.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return e.method.config}var E_=class{constructor(t,r=vye){this.transport=t;this.identityToken=r}transport;identityToken;facts=cu;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(t,r){let o=oo(o9(t).fields,t.fields),n=o.authentication;["api_key","oidc","instance"].includes(n)||C(400,"invalid_field","Choose a Vultr authentication source.");let i=n==="api_key"?o.token:o.credential||await this.identityToken(n,r);(!i||i.length>16384||/\s/.test(i))&&C(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(o.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&C(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+i},signal:r,body:JSON.stringify({role_id:o.roleId,session_name:o.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:o.userId}:{},...n==="oidc"?{oidc_issuer_id:o.issuerId}:{}})});a.status>=400&&C(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=Wn(a);(c.role_id!==void 0&&c.role_id!==o.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==o.userId)&&C(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=wye.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&C(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(t,r,o){let n=o9(t);o.throwIfAborted();let i=await Sy(t),s=this.sessions.get(i);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(i);a||(a=this.obtain(t,o),this.pending.set(i,a));try{s=await a,this.sessions.set(i,s)}finally{this.pending.get(i)===a&&this.pending.delete(i)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,Ny(s,c)]))}};function i9(e,t){let r={oauth:new S_(e),token:new km,aws:new d_(t),approval:new km,ovh:new x_},o=new E_(e);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?o:r[n.kind]}function I_(e){return new TextDecoder("utf-8",{fatal:!0}).decode(e)}async function bye(e,t){let r={},o={},n=[],i=new Set;for(let s of e){if(i.has(s.name)||!rj(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await t(s.source),c=s.format??(a.file?"file":"text"),u=a.value;if(c==="json"&&(u=at(Xi(vn(JSON.parse(I_(u)),s.pointer??"")))),c==="file")o[s.name]=Buffer.from(u).toString("base64");else{let l=I_(u);if(l.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=l}n.push(Buffer.from(u).toString("utf8"),Buffer.from(u).toString("base64"),Buffer.from(u).toString("base64url"))}return{environment:r,files:o,sensitive:n}}async function s9(e,t,r){let o=await e.sourceContents(r.map(i=>i.source.id)),n=new Map;return bye(r,async i=>{let s=o.get(i.id);if(s.kind==="variable")return{value:await e.open(s.content)};n.has(i.id)||n.set(i.id,t.outputs(i.id,o,new AbortController().signal));let{values:a,files:c}=await n.get(i.id);if(!i.output||!Object.hasOwn(a,i.output))throw new Error("Choose an available connection output.");return{value:at(a[i.output]),file:c.includes(i.output)}})}var A_=class{constructor(t,r,o,n,i=new l_){this.custody=t;this.broker=r;this.journal=o;this.providers=i9(n,i)}custody;broker;journal;providers;provider(t){return this.providers(t)}metadata(t){return fu(t,this.provider(t.method).facts(t))}source(t,r,o){let n=o.get(t);return(!n||n.kind!==r)&&C(409,"input_required","Include the connection and its application in the inputs."),n.content}async material(t,r){let o=await this.broker.method(t),n=jy(await this.custody.open(r),r.metadata,o);return n.state==="reconnect"&&C(409,"reconnect_required","Reconnect this service before using it."),n}async app(t,r,o){let n=this.source(t,"app",o);await My(n,this.custody.keys.publicKey)||C(403,"refresh_required","Only one its application is sealed for can renew this connection.");let i=fr.parse(JSON.parse(I_(await this.custody.open(n))));return i.methodId!==r&&C(400,"wrong_app","Choose an application for this connection method."),i}async connectionApp(t,r){if(Ue(t.method).application==="none")return null;if(!qi(t.method))return"implicitApp"in t&&t.implicitApp?t.implicitApp:fr.parse({format:1,methodId:t.methodId,generation:t.generation,clientId:"",fields:{}});let o=await this.app(t.appId,t.methodId,r);return o.generation!==t.appGeneration&&C(409,"app_changed","Reconnect this service with the current application."),Ue(t.method).requiresApp&&t.method.kind!=="aws"&&Object.entries(io(t.method.config.fields,t.fields??{})).some(([n,i])=>o.fields[n]!==i)&&C(409,"app_changed","Reconnect this service with the current application settings."),o}async outputs(t,r,o){let n=this.source(t,"connection",r),i=await this.material(t,n);return this.provider(i.method).renew&&await this.broker.state(t)&&C(409,"connection_busy","Resolve the current token update before using this connection."),i=await this.refresh(t,n,i,r,o),{values:await this.provider(i.method).outputs(i,await this.connectionApp(i,r),o),files:i.method.kind==="token"?i.method.config.files??[]:[]}}async deliver(t){let{operation:r,material:o}=t,n=await this.metadata(o);for(let i=1;;i++){let s=await this.custody.seal(r.resource_id,pu(o),t.previous.revision+1,n);try{await this.broker.commit(r.id,r.fence,s);break}catch(a){if(i<3&&a instanceof ct&&a.code==="recipients_changed")continue;throw a}}t.delivered=!0,await this.journal.write("refresh_"+r.id,t)}async refreshed(t,r){return t.material=r,t.phase="settled",await this.journal.write("refresh_"+t.operation.id,t),await this.deliver(t),r}async refresh(t,r,o,n,i){let s=this.provider(o.method);if(!s.needsRenewal(o))return o;s.renew||C(409,"reconnect_required","Reconnect this service to renew access.");let a=await this.connectionApp(o,n),c=Sye(),u=await this.broker.prepare(c,t,r.revision),l={operation:u,previous:r,material:o,app:a,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+c,l);try{i.throwIfAborted(),l.phase="dispatched",await this.journal.write("refresh_"+c,l),await this.broker.dispatch(c,u.fence),i.throwIfAborted();let d=await s.renew({material:o,app:a,signal:i,receive:async p=>{l.checkpoint=p,l.phase="received",await this.journal.write("refresh_"+c,l)}});return await this.refreshed(l,d)}catch(d){let p=l.phase==="dispatched"&&d instanceof ct&&d.code==="reconnect_required";if(l.phase==="prepared"?await this.broker.abort(c,u.fence):p?(await this.broker.refused(c,u.fence),l.delivered=!0,await this.journal.write("refresh_"+c,l)):await this.broker.uncertain(c,u.fence).catch(()=>{}),d instanceof ct&&["reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(d.code))throw d;C(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let t=[];for(let r of await this.journal.pending("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.phase==="settled"){await this.deliver(o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{t.push(r.slice(8))}return t}};import{lookup as _ye}from"node:dns/promises";import{request as xye}from"node:https";import{brotliDecompressSync as Eye,gunzipSync as Iye,inflateSync as Aye}from"node:zlib";var Hl=class{constructor(t){this.origin=t}origin;async send(t){let r=Nr(t.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=t.maxBytes??1048576;t.body&&Buffer.byteLength(t.body)>n&&C(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(t.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&C(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await _ye(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!b_(u.address)))&&C(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]]);return await new Promise((u,l)=>{let d={method:t.method??"GET",headers:i,signal:c,agent:!1,lookup:(f,m,g)=>{m.all?g(null,[a]):g(null,a.address,a.family)}},p=xye(r,d,f=>{let m=[],g=0;f.on("data",w=>{g+=w.length,g>n?f.destroy(new ct(413,"body_limit","The response body is too large.")):m.push(w)}),f.on("error",l),f.on("end",()=>{try{let w=Buffer.concat(m),v=f.headers["content-encoding"];if(v&&v!=="identity"){let x=v==="gzip"?Iye:v==="deflate"?Aye:v==="br"?Eye:null;if(!x)throw new ct(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let b={};for(let[x,E]of Object.entries(f.headers))E!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(b[x]=Array.isArray(E)?E.join(", "):E);u({status:f.statusCode??502,headers:b,body:new Uint8Array(w)})}catch(w){l(w)}})});p.on("error",l),p.end(t.body)})}catch(s){if(s instanceof ct)throw s;t.signal?.aborted&&C(409,"cancelled","The operation was cancelled."),C(502,"service_unavailable","The service could not be reached. Try again.")}}};async function Ws(e){let{keys:t,origin:r,principalId:o}=e.identity;if(!t)throw new Error("Use a sign-in key that carries the encryption key for this operation.");let n={publicKey:ou(t.encryption),privateKey:t.encryption},i=new Fy(e,r,o,n),s=a9(kye(ii()),"custody",await Sr(n.publicKey)),a=new By(e),c=new Hl(r),u=new A_(i,a.connections(),new Vy(a9(s,"connections"),r,n),c);return{custody:i,directory:s,broker:a,transport:c,connections:u}}async function k_(e,t){let{custody:r,connections:o}=await Ws(e);return await o.reconcile(),s9(r,o,t)}import{setTimeout as $ye}from"node:timers/promises";function u9(e){return{kind:e.kind,id:e.flow.operationId,...e.kind==="authorize"?{authorizationUrl:e.url,...e.device?{userCode:e.device.userCode,verificationUri:e.device.verificationUri,expiresAt:new Date(e.device.expiresAt).toISOString()}:{},next:"Have whoever signs in at the service open the URL and allow it, then run foundation connect continue "+e.flow.operationId}:{},...e.kind==="cli"?{next:e.command}:{},...e.kind==="connected"?{connectionId:e.id}:{},...e.kind==="failed"?{error:e.error}:{}}}var qN=e=>Ue(e).outputs,c9=e=>e.id+" ("+qN(e).join(", ")+")";async function l9(e,t,r){if(r)return $.parse(r);let n=(await e.json("/api/relations?"+new URLSearchParams({subject:t,relation:"delegate",objectType:"principal",limit:"200"}),{},pt(Q4))).items;if(n.length===1)return n[0].objectId;throw n.length?new Error("Several principals delegate to this machine. Choose one with --owner: "+n.map(i=>i.objectId+" ("+i.objectName+")").join(", ")):new Error("Choose the principal to ask with --owner ID.")}async function $_(e,t){let r=await e.json("/api/catalog",{},pt(tj)),o=t.service?.toLowerCase(),n=o?r.items.find(c=>c.id.toLowerCase()===o||c.name.toLowerCase()===o):r.items.find(c=>Object.values(c.methods).some(u=>u.id===t.methodId));if(!n)throw new Error(t.service?"No service is named "+t.service+". Check foundation api GET /api/catalog.":"Choose an available connection method.");let i=Object.values(n.methods).filter(c=>c.availability!=="unavailable"&&(!t.methodId||c.id===t.methodId)&&t.needs.every(u=>qN(c).includes(u)));if(!i.length)throw new Error(n.name+" has no available method"+(t.methodId?" "+t.methodId:"")+(t.needs.length?" giving "+t.needs.join(", "):"")+". Its methods: "+Object.values(n.methods).map(c9).join(", "));if(new Set(i.map(c=>[...qN(c)].sort().join(","))).size>1)throw new Error(n.name+" connections give different values. Choose one with --needs NAME or --method ID: "+i.map(c9).join(", "));let a=c=>Number(t.making===!0&&Ue(c).browserAuthorization);return i=[...i].sort((c,u)=>a(u)-a(c)||+(u.availability==="ready")-+(c.availability==="ready")||+(u.registration.kind==="input")-+(c.registration.kind==="input")),{service:n,method:i[0]}}async function d9(e,t,r,o){if(o)return $.parse(o);let n=[],i=null;do{let s=await e.json("/api/principals/"+t+"/resources?"+new URLSearchParams({kind:"app",limit:"200",...i?{after:i}:{}}),{},pt(ze));for(let a of s.items)a.kind==="app"&&a.ownerId===t&&a.data.methodId===r.id&&a.permissions.includes("reveal")&&n.push(a.id);i=s.next}while(i);if(n.length>1)throw new Error("The owner has several applications for "+r.id+". Choose one with --app: "+n.join(", "));return n[0]}function JN(e){return{ownerId:e.ownerId,methodId:e.method.id,name:ce.parse(e.name),...e.connectionId?{connectionId:e.connectionId}:{},...e.appId?{appId:e.appId}:{},...e.scopes?.length?{scopes:e.scopes}:{},...e.fields&&Object.keys(e.fields).length?{fields:e.fields}:{}}}function f9(e,t){if(e.name!=="connection.connect"||!["in_progress","stopped","failed"].includes(e.state))throw new Error("Choose a connection that is still being made.");let r=au.parse(e.input);if(r.users?.length)throw new Error("This connection lets others open it, which its owner decides. Finish it signed in as "+e.actor.name+".");return JN({ownerId:r.ownerId,method:t,name:r.name??t.defaultName,connectionId:r.connectionId,appId:r.appId,scopes:r.scopes,fields:r.fields})}async function p9(e,t){let{owner:r,canListOwner:o,service:n,outputs:i}=t,s=c=>c.ownerId===r&&c.kind==="connection"&&c.permissions.includes("reveal")&&c.data.state==="ready"&&c.data.services.some(u=>u.id===n.id)&&i.every(u=>c.data.outputs.includes(u));if(!o)return(await e.json("/api/resources/shared",{},pt(ze))).items.find(s)??null;let a=null;do{let c=await e.json("/api/principals/"+r+"/resources?"+new URLSearchParams({kind:"connection",limit:"200",...a?{after:a}:{}}),{},pt(ze)),u=c.items.find(s);if(u)return u;a=c.next}while(a);return null}function ZN(e){return{connectionId:e.id,name:e.name,ownerId:e.ownerId,outputs:e.data.outputs}}async function m9(e,t){return e.json("/api/requests",{method:"POST",body:{to:t.owner,message:t.why??"",operations:[{name:"connection.connect",input:{ownerId:t.owner,methodId:t.method.id,name:ce.parse(t.method.defaultName),...t.connectionId?{connectionId:t.connectionId}:{},...!t.connectionId&&t.userId?{users:[t.userId]}:{}}}]}},wn)}async function GN(e,t,r){let o=Date.now()+r*1e3;for(;;){let n=await e.json("/api/requests/"+t.id,{},wn);if(!["pending","approved"].includes(n.state))return{kind:n.state,requestId:t.id};let i=n.performed[0];if(i&&["succeeded","failed","cancelled","uncertain"].includes(i.state)){let s=await e.json("/api/operations/"+i.id,{},dr);if(s.state!=="succeeded")return{kind:s.state,requestId:t.id,operationId:s.id,error:s.error};let a=await e.json("/api/resources/"+$.parse(s.result?.id),{},ze);if(a.kind!=="connection")throw new Error("The request did not make a connection.");return{kind:"connected",requestId:t.id,operationId:s.id,...ZN(a)}}if(Date.now()>=o)throw new Error("The owner has not finished yet. Run foundation connect wait "+t.id+" to keep waiting.");await $ye(1500)}}import{spawn as y9}from"node:child_process";import{createPrivateKey as Tye,createPublicKey as Pye}from"node:crypto";import{chmod as Cye,mkdtemp as Rye,rm as Oye,stat as Nye,writeFile as Dye}from"node:fs/promises";import{tmpdir as zye}from"node:os";import{join as XN}from"node:path";import{setTimeout as Uye}from"node:timers/promises";function w9(){let e=Buffer.from(crypto.getRandomValues(new Uint8Array(32))),t=Tye({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e]),format:"der",type:"pkcs8"}),r=Buffer.from(Pye(t).export({format:"jwk"}).x,"base64url"),o=c=>{let u=Buffer.from(c),l=Buffer.alloc(4);return l.writeUInt32BE(u.length),Buffer.concat([l,u])},n=Buffer.concat([o("ssh-ed25519"),o(r)]),i=Buffer.from(crypto.getRandomValues(new Uint8Array(4))),s=Buffer.concat([i,i,n,o(Buffer.concat([e,r])),o("")]);s=Buffer.concat([s,Buffer.from(Array.from({length:(8-s.length%8)%8},(c,u)=>u+1))]);let a=Buffer.concat([Buffer.from("openssh-key-v1\0"),o("none"),o("none"),o(""),Buffer.from([0,0,0,1]),o(n),o(s)]).toString("base64");return{publicKey:"ssh-ed25519 "+n.toString("base64"),privateKey:`-----BEGIN OPENSSH PRIVATE KEY-----
|
|
125
125
|
`+(a.match(/.{1,70}/g)??[]).join(`
|