@tomato414941/foundation 19.1.0 → 21.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.mjs +1 -1
- package/dist/cli.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -125,8 +125,8 @@ ${c}`:c:"",l=Function,d=`return (input) => {
|
|
|
125
125
|
${c}
|
|
126
126
|
}`,f;try{f=new l(...s,d)(...a)}catch(p){throw new ze(`this schema (generated code failed to evaluate: ${p.message})`)}return e?.debug&&(f.code=u),f.definite=o.definite,f}function ae(t,e){for(let[o,n]of t.constants)if(n===e)return o;let r=`c${t.constantCounter++}`;return t.constants.set(r,e),r}function ju(t,e){return t.definite=!1,ae(t,e)}function te(t){return`v${t.varCounter++}`}function $pe(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return pn;let o=r;return o.issues.length===0?o.value:pn}function Br(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return Ot(t,e,r,o,n)}catch(u){if(!(u instanceof ze)||!u.islandable)throw u;if(t.content.length=i,e.constants.size>s){let l=Array.from(e.constants.keys()).slice(s);for(let d of l)e.constants.delete(d)}return e.constantCounter=a,e.varCounter=c,Ape(t,e,r,o)}}function Ape(t,e,r,o){e.definite=!1;let n=ae(e,r),i=ae(e,$pe),s=te(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var Tpe=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Ppe(t,e,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&&!Tpe.has(a.check))throw new ze('check with a custom "when" condition');switch(a.check){case"greater_than":Rpe(t,e,a,i);break;case"less_than":Cpe(t,e,a,i);break;case"multiple_of":Ope(t,e,a,i);break;case"number_format":HV(t,a,i);break;case"min_length":{let c=Du(a.minimum,"min_length"),u=CR(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Du(a.maximum,"max_length"),u=CR(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Du(a.length,"length_equals"),u=CR(t,e,i,`${i}.length >= ${c} && ${i}.length <= ${a.length*2}`);t.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":t.write(`if (${i}.size < ${Du(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${Du(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${Du(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=BV(t,e,a,i);break;case"custom":i=Upe(t,e,s,i);break;case"bigint_format":Npe(t,a,i);break;case"mime_type":Dpe(t,e,a,i);break;case"property":jpe(t,e,a,i);break;case"properties":zpe(t,e,a,i);break;case"overwrite":{let c=te(e);Mpe(t,e,s,i,c),i=c;break}default:throw new ze(`check type ${a.check}`)}}return i}function CR(t,e,r,o){let n=ae(e,Pu),i=te(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function Du(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new ze(`${e} bound of type ${typeof t}`);return`${t}`}function qV(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new ze("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new ze("comparison check with Invalid Date bound");return ae(t,e)}throw new ze(`comparison check bound of type ${typeof e}`)}function Rpe(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${qV(e,r.value)}) return INVALID;`)}function Cpe(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${qV(e,r.value)}) return INVALID;`)}function Ope(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new ze("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ae(e,Km);t.write(`if (${n}(${o}, ${Du(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function HV(t,e,r){let o=e.format;switch(o){case"safeint":t.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":t.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":t.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":t.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":t.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new ze(`number format ${o}`)}}function Npe(t,e,r){let o=e.format;if(o)switch(o){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new ze(`bigint format ${o}`)}}function Dpe(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=ae(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function zpe(t,e,r,o){if(r.when)throw new ze('check with a custom "when" condition');t.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let s=typeof i=="symbol"?ae(e,i):ln(i),a=te(e);t.write(`const ${a} = ${o}[${s}];`),Br(t,e,n[i],a,!1)}}function jpe(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Ot(t,e,r.schema,n)}function Mpe(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new ze("overwrite check without a transform function");if(Mu(i))throw new ti("z.compile: async overwrite transforms are not supported");let s=ae(e,i);t.write(`const ${n} = ${s}(${o});`)}function OR(){throw new Cn}function zR(t){this.issues.push(t)}function Upe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Mu(n.fn))throw new ti("z.compile: async .refine() predicates are not supported");let i=ju(e,n.fn),s=ae(e,OR),a=te(e);return t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`),o}if(r._zod.check){if(Mu(r._zod.check))throw new ti("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=ju(e,u=>{let l={value:u,issues:[],addIssue:zR};return i(l)instanceof Promise&&OR(),l.issues.length===0?l.value:pn}),c=te(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new ze("custom check without a predicate or check function")}var Lpe=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 BV(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=ae(e,ch);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=ae(e,Vb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ae(e,Jb),l=ae(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=ae(e,ah);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=ae(e,Mb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ae(e,Bb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ae(e,Zb);return t.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=ae(e,Sb),l=ae(e,r),d=te(e),f=te(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${f} = ${u}(${d}, ${l});`),t.write(`if (typeof ${f} === "number") return INVALID;`),s.hostname!==void 0){let g=ae(e,Eb);t.write(`if (!${g}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let g=ae(e,Ib);t.write(`if (!${g}(${f}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=te(e),h=s.normalize?`${f}.href`:`${ae(e,sh)}(${d})`;return t.write(`const ${p} = ${h};`),p}let a=r.fn;if(a){if(Mu(a))throw new ze(`async string format ${i}`);let u=ae(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(Lpe.has(i)&&r.pattern){let u=ae(e,r.pattern);return t.write(`${u}.lastIndex = 0;`),t.write(`if (!${u}.test(${o})) return INVALID;`),o}let c=r.format;switch(c){case"regex":throw new ze("regex format without a pattern");case"lowercase":t.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":t.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":t.write(`if (!${o}.includes(${ln(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${ln(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${ln(u)}) return INVALID;`);break}default:throw new ze(`string format ${c}`)}return o}function Ot(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new ze(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=Fpe(t,e,r,o,a);break;case"number":c=Vpe(t,r,o);break;case"boolean":c=qpe(t,o);break;case"bigint":c=Hpe(t,r,o);break;case"symbol":c=Bpe(t,o);break;case"undefined":c=Kpe(t,o);break;case"null":c=Zpe(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=Wpe(t,o);break;case"nan":c=Jpe(t,o);break;case"date":c=Gpe(t,o);break;case"object":c=Xpe(t,e,r,o,a);break;case"optional":c=Ype(t,e,r,o,a);break;case"nullable":c=tfe(t,e,r,o,a);break;case"array":c=rfe(t,e,r,o,a);break;case"literal":c=nfe(t,e,r,o);break;case"enum":c=ofe(t,e,r,o);break;case"readonly":{let u=LV(t,e,r,o),l=te(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":LV(t,e,r,o),c="true";break;case"default":case"prefault":c=ife(t,e,r,o);break;case"nonoptional":c=sfe(t,e,r,o);break;case"tuple":c=afe(t,e,r,o);break;case"union":c=cfe(t,e,r,o);break;case"intersection":c=dfe(t,e,r,o);break;case"record":c=pfe(t,e,r,o);break;case"map":c=mfe(t,e,r,o);break;case"set":c=hfe(t,e,r,o);break;case"file":c=gfe(t,o);break;case"template_literal":c=yfe(t,e,r,o);break;case"lazy":c=vfe(t,e,r,o);break;case"pipe":c=wfe(t,e,r,o);break;case"custom":c=bfe(t,e,r,o);break;case"transform":c=Sfe(t,e,r,o);break;case"catch":c=xfe(t,e,r,o);break;default:throw new ze(`schema type ${s}`)}return c===null?null:Ppe(t,e,r,c)}function Fpe(t,e,r,o,n=!0){t.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:BV(t,e,i,o,n)}function Vpe(t,e,r){t.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=e._zod.def;return o.check==="number_format"&&o.format&&HV(t,{format:o.format},r),r}function qpe(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function Hpe(t,e,r){t.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=e._zod.def;if(o.format)switch(o.format){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function Bpe(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function Kpe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Zpe(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function Wpe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Jpe(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function Gpe(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function Xpe(t,e,r,o,n=!0){let i=r._zod.def;t.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"?ae(e,b):ln(b),d=b=>typeof b=="symbol"?`[${l(b)}]`:ln(b),f=s;if(a.includes("__proto__"))throw new ze('object shape key "__proto__"');let p=new Map;for(let b of u){let _=f[b],I=l(b),$=te(e);if(t.write(`const ${$} = ${o}[${I}];`),_._zod.optin!==void 0){let C=te(e);t.write(`let ${C} = (() => {`),t.indented(B=>{let Q=Br(B,e,_,$);B.write(`return ${Q};`)}),t.write("})();"),_._zod.optout==="optional"?(t.write(`if (${C} === INVALID) {`),t.indented(B=>{B.write(`if (${I} in ${o}) return INVALID;`),B.write(`${C} = undefined;`)}),t.write("}")):t.write(`if (${C} === INVALID) return INVALID;`),p.set(b,C)}else{efe(_)&&t.write(`if (!(${I} in ${o})) return INVALID;`);let C=Br(t,e,_,$,n);C!==null&&p.set(b,C)}}let h=i.catchall,g="none";if(h){let b=h._zod.def.type;if(b==="never"){let _=a.map(I=>`k !== ${ln(I)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(I=>{I.write(`if (${_}) return INVALID;`)}),t.write("}")}else(b==="unknown"||b==="any")&&!h._zod.def.checks?.length?g="passthrough":g="schema"}let y=te(e),w=u.some(b=>UV(f[b])||NR(f[b]));if(!n){if(g==="schema"){let b=a.length>0?ae(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(_=>{_.write('if (k === "__proto__") continue;'),b&&_.write(`if (${b}.has(k)) continue;`);let I=te(e);_.write(`const ${I} = ${o}[k];`),Br(_,e,h,I,!1)}),t.write("}")}return null}if(w){t.write(`const ${y} = {};`);for(let b of u){let _=l(b),I=p.get(b);NR(f[b])?t.write(`if (${_} in ${o}) ${y}[${_}] = ${I};`):UV(f[b])?t.write(`if (${I} !== undefined || ${_} in ${o}) ${y}[${_}] = ${I};`):t.write(`${y}[${_}] = ${I};`)}}else{let b=u.map(_=>`${d(_)}: ${p.get(_)}`).join(", ");t.write(`const ${y} = { ${b} };`)}if(g!=="none"){let b=a.length>0?ae(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(_=>{if(_.write('if (k === "__proto__") continue;'),b&&_.write(`if (${b}.has(k)) continue;`),g==="passthrough")_.write(`${y}[k] = ${o}[k];`);else{let I=te(e);_.write(`const ${I} = ${o}[k];`);let $=Br(_,e,h,I);_.write(`${y}[k] = ${$};`)}}),t.write("}")}return y}function Ype(t,e,r,o,n=!0){let i=r._zod.def;if(Qpe(r))return Ot(t,e,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=te(e),c=te(e);return t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=Ot(l,e,i.innerType,o);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),t.write("} else {"),t.indented(u=>{let l=Ot(u,e,i.innerType,o);u.write(`${a} = ${l};`)}),t.write("}"),a}let s=n?te(e):null;return s&&t.write(`let ${s};`),t.write(`if (${o} !== undefined) {`),t.indented(a=>{let c=Ot(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function Qpe(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function efe(t){return t._zod.optin===void 0&&zu(t)}function zu(t){if(t._zod.def.coerce)return!0;let e=t._zod.def;switch(e.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 e.innerType?zu(e.innerType):!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return e.innerType?zu(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(zu):!0;case"intersection":return!e.left||!e.right?!0:zu(e.left)&&zu(e.right);case"pipe":return e.in?zu(e.in):!0;default:return!0}}function NR(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function UV(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&Rd(t)}function Rd(t){let e=t._zod.def;switch(e.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!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return e.innerType?Rd(e.innerType):!0;case"union":return e.options?e.options.some(Rd):!0;case"intersection":return!e.left||!e.right||Rd(e.left)||Rd(e.right);case"pipe":return e.out?Rd(e.out):!0;default:return!0}}function tfe(t,e,r,o,n=!0){let i=r._zod.def,s=n?te(e):null;return s&&t.write(`let ${s} = null;`),t.write(`if (${o} !== null) {`),t.indented(a=>{let c=Ot(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function rfe(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (!Array.isArray(${o})) return INVALID;`);let s=n?te(e):null,a=te(e),c=te(e);return s&&t.write(`const ${s} = new Array(${o}.length);`),t.write(`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`),t.indented(u=>{u.write(`const ${c} = ${o}[${a}];`);let l=Br(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function nfe(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=ae(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}let s=i[0];if(typeof s=="number"&&Number.isNaN(s)){let a=ae(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${ln(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")t.write(`if (${o} !== ${s}) return INVALID;`);else if(s===null)t.write(`if (${o} !== null) return INVALID;`);else if(s===void 0)t.write(`if (${o} !== undefined) return INVALID;`);else if(typeof s=="bigint")t.write(`if (${o} !== ${s}n) return INVALID;`);else throw new ze(`literal type ${typeof s}`);return o}function ofe(t,e,r,o){let n=r._zod.values;if(!n)throw new ze("enum schema without enumerated values");let i=ae(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function LV(t,e,r,o){let n=r._zod.def;return Ot(t,e,n.innerType,o)}function ife(t,e,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 Ot(t,e,n.innerType,o);let c=ae(e,s),u=te(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),Ot(t,e,n.innerType,u)}let a=te(e);if(s){let c=ae(e,s),u=ae(e,pd);t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),t.write("} else {"),t.indented(l=>{let d=Ot(l,e,n.innerType,o);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),t.write("}")}else t.write(`let ${a};`),t.write(`if (${o} !== undefined) {`),t.indented(c=>{let u=Ot(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function sfe(t,e,r,o){let n=r._zod.def,i=Ot(t,e,n.innerType,o),s=te(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function afe(t,e,r,o){let n=r._zod.def,i=n.items,s=n.rest;t.write(`if (!Array.isArray(${o})) return INVALID;`);let a=FV(i,"optin"),c=FV(i,"optout");s?t.write(`if (${o}.length < ${a}) return INVALID;`):t.write(`if (${o}.length < ${a} || ${o}.length > ${i.length}) return INVALID;`);let u=te(e);t.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)t.write(`if (${u}.length === ${l}) {`),t.indented(f=>{f.write(`if (${l} < ${o}.length) {`),f.indented(p=>{let h=te(e);p.write(`const ${h} = ${o}[${l}];`);let g=Br(p,e,d,h);p.write(`${u}[${l}] = ${g};`)}),f.write("} else {"),f.indented(p=>{if(NR(d)){p.write(`${u}.length = ${l};`);return}let h=te(e),g=te(e);p.write(`const ${h} = undefined;`),p.write(`const ${g} = (() => {`),p.indented(y=>{let w=Br(y,e,d,h);y.write(`return ${w};`)}),p.write("})();"),p.write(`if (${g} === INVALID || ${g} === undefined) ${u}.length = ${l};`),p.write(`else ${u}[${l}] = ${g};`)}),f.write("}")}),t.write("}");else{let f=te(e);t.write(`const ${f} = ${o}[${l}];`);let p=Br(t,e,d,f);t.write(`${u}[${l}] = ${p};`)}}if(s){let l=te(e),d=te(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(f=>{f.write(`const ${d} = ${o}[${l}];`);let p=Br(f,e,s,d);f.write(`${u}[${l}] = ${p};`)}),t.write("}")}return u}function FV(t,e){for(let r=t.length-1;r>=0;r--)if(!(e==="optin"?t[r]._zod.optin!==void 0:t[r]._zod.optout==="optional"))return r+1;return 0}function cfe(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return ufe(t,e,n,o);if(n.inclusive===!1)throw new ze("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return Ot(t,e,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=ae(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=te(e);t.write(`let ${a};`);for(let c=0;c<i.length;c++){let u=i[c];c===0?t.write(`${a} = (() => {`):t.write(`if (${a} === INVALID) ${a} = (() => {`),t.indented(l=>{let d=Ot(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function ufe(t,e,r,o){if(r.unionFallback)throw new ze("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=te(e),i=te(e);t.write(`const ${n} = ${o}?.[${ln(r.discriminator)}];`),t.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 ze("discriminated union option without static discriminator values");for(let f of u){if(a.has(f))throw new ze(`duplicate discriminator value ${String(f)}`);a.add(f)}let l=Array.from(u,f=>lfe(e,n,f)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(f=>{let p=Ot(f,e,c,o);f.write(`${i} = ${p};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function lfe(t,e,r){if(typeof r=="string")return`${e} === ${ln(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${e})`:`${e} === ${r}`;if(typeof r=="boolean")return`${e} === ${r}`;if(r===null)return`${e} === null`;if(r===void 0)return`${e} === undefined`;if(typeof r=="bigint")return`${e} === ${r}n`;if(typeof r=="symbol"){let o=ae(t,r);return`${e} === ${o}`}throw new ze(`literal discriminator value ${String(r)}`)}function dfe(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=Br(t,e,n.left,o),s=Br(t,e,n.right,o),a=ae(e,Sd),c=te(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function pfe(t,e,r,o){let n=r._zod.def,i=ae(e,vo);t.write(`if (!${i}(${o})) return INVALID;`);let s=te(e),a=te(e),c=te(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let p=[];for(let g of l){if(!(typeof g=="string"||typeof g=="number"||typeof g=="symbol"))throw new ze(`record key value ${String(g)}`);let y=typeof g=="number"?g.toString():g;if(y==="__proto__")throw new ze('record key "__proto__"');p.push(y);let w=ae(e,g),b=Ot(t,e,n.keyType,w),_=te(e);t.write(`const ${_} = ${o}[${ffe(e,y)}];`);let I=Br(t,e,n.valueType,_);t.write(`${s}[${b}] = ${I};`)}let h=ae(e,new Set(p));return t.write(`for (const ${a} in ${o}) {`),t.indented(g=>{g.write(`if (${h}.has(${a})) continue;`),u.mode==="loose"?g.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):g.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let p=n.mode==="loose",h=B_(n.keyType);h.definite===!1&&(e.definite=!1);let g=ae(e,h),y=ae(e,Qs),w=te(e);return VV(t,e,o,a,b=>{b.write(`let ${w} = ${g}(${a});`),b.write(`if (${w} === INVALID && typeof ${a} === "string" && ${y}.test(${a})) ${w} = ${g}(Number(${a}));`),p?b.write(`if (${w} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):b.write(`if (${w} === INVALID) return INVALID;`),b.write(`if (${w} === "__proto__") continue;`);let _=te(e);b.write(`const ${_} = ${o}[${a}];`);let I=Br(b,e,n.valueType,_);b.write(`${s}[${w}] = ${I};`)}),s}return VV(t,e,o,a,p=>{p.write(`const ${c} = ${o}[${a}];`);let h=Br(p,e,n.valueType,c);p.write(`${s}[${a}] = ${h};`)},"return INVALID;"),s}function VV(t,e,r,o,n,i){let s=ae(e,Object.prototype.propertyIsEnumerable),a=te(e),c=te(e),u=te(e);t.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),t.write(`const ${c} = Object.getOwnPropertyNames(${r});`),t.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${c}[${u}];`),l.write(`if (${o} === "__proto__" || !${s}.call(${r}, ${o})) continue;`),n(l)}),t.write("}"),t.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),t.write("}")}function ffe(t,e){return typeof e=="string"?ln(e):ae(t,e)}function mfe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Map)) return INVALID;`);let i=te(e),s=te(e),a=te(e);return t.write(`const ${i} = new Map();`),t.write(`for (const [${s}, ${a}] of ${o}) {`),t.indented(c=>{let u=Ot(c,e,n.keyType,s),l=Ot(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function hfe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Set)) return INVALID;`);let i=te(e),s=te(e);return t.write(`const ${i} = new Set();`),t.write(`for (const ${s} of ${o}) {`),t.indented(a=>{let c=Ot(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function gfe(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function yfe(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=ae(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function vfe(t,e,r,o){let n=r._zod.def,i=ju(e,n.getter),s=ae(e,{parser:null});t.write(`if (!${s}.parser) {`),t.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("};")}),t.write("}");let a=te(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function wfe(t,e,r,o){let n=r._zod.def,i=Ot(t,e,n.in,o);if(n.transform){if(Mu(n.transform))throw new ti("z.compile: async transforms in pipes are not supported");let s=n.transform,c=ju(e,l=>{let d={value:l,issues:[],addIssue:zR},f=s(l,d);return f instanceof Promise?pn:d.issues.length===0?f:pn}),u=te(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),Ot(t,e,n.out,u)}else return Ot(t,e,n.out,i)}function Mu(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function bfe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Mu(n.fn))throw new ti("z.compile: async custom predicates are not supported");let i=ju(e,n.fn),s=ae(e,OR),a=te(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new ze("custom schema without a predicate function");return o}function _fe(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return pn;let n=o;return n.issues.length===0?n.value:e()}function xfe(t,e,r,o){let n=r._zod.def;if(!n.catchValue[Qw])throw new ze("catch with a callback (only a constant catch value compiles)",!1);let i=te(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=Br(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=ae(e,n.innerType),a=ju(e,n.catchValue),c=ae(e,_fe);return t.write(`if (${i} === INVALID) {`),t.indented(u=>{u.write(`${i} = ${c}(${s}, ${a}, ${o});`),u.write(`if (${i} === INVALID) return INVALID;`)}),t.write("}"),i}function Sfe(t,e,r,o){let n=r._zod.def;if(n.transform){if(Mu(n.transform))throw new ti("z.compile: async transforms are not supported");let i=n.transform,a=ju(e,u=>{let l={value:u,issues:[],addIssue:zR},d=i(u,l);return d instanceof Promise?pn:l.issues.length===0?d:pn}),c=te(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function K_(t){return t.checks&&(t.checks=[...t.checks]),t}function Z_(t,e){return new t(K_({type:"string",...z(e)}))}function jR(t,e){return new t(K_({type:"string",coerce:!0,...z(e)}))}function wh(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...z(e)})}function bh(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...z(e)})}function _h(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...z(e)})}function xh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(e)})}function Sh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(e)})}function Eh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(e)})}function Cd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...z(e)})}function Ih(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...z(e)})}function kh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(e)})}function $h(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...z(e)})}function Ah(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(e)})}function Th(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...z(e)})}function Ph(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...z(e)})}function Rh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(e)})}function Ch(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(e)})}function Oh(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(e)})}function W_(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...z(e)})}function Nh(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(e)})}function Dh(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(e)})}function zh(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...z(e)})}function jh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...z(e)})}function Mh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...z(e)})}function J_(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...z(e)})}function G_(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...z(e)})}function Uh(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...z(e)})}var MR={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Lh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(e)})}function Fh(t,e){return new t({type:"string",format:"date",check:"string_format",...z(e)})}function Vh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...z(e)})}function qh(t,e){return new t({type:"string",format:"duration",check:"string_format",...z(e)})}function X_(t,e){return new t(K_({type:"number",checks:[],...z(e)}))}function UR(t,e){return new t(K_({type:"number",coerce:!0,checks:[],...z(e)}))}function Y_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...z(e)})}function Q_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...z(e)})}function ex(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...z(e)})}function tx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...z(e)})}function rx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...z(e)})}function nx(t,e){return new t({type:"boolean",...z(e)})}function LR(t,e){return new t({type:"boolean",coerce:!0,...z(e)})}function ox(t,e){return new t({type:"bigint",...z(e)})}function FR(t,e){return new t({type:"bigint",coerce:!0,...z(e)})}function ix(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...z(e)})}function sx(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...z(e)})}function ax(t,e){return new t({type:"symbol",...z(e)})}function cx(t,e){return new t({type:"undefined",...z(e)})}function ux(t,e){return new t({type:"null",...z(e)})}function lx(t){return new t({type:"any"})}function dx(t){return new t({type:"unknown"})}function px(t,e){return new t({type:"never",...z(e)})}function fx(t,e){return new t({type:"void",...z(e)})}function mx(t,e){return new t({type:"date",...z(e)})}function VR(t,e){return new t({type:"date",coerce:!0,...z(e)})}function hx(t,e){return new t({type:"nan",...z(e)})}function Gi(t,e){return new fb({check:"less_than",...z(e),value:t,inclusive:!1})}function Gn(t,e){return new fb({check:"less_than",...z(e),value:t,inclusive:!0})}function Xi(t,e){return new mb({check:"greater_than",...z(e),value:t,inclusive:!1})}function Xn(t,e){return new mb({check:"greater_than",...z(e),value:t,inclusive:!0})}function gx(t){return Xi(0,t)}function yx(t){return Gi(0,t)}function vx(t){return Gn(0,t)}function wx(t){return Xn(0,t)}function Ha(t,e){return new YP({check:"multiple_of",...z(e),value:t})}function Ba(t,e){return new tR({check:"max_size",...z(e),maximum:t})}function Yi(t,e){return new rR({check:"min_size",...z(e),minimum:t})}function Uu(t,e){return new nR({check:"size_equals",...z(e),size:t})}function Lu(t,e){return new oR({check:"max_length",...z(e),maximum:t})}function ea(t,e){return new iR({check:"min_length",...z(e),minimum:t})}function Fu(t,e){return new sR({check:"length_equals",...z(e),length:t})}function Od(t,e){return new aR({check:"string_format",format:"regex",...z(e),pattern:t})}function Nd(t){return new cR({check:"string_format",format:"lowercase",...z(t)})}function Dd(t){return new uR({check:"string_format",format:"uppercase",...z(t)})}function zd(t,e){return new lR({check:"string_format",format:"includes",...z(e),includes:t})}function jd(t,e){return new dR({check:"string_format",format:"starts_with",...z(e),prefix:t})}function Md(t,e){return new pR({check:"string_format",format:"ends_with",...z(e),suffix:t})}function bx(t,e,r){return new fR({check:"property",property:t,schema:e,...z(r)})}function Ud(t,e){return new mR({check:"properties",shape:t,...z(e)})}function Ld(t,e){return new hR({check:"mime_type",mime:t,...z(e)})}function ri(t){return new gR({check:"overwrite",tx:t})}function Fd(t){return ri(e=>e.normalize(t))}function Vd(){return ri(t=>t.trim())}function qd(){return ri(t=>t.toLowerCase())}function Hd(){return ri(t=>t.toUpperCase())}function Bd(){return ri(t=>QT(t))}function qR(t,e,r){return new t({type:"array",element:e,...z(r)})}function Efe(t,e,r){return new t({type:"union",options:e,...z(r)})}function Ife(t,e,r){return new t({type:"union",options:e,inclusive:!1,...z(r)})}function kfe(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...z(o)})}function $fe(t,e,r){return new t({type:"intersection",left:e,right:r})}function Afe(t,e,r,o){let n=r instanceof de,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...z(i)})}function Tfe(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...z(o)})}function Pfe(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...z(o)})}function Rfe(t,e,r){return new t({type:"set",valueType:e,...z(r)})}function Cfe(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...z(r)})}function Ofe(t,e,r){return new t({type:"enum",entries:e,...z(r)})}function Nfe(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...z(r)})}function _x(t,e){return new t({type:"file",...z(e)})}function Dfe(t,e){return new t({type:"transform",transform:e})}function zfe(t,e){return new t({type:"optional",innerType:e})}function jfe(t,e){return new t({type:"nullable",innerType:e})}function Mfe(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():pd(r)}})}function Ufe(t,e,r){return new t({type:"nonoptional",innerType:e,...z(r)})}function Lfe(t,e){return new t({type:"success",innerType:e})}function Ffe(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:sP(r)})}function Vfe(t,e,r){return new t({type:"pipe",in:e,out:r})}function qfe(t,e){return new t({type:"readonly",innerType:e})}function Hfe(t,e,r){return new t({type:"template_literal",parts:e,...z(r)})}function Bfe(t,e){return new t({type:"lazy",getter:e})}function Kfe(t,e){return new t({type:"promise",innerType:e})}function xx(t,e,r){let o=z(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function Sx(t,e,r){return new t({type:"custom",check:"custom",fn:e,...z(r)})}function Ex(t,e){let r=KV(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(fd(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(fd(i))}},t(o.value,o)),e);return r}function KV(t,e){let r=new at({check:"custom",...z(e)});return r._zod.check=t,r}function Ix(t){let e=new at({check:"describe"});return e._zod.onattach=[r=>{let o=xr.get(r)??{};xr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function kx(t){let e=new at({check:"meta"});return e._zod.onattach=[r=>{let o=xr.get(r)??{};xr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function $x(t,e){let r=z(e),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(p=>typeof p=="string"?p.toLowerCase():p),n=n.map(p=>typeof p=="string"?p.toLowerCase():p));let i=new Set(o),s=new Set(n),a=t.Codec??kd,c=t.Boolean??Ed,u=t.String??qa,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),f=new a({type:"pipe",in:l,out:d,transform:((p,h)=>{let g=p;return r.case!=="sensitive"&&(g=g.toLowerCase()),i.has(g)?!0:s.has(g)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:h.value,inst:f,continue:!1}),{})}),reverseTransform:((p,h)=>p===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function Ka(t,e,r,o={}){let n=z(o),i={check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(i.pattern=r),new t(i)}function Hh(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&_r(t,o,r[o]);return t}function Za(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??xr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function rr(t,e,r,o,n){let i=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:o.path,message:n}):e.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function it(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,l);else{let f=s.schema,p=e.processors[n.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);p(t,e,f,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),it(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Hh(s.schema,c),e.io==="input"&&fn(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function ZV(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Wa(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.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=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,f=t.external.uri??(h=>h);if(d)return{ref:f(d)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${ZV(p)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+ZV(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(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
127
127
|
|
|
128
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function GV(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;GV(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 t.anyOf,t.type=r.length===1?r[0]:r}var XV=new Set(["type","properties","required","additionalProperties"]),WV=["oneOf","anyOf"];function JV(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function HR(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!XV.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??JV(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:HR(a)??{allOf:a};_r(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=JV(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 Zfe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of XV)if(n in t)return;let r=e.filter(n=>WV.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=HR(e);else{let n=r[0],i=WV.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>HR([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,Hh(t,o))}function Ja(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.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 p=t.seen.get(d),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Hh(u,h),Hh(u,l),a._zod.parent===d)for(let y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(h.$ref&&p.def)for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())GV(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.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 t.intersections)for(let u of a.get(c)??[])Zfe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Hh(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,_r(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Kd(e,"input",t.processors),output:Kd(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function fn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return fn(o.element,r);if(o.type==="set")return fn(o.valueType,r);if(o.type==="lazy")return fn(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 fn(o.innerType,r);if(o.type==="intersection")return fn(o.left,r)||fn(o.right,r);if(o.type==="record"||o.type==="map")return fn(o.keyType,r)||fn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:fn(o.in,r)||fn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(fn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(fn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(fn(n,r))return!0;return!!(o.rest&&fn(o.rest,r))}return!1}var BR=(t,e={})=>r=>{let o=Za({...r,processors:e});return it(t,o),Wa(o,t),Ja(o,t)},Kd=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Za({...n??{},target:i,io:e,processors:r});return it(t,s),Wa(s,t),Ja(s,t)};var Zd=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},Wd=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},YV=(t,e)=>{Zd(t,"minimum",e),Wd(t,"maximum",e)},rq=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},nq=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},oq=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},iq=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},QV=(t,e)=>Zd(t,"minimum",e.minimum),eq=(t,e)=>Wd(t,"maximum",e.maximum),tq=t=>(e,r)=>{iq(e,r.format);let[o,n]=t[r.format];Zd(e,"minimum",o),Wd(e,"maximum",n)},Wfe={greater_than:(t,e)=>Zd(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>Wd(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>rq(t,e.value),number_format:tq(Wm),bigint_format:tq(Jm),min_length:QV,max_length:eq,length_equals:(t,e)=>YV(t,e.length),min_size:QV,max_size:eq,size_equals:(t,e)=>YV(t,e.size),string_format:(t,e)=>{iq(t,e.format),e.pattern&&nq(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>oq(t,e.mime)};function nr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)Wfe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Zd(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Zd(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Wd(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Wd(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&rq(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&oq(e,n.mime);for(let i of n.patterns??[])nq(e,i);return e}var Jfe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Gfe=new Map([[Lb,CP],[uh,OP]]),sq=t=>Gfe.get(t)??t,WR=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=nr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=Jfe[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(sq);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},JR=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=nr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let h=new Set;for(let w of a)Number.isFinite(w)&&w!==0?h.add(Math.abs(w)):rr(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[g,...y]=h;g!==void 0&&(n.multipleOf=g),y.length&&(n.allOf=[...n.allOf??[],...y.map(w=>({multipleOf:w}))])}},GR=(t,e,r,o)=>{r.type="boolean"},XR=(t,e,r,o)=>{rr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},YR=(t,e,r,o)=>{rr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},QR=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},eC=(t,e,r,o)=>{rr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},tC=(t,e,r,o)=>{rr(t,e,r,o,"Void cannot be represented in JSON Schema")},rC=(t,e,r,o)=>{r.not={}},nC=(t,e,r,o)=>{},oC=(t,e,r,o)=>{},iC=(t,e,r,o)=>{rr(t,e,r,o,"Date cannot be represented in JSON Schema")},sC=(t,e,r,o)=>{let n=t._zod.def,i=cd(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},aC=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(rr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(rr(t,e,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,e.target==="draft-04"||e.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},cC=(t,e,r,o)=>{rr(t,e,r,o,"NaN cannot be represented in JSON Schema")},uC=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},lC=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=nr(t);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})))},dC=(t,e,r,o)=>{r.type="boolean"},pC=(t,e,r,o)=>{rr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},fC=(t,e,r,o)=>{rr(t,e,r,o,"Function types cannot be represented in JSON Schema")},mC=(t,e,r,o)=>{rr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},hC=(t,e,r,o)=>{rr(t,e,r,o,"Map cannot be represented in JSON Schema")},gC=(t,e,r,o)=>{rr(t,e,r,o,"Set cannot be represented in JSON Schema")},yC=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=nr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=it(i.element,e,{...o,path:[...o.path,"items"]})};function Bh(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?Bh(e.out):e.type==="catch"?Bh(e.innerType):t._zod.optin}var vC=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&rr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)_r(n.properties,u,it(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?Bh(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=it(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},Tx=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>it(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},wC=(t,e,r,o)=>{let n=t._zod.def,i=it(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=it(n.right,e,{...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,e.intersections.push(c)},bC=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((g,y)=>it(g,e,{...o,path:[...o.path,s,y]})),u=i.rest?it(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let g=i.items[l-1];if(!(e.io==="input"?Bh(g)!==void 0:g._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:h}=nr(t);typeof p=="number"&&(n.minItems=p),typeof h=="number"&&(n.maxItems=h)};function KR(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let h=t.get(e)?.def;if(!h)return e;let g=KR(t,h,r);return g===h?e:g}for(let h of["anyOf","oneOf"]){let g=e[h];if(!Array.isArray(g))continue;let y=g.map(w=>KR(t,w,r));y.some((w,b)=>w!==g[b])&&(e={...e,[h]:y})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(h=>typeof h=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(h=>typeof h=="number"?String(h):h):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Qs:rh).source)),p}var ZR=new WeakMap;function Xfe(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of ZR.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=KR(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var _C=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=nr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=it(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)_r(n.patternProperties,sq(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=it(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=ZR.get(e);l||(l=[],ZR.set(e,l),e.deferred.push(()=>Xfe(e))),l.push(t)}n.additionalProperties=it(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&Bh(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))}},xC=(t,e,r,o)=>{let n=t._zod.def,i=it(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},SC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},EC=Symbol();function aq(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(rr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),EC):JSON.parse(s)}var IC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=aq(n.defaultValue,t,e,r,o);s!==EC&&(r.default=s)},kC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=aq(n.defaultValue,t,e,r,o);s!==EC&&(r._prefault=s)},$C=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{rr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},AC=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;it(s,e,o);let a=e.seen.get(t);a.ref=s},TC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},PC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},Px=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},RC=(t,e,r,o)=>{let n=t._zod.innerType;it(n,e,o);let i=e.seen.get(t);i.ref=n},Ax={string:WR,number:JR,boolean:GR,bigint:XR,symbol:YR,null:QR,undefined:eC,void:tC,never:rC,any:nC,unknown:oC,date:iC,enum:sC,literal:aC,nan:cC,template_literal:uC,file:lC,success:dC,custom:pC,function:fC,transform:mC,map:hC,set:gC,array:yC,object:vC,union:Tx,intersection:wC,tuple:bC,record:_C,nullable:xC,nonoptional:SC,default:IC,prefault:kC,catch:$C,pipe:AC,readonly:TC,promise:PC,optional:Px,lazy:RC};function Vu(t,e){if("_idmap"in t){let o=t,n=Za({...e,processors:Ax}),i={};for(let c of o._idmap.entries()){let[u,l]=c;it(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Wa(n,l),_r(s,u,Ja(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=Za({...e,processors:Ax});return it(t,r),Wa(r,t),Ja(r,t)}var Rx=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(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Za({processors:Ax,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return it(e,this.ctx,r)}emit(e,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,Wa(this.ctx,e);let o=Ja(this.ctx,e),{"~standard":n,...i}=o;return i}};var cq={};var rp={};St(rp,{ZodAny:()=>GC,ZodArray:()=>eO,ZodBase64:()=>Gx,ZodBase64URL:()=>Xx,ZodBigInt:()=>ep,ZodBigIntFormat:()=>eS,ZodBoolean:()=>Qd,ZodCIDRv4:()=>Wx,ZodCIDRv6:()=>Jx,ZodCUID:()=>Fx,ZodCUID2:()=>Vx,ZodCatch:()=>wO,ZodCodec:()=>eg,ZodCreditCard:()=>BC,ZodCustom:()=>tg,ZodCustomStringFormat:()=>Hu,ZodDate:()=>Jh,ZodDefault:()=>fO,ZodDiscriminatedUnion:()=>rO,ZodE164:()=>Yx,ZodEmail:()=>jx,ZodEmoji:()=>Ux,ZodEnum:()=>Gd,ZodExactOptional:()=>nS,ZodFile:()=>uO,ZodFunction:()=>TO,ZodGUID:()=>Mx,ZodIBAN:()=>KC,ZodIPv4:()=>Kx,ZodIPv6:()=>Zx,ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,ZodInstanceOf:()=>CO,ZodIntersection:()=>nO,ZodJWT:()=>Qx,ZodKSUID:()=>Bx,ZodLazy:()=>kO,ZodLiteral:()=>cO,ZodMAC:()=>HC,ZodMap:()=>sO,ZodNaN:()=>_O,ZodNanoID:()=>Lx,ZodNever:()=>YC,ZodNonOptional:()=>oS,ZodNull:()=>JC,ZodNullable:()=>pO,ZodNumber:()=>Yd,ZodNumberFormat:()=>Bu,ZodObject:()=>Gh,ZodOptional:()=>Ku,ZodPipe:()=>Qh,ZodPrefault:()=>hO,ZodPreprocess:()=>xO,ZodPromise:()=>AO,ZodReadonly:()=>SO,ZodRecord:()=>Jd,ZodSet:()=>aO,ZodString:()=>Xd,ZodStringFormat:()=>ut,ZodSuccess:()=>vO,ZodSymbol:()=>ZC,ZodTemplateLiteral:()=>IO,ZodTransform:()=>lO,ZodTuple:()=>oO,ZodType:()=>Se,ZodULID:()=>qx,ZodURL:()=>Zh,ZodUUID:()=>Qi,ZodUndefined:()=>WC,ZodUnion:()=>Xh,ZodUnknown:()=>XC,ZodVoid:()=>QC,ZodXID:()=>Hx,ZodXor:()=>tO,_ZodString:()=>zx,_default:()=>mO,_function:()=>gH,any:()=>Xq,array:()=>Oe,base64:()=>Rq,base64url:()=>Cq,bigint:()=>Kq,boolean:()=>Wt,catch:()=>bO,check:()=>yH,cidrv4:()=>Tq,cidrv6:()=>Pq,codec:()=>pH,creditCard:()=>Nq,cuid:()=>_q,cuid2:()=>xq,currencyCode:()=>Lq,custom:()=>iS,date:()=>Qq,describe:()=>vH,discriminatedUnion:()=>Yh,e164:()=>Oq,email:()=>dq,emoji:()=>wq,enum:()=>Er,exactOptional:()=>dO,file:()=>cH,float32:()=>Vq,float64:()=>qq,function:()=>gH,guid:()=>pq,hash:()=>Fq,hex:()=>Uq,hostname:()=>Mq,httpUrl:()=>vq,iban:()=>Dq,instanceof:()=>bH,int:()=>Nx,int32:()=>Hq,int64:()=>Zq,intersection:()=>tp,invertCodec:()=>fH,ipv4:()=>kq,ipv6:()=>Aq,json:()=>xH,jwt:()=>zq,keyof:()=>eH,ksuid:()=>Iq,lazy:()=>$O,literal:()=>G,looseObject:()=>Sr,looseRecord:()=>oH,mac:()=>$q,map:()=>iH,meta:()=>wH,nan:()=>dH,nanoid:()=>bq,nativeEnum:()=>aH,never:()=>tS,nonoptional:()=>yO,null:()=>Wh,nullable:()=>Kh,nullish:()=>uH,number:()=>Je,object:()=>q,optional:()=>ct,partialRecord:()=>nH,pipe:()=>Dx,prefault:()=>gO,preprocess:()=>rg,promise:()=>hH,readonly:()=>EO,record:()=>lt,refine:()=>PO,set:()=>sH,strictObject:()=>tH,string:()=>k,stringFormat:()=>jq,stringbool:()=>_H,success:()=>lH,superRefine:()=>RO,symbol:()=>Jq,templateLiteral:()=>mH,transform:()=>rS,tuple:()=>iO,uint32:()=>Bq,uint64:()=>Wq,ulid:()=>Sq,undefined:()=>Gq,union:()=>st,unknown:()=>ht,url:()=>yq,uuid:()=>fq,uuidv4:()=>mq,uuidv6:()=>hq,uuidv7:()=>gq,void:()=>Yq,xid:()=>Eq,xor:()=>rH});var Cx={};St(Cx,{endsWith:()=>Md,gt:()=>Xi,gte:()=>Xn,includes:()=>zd,length:()=>Fu,lowercase:()=>Nd,lt:()=>Gi,lte:()=>Gn,maxLength:()=>Lu,maxSize:()=>Ba,mime:()=>Ld,minLength:()=>ea,minSize:()=>Yi,multipleOf:()=>Ha,negative:()=>yx,nonnegative:()=>wx,nonpositive:()=>vx,normalize:()=>Fd,overwrite:()=>ri,positive:()=>gx,properties:()=>Ud,property:()=>bx,regex:()=>Od,size:()=>Uu,slugify:()=>Bd,startsWith:()=>jd,toLowerCase:()=>qd,toUpperCase:()=>Hd,trim:()=>Vd,uppercase:()=>Dd});var uq=new WeakSet([Object.prototype,Error.prototype]);function Ox(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var lq=(t,e)=>{pP.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);uq.has(r)||(uq.add(r),Ox(r,"format",o=>n=>eh(o,n)),Ox(r,"flatten",o=>n=>Qm(o,n)),Ox(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,ud,2)}),Ox(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,ud,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Qfe=S("ZodError",lq),Nn=S("ZodError",lq,void 0,{Parent:Error});var CC=md(Nn),OC=hd(Nn),NC=gd(Nn),DC=vd(Nn),zC=tb(Nn),jC=rb(Nn),MC=nb(Nn),UC=ob(Nn),LC=ib(Nn),FC=sb(Nn),VC=ab(Nn),qC=cb(Nn);function tme(){cr.localeError||Ft(U_())}function qu(){cr.memoizer||Ft({memoizer:yh()})}var Se=S("ZodType",(t,e)=>(tme(),de.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(A.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return We(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(PO(t,e))},superRefine(t,e){return this.check(RO(t,e))},overwrite(t){return this.check(ri(t))},optional(){return ct(this)},exactOptional(){return dO(this)},nullable(){return Kh(this)},nullish(){return ct(Kh(this))},nonoptional(t){return yO(this,t)},array(){return Oe(this)},or(t){return st([this,t])},and(t){return tp(this,t)},transform(t){return Dx(this,rS(t))},default(t){return mO(this,t)},prefault(t){return gO(this,t)},catch(t){return bO(this,t)},pipe(t){return Dx(this,t)},readonly(){return EO(this)},describe(t){let e=this.clone();return xr.add(e,{description:t}),e},meta(...t){if(t.length===0)return xr.get(this);let e=this.clone();return xr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return A.hide(this,"~standard",{...wb(this),jsonSchema:{input:Kd(this,"input"),output:Kd(this,"output")}})},set"~standard"(t){A.own(this,"~standard",t)},parse:function t(e,r){return CC(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await OC(this,e,r,{callee:t})},safeParse(t,e){return NC(this,t,e)},async safeParseAsync(t,e){return DC(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){A.own(this,"spa",t)},validate(t,e){return bd(this,t,e)},validateAsync(t,e){return _d(this,t,e)},encode:function t(e,r){return zC(this,e,r,{callee:t})},decode:function t(e,r){return jC(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await MC(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await UC(this,e,r,{callee:t})},safeEncode(t,e){return LC(this,t,e)},safeDecode(t,e){return FC(this,t,e)},async safeEncodeAsync(t,e){return VC(this,t,e)},async safeDecodeAsync(t,e){return qC(this,t,e)},toJSONSchema(t){return BR(this,{})(t)},get description(){return xr.get(this)?.description},get _def(){return this._zod.def}}),zx=S("_ZodString",(t,e)=>{qa.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WR(t,r,o,n)},A.derived({format:t=>nr(t).format??null,minLength:t=>nr(t).minimum??null,maxLength:t=>nr(t).maximum??null},{regex(...t){return this.check(Od(...t))},includes(...t){return this.check(zd(...t))},startsWith(...t){return this.check(jd(...t))},endsWith(...t){return this.check(Md(...t))},min(...t){return this.check(ea(...t))},max(...t){return this.check(Lu(...t))},length(...t){return this.check(Fu(...t))},nonempty(...t){return this.check(ea(1,...t))},lowercase(t){return this.check(Nd(t))},uppercase(t){return this.check(Dd(t))},trim(){return this.check(Vd())},normalize(...t){return this.check(Fd(...t))},toLowerCase(){return this.check(qd())},toUpperCase(){return this.check(Hd())},slugify(){return this.check(Bd())}})),Xd=S("ZodString",(t,e)=>{qa.init(t,e),zx.init(t,e)},{email(t){return this.check(wh(jx,t))},url(t){return this.check(Cd(Zh,t))},jwt(t){return this.check(Uh(Qx,t))},emoji(t){return this.check(Ih(Ux,t))},guid(t){return this.check(bh(Mx,t))},uuid(t){return this.check(_h(Qi,t))},uuidv4(t){return this.check(xh(Qi,t))},uuidv6(t){return this.check(Sh(Qi,t))},uuidv7(t){return this.check(Eh(Qi,t))},nanoid(t){return this.check(kh(Lx,t))},cuid(t){return this.check($h(Fx,t))},cuid2(t){return this.check(Ah(Vx,t))},ulid(t){return this.check(Th(qx,t))},base64(t){return this.check(zh(Gx,t))},base64url(t){return this.check(jh(Xx,t))},xid(t){return this.check(Ph(Hx,t))},ksuid(t){return this.check(Rh(Bx,t))},ipv4(t){return this.check(Ch(Kx,t))},ipv6(t){return this.check(Oh(Zx,t))},cidrv4(t){return this.check(Nh(Wx,t))},cidrv6(t){return this.check(Dh(Jx,t))},e164(t){return this.check(Mh(Yx,t))},datetime(t){return this.check(Lh(Ga,t))},date(t){return this.check(Fh(Xa,t))},time(t){return this.check(Vh(Ya,t))},duration(t){return this.check(qh(Qa,t))}});function k(t){return Z_(Xd,t)}var ut=S("ZodStringFormat",(t,e)=>{Qe.init(t,e),zx.init(t,e)}),Ga=S("ZodISODateTime",(t,e)=>{_R.init(t,e),ut.init(t,e)}),Xa=S("ZodISODate",(t,e)=>{xR.init(t,e),ut.init(t,e)}),Ya=S("ZodISOTime",(t,e)=>{SR.init(t,e),ut.init(t,e)}),Qa=S("ZodISODuration",(t,e)=>{ER.init(t,e),ut.init(t,e)}),jx=S("ZodEmail",(t,e)=>{xb.init(t,e),ut.init(t,e)});function dq(t){return wh(jx,t)}var Mx=S("ZodGUID",(t,e)=>{bb.init(t,e),ut.init(t,e)});function pq(t){return bh(Mx,t)}var Qi=S("ZodUUID",(t,e)=>{_b.init(t,e),ut.init(t,e)});function fq(t){return _h(Qi,t)}function mq(t){return xh(Qi,t)}function hq(t){return Sh(Qi,t)}function gq(t){return Eh(Qi,t)}var Zh=S("ZodURL",(t,e)=>{kb.init(t,e),ut.init(t,e)});function yq(t){return Cd(Zh,t)}function vq(t){return Cd(Zh,{protocol:th,hostname:DP,...A.normalizeParams(t)})}var Ux=S("ZodEmoji",(t,e)=>{$b.init(t,e),ut.init(t,e)});function wq(t){return Ih(Ux,t)}var Lx=S("ZodNanoID",(t,e)=>{Ab.init(t,e),ut.init(t,e)});function bq(t){return kh(Lx,t)}var Fx=S("ZodCUID",(t,e)=>{Tb.init(t,e),ut.init(t,e)});function _q(t){return $h(Fx,t)}var Vx=S("ZodCUID2",(t,e)=>{Pb.init(t,e),ut.init(t,e)});function xq(t){return Ah(Vx,t)}var qx=S("ZodULID",(t,e)=>{Rb.init(t,e),ut.init(t,e)});function Sq(t){return Th(qx,t)}var Hx=S("ZodXID",(t,e)=>{Cb.init(t,e),ut.init(t,e)});function Eq(t){return Ph(Hx,t)}var Bx=S("ZodKSUID",(t,e)=>{Ob.init(t,e),ut.init(t,e)});function Iq(t){return Rh(Bx,t)}var Kx=S("ZodIPv4",(t,e)=>{Nb.init(t,e),ut.init(t,e)});function kq(t){return Ch(Kx,t)}var HC=S("ZodMAC",(t,e)=>{zb.init(t,e),ut.init(t,e)});function $q(t){return W_(HC,t)}var Zx=S("ZodIPv6",(t,e)=>{Db.init(t,e),ut.init(t,e)});function Aq(t){return Oh(Zx,t)}var Wx=S("ZodCIDRv4",(t,e)=>{jb.init(t,e),ut.init(t,e)});function Tq(t){return Nh(Wx,t)}var Jx=S("ZodCIDRv6",(t,e)=>{Ub.init(t,e),ut.init(t,e)});function Pq(t){return Dh(Jx,t)}var Gx=S("ZodBase64",(t,e)=>{Fb.init(t,e),ut.init(t,e)});function Rq(t){return zh(Gx,t)}var Xx=S("ZodBase64URL",(t,e)=>{qb.init(t,e),ut.init(t,e)});function Cq(t){return jh(Xx,t)}var Yx=S("ZodE164",(t,e)=>{Hb.init(t,e),ut.init(t,e)});function Oq(t){return Mh(Yx,t)}var BC=S("ZodCreditCard",(t,e)=>{Kb.init(t,e),ut.init(t,e)});function Nq(t){return J_(BC,t)}var KC=S("ZodIBAN",(t,e)=>{Wb.init(t,e),ut.init(t,e)});function Dq(t){return G_(KC,t)}var Qx=S("ZodJWT",(t,e)=>{Gb.init(t,e),ut.init(t,e)});function zq(t){return Uh(Qx,t)}var Hu=S("ZodCustomStringFormat",(t,e)=>{Xb.init(t,e),ut.init(t,e)});function jq(t,e,r={}){return Ka(Hu,t,e,r)}function Mq(t){return Ka(Hu,"hostname",NP,t)}function Uq(t){return Ka(Hu,"hex",JP,t)}function Lq(t){return Ka(Hu,"currency_code",jP,t)}function Fq(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Jn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Ka(Hu,o,n,e)}var Yd=S("ZodNumber",(t,e)=>{lh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JR(t,r,o,n),t.isFinite=!0},A.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=nr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=nr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=nr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>nr(t).format??null},{gt(t,e){return this.check(Xi(t,e))},gte(t,e){return this.check(Xn(t,e))},min(t,e){return this.check(Xn(t,e))},lt(t,e){return this.check(Gi(t,e))},lte(t,e){return this.check(Gn(t,e))},max(t,e){return this.check(Gn(t,e))},int(t){return this.check(Nx(t))},safe(t){return this.check(Nx(t))},positive(t){return this.check(Xi(0,t))},nonnegative(t){return this.check(Xn(0,t))},negative(t){return this.check(Gi(0,t))},nonpositive(t){return this.check(Gn(0,t))},multipleOf(t,e){return this.check(Ha(t,e))},step(t,e){return this.check(Ha(t,e))},finite(){return this}}));function Je(t){return X_(Yd,t)}var Bu=S("ZodNumberFormat",(t,e)=>{Yb.init(t,e),Yd.init(t,e)});function Nx(t){return Y_(Bu,t)}function Vq(t){return Q_(Bu,t)}function qq(t){return ex(Bu,t)}function Hq(t){return tx(Bu,t)}function Bq(t){return rx(Bu,t)}var Qd=S("ZodBoolean",(t,e)=>{Ed.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GR(t,r,o,n)});function Wt(t){return nx(Qd,t)}var ep=S("ZodBigInt",(t,e)=>{dh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XR(t,r,o,n)},A.derived({minValue:t=>nr(t).minimum??null,maxValue:t=>nr(t).maximum??null,format:t=>nr(t).format??null},{gte(t,e){return this.check(Xn(t,e))},min(t,e){return this.check(Xn(t,e))},gt(t,e){return this.check(Xi(t,e))},lt(t,e){return this.check(Gi(t,e))},lte(t,e){return this.check(Gn(t,e))},max(t,e){return this.check(Gn(t,e))},positive(t){return this.check(Xi(BigInt(0),t))},negative(t){return this.check(Gi(BigInt(0),t))},nonpositive(t){return this.check(Gn(BigInt(0),t))},nonnegative(t){return this.check(Xn(BigInt(0),t))},multipleOf(t,e){return this.check(Ha(t,e))}}));function Kq(t){return ox(ep,t)}var eS=S("ZodBigIntFormat",(t,e)=>{Qb.init(t,e),ep.init(t,e)});function Zq(t){return ix(eS,t)}function Wq(t){return sx(eS,t)}var ZC=S("ZodSymbol",(t,e)=>{e_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YR(t,r,o,n)});function Jq(t){return ax(ZC,t)}var WC=S("ZodUndefined",(t,e)=>{t_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eC(t,r,o,n)});function Gq(t){return cx(WC,t)}var JC=S("ZodNull",(t,e)=>{r_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QR(t,r,o,n)});function Wh(t){return ux(JC,t)}var GC=S("ZodAny",(t,e)=>{n_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nC(t,r,o,n)});function Xq(){return lx(GC)}var XC=S("ZodUnknown",(t,e)=>{o_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oC(t,r,o,n)});function ht(){return dx(XC)}var YC=S("ZodNever",(t,e)=>{i_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rC(t,r,o,n)});function tS(t){return px(YC,t)}var QC=S("ZodVoid",(t,e)=>{s_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tC(t,r,o,n)});function Yq(t){return fx(QC,t)}var Jh=S("ZodDate",(t,e)=>{a_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iC(t,r,o,n),t.min=(r,o)=>t.check(Xn(r,o)),t.max=(r,o)=>t.check(Gn(r,o))},A.derived({minDate:t=>{let{minimum:e}=nr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=nr(t);return e?new Date(e):null}},{}));function Qq(t){return mx(Jh,t)}var eO=S("ZodArray",(t,e)=>{qu(),c_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yC(t,r,o,n),t.element=e.element},{min(t,e){return this.check(ea(t,e))},nonempty(t){return this.check(ea(1,t))},max(t,e){return this.check(Lu(t,e))},length(t,e){return this.check(Fu(t,e))},unwrap(){return this.element}});function Oe(t,e){return qR(eO,t,e)}function eH(t){let e=t._zod.def.shape;return Er(Object.keys(e))}var Gh=S("ZodObject",(t,e)=>{qu(),IR.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vC(t,r,o,n),A.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Er(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(A.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ht()}))},loose(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ht()}))},strict(){return this.clone(A.mergeDefs(this._zod.def,{catchall:tS()}))},strip(){return this.clone(A.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return A.extend(this,t)},safeExtend(t){return A.safeExtend(this,t)},merge(t){return A.merge(this,t)},pick(t){return A.pick(this,t)},omit(t){return A.omit(this,t)},partial(...t){return A.partial(Ku,this,t[0])},exactPartial(...t){return A.partial(nS,this,t[0],"exactPartial")},required(...t){return A.required(oS,this,t[0])}});function q(t,e){let r={type:"object",shape:t??{},...A.normalizeParams(e)};return new Gh(r)}function tH(t,e){return new Gh({type:"object",shape:t,catchall:tS(),...A.normalizeParams(e)})}function Sr(t,e){return new Gh({type:"object",shape:t,catchall:ht(),...A.normalizeParams(e)})}var Xh=S("ZodUnion",(t,e)=>{Id.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tx(t,r,o,n),t.options=e.options});function st(t,e){return new Xh({type:"union",options:t,...A.normalizeParams(e)})}var tO=S("ZodXor",(t,e)=>{Xh.init(t,e),l_.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tx(t,r,o,n),t.options=e.options});function rH(t,e){return new tO({type:"union",options:t,inclusive:!1,...A.normalizeParams(e)})}var rO=S("ZodDiscriminatedUnion",(t,e)=>{Xh.init(t,e),d_.init(t,e)});function Yh(t,e,r){return new rO({type:"union",options:e,discriminator:t,...A.normalizeParams(r)})}var nO=S("ZodIntersection",(t,e)=>{p_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wC(t,r,o,n)});function tp(t,e){return new nO({type:"intersection",left:t,right:e})}var oO=S("ZodTuple",(t,e)=>{qu(),ph.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bC(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Ku({type:"optional",innerType:e}))})}});function iO(t,e,r){let o=e instanceof de,n=o?r:e,i=o?e:null;return new oO({type:"tuple",items:t,rest:i,...A.normalizeParams(n)})}var Jd=S("ZodRecord",(t,e)=>{qu(),f_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_C(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function lt(t,e,r){return!e||!e._zod?new Jd({type:"record",keyType:k(),valueType:t,...A.normalizeParams(e)}):new Jd({type:"record",keyType:t,valueType:e,...A.normalizeParams(r)})}function nH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,...A.normalizeParams(r),partial:!0})}function oH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,mode:"loose",...A.normalizeParams(r)})}var sO=S("ZodMap",(t,e)=>{qu(),m_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hC(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Yi(...r)),t.nonempty=r=>t.check(Yi(1,r)),t.max=(...r)=>t.check(Ba(...r)),t.size=(...r)=>t.check(Uu(...r))});function iH(t,e,r){return new sO({type:"map",keyType:t,valueType:e,...A.normalizeParams(r)})}var aO=S("ZodSet",(t,e)=>{qu(),h_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gC(t,r,o,n),t.min=(...r)=>t.check(Yi(...r)),t.nonempty=r=>t.check(Yi(1,r)),t.max=(...r)=>t.check(Ba(...r)),t.size=(...r)=>t.check(Uu(...r))});function sH(t,e){return new aO({type:"set",valueType:t,...A.normalizeParams(e)})}var Gd=S("ZodEnum",(t,e)=>{g_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(o,n,i)=>sC(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Gd({...e,checks:[],...A.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.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 Gd({...e,checks:[],...A.normalizeParams(n),entries:i})}});function Er(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Gd({type:"enum",entries:r,...A.normalizeParams(e)})}function aH(t,e){return new Gd({type:"enum",entries:t,...A.normalizeParams(e)})}var cO=S("ZodLiteral",(t,e)=>{y_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aC(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function G(t,e){return new cO({type:"literal",values:Array.isArray(t)?t:[t],...A.normalizeParams(e)})}var uO=S("ZodFile",(t,e)=>{v_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lC(t,r,o,n),t.min=(r,o)=>t.check(Yi(r,o)),t.max=(r,o)=>t.check(Ba(r,o)),t.mime=(r,o)=>t.check(Ld(Array.isArray(r)?r:[r],o))});function cH(t){return _x(uO,t)}var lO=S("ZodTransform",(t,e)=>{qu(),w_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mC(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Va(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(A.issue(i,r.value,e));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=t),r.issues.push(A.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function rS(t){return new lO({type:"transform",transform:t})}var Ku=S("ZodOptional",(t,e)=>{fh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ct(t){return new Ku({type:"optional",innerType:t})}var nS=S("ZodExactOptional",(t,e)=>{b_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function dO(t){return new nS({type:"optional",innerType:t})}var pO=S("ZodNullable",(t,e)=>{__.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Kh(t){return new pO({type:"nullable",innerType:t})}function uH(t){return ct(Kh(t))}var fO=S("ZodDefault",(t,e)=>{x_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function mO(t,e){return new fO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var hO=S("ZodPrefault",(t,e)=>{S_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function gO(t,e){return new hO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var oS=S("ZodNonOptional",(t,e)=>{E_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yO(t,e){return new oS({type:"nonoptional",innerType:t,...A.normalizeParams(e)})}var vO=S("ZodSuccess",(t,e)=>{I_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function lH(t){return new vO({type:"success",innerType:t})}var wO=S("ZodCatch",(t,e)=>{k_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$C(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function bO(t,e){return new wO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:A.constantCatch(e)})}var _O=S("ZodNaN",(t,e)=>{$_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cC(t,r,o,n)});function dH(t){return hx(_O,t)}var Qh=S("ZodPipe",(t,e)=>{mh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AC(t,r,o,n),t.in=e.in,t.out=e.out});function Dx(t,e){return new Qh({type:"pipe",in:t,out:e})}var eg=S("ZodCodec",(t,e)=>{Qh.init(t,e),kd.init(t,e)});function pH(t,e,r){return new eg({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function fH(t){let e=t._zod.def;return new eg({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var xO=S("ZodPreprocess",(t,e)=>{Qh.init(t,e),$R.init(t,e)}),SO=S("ZodReadonly",(t,e)=>{A_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function EO(t){return new SO({type:"readonly",innerType:t})}var IO=S("ZodTemplateLiteral",(t,e)=>{T_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uC(t,r,o,n)});function mH(t,e){return new IO({type:"template_literal",parts:t,...A.normalizeParams(e)})}var kO=S("ZodLazy",(t,e)=>{$d.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RC(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function $O(t){return new kO({type:"lazy",getter:t})}var AO=S("ZodPromise",(t,e)=>{R_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function hH(t){return new AO({type:"promise",innerType:t})}var TO=S("ZodFunction",(t,e)=>{P_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fC(t,r,o,n)});function gH(t){return new TO({type:"function",input:Array.isArray(t?.input)?iO(t?.input):t?.input??Oe(ht()),output:t?.output??ht()})}var tg=S("ZodCustom",(t,e)=>{C_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pC(t,r,o,n)});function yH(t){let e=new at({check:"custom"});return e._zod.check=t,e}function iS(t,e){return xx(tg,t??(()=>!0),e)}function PO(t,e={}){return Sx(tg,t,e)}function RO(t,e){return Ex(t,e)}var vH=Ix,wH=kx,CO=S("ZodInstanceOf",(t,e)=>{tg.init(t,e)},{properties(t,e){return this.check(Ud(t,e))}});function bH(t,e={}){let r=new CO({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...A.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var _H=(...t)=>$x({Codec:eg,Boolean:Qd,String:Xd},...t);function xH(t){let e=$O(()=>st([k(t),Je(),Wt(),Wh(),Oe(e),lt(k(),e)]));return e}function rg(t,e){return new xO({type:"pipe",in:rS(t),out:e})}var rme={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 nme(t){Ft({customError:t})}function ome(){return Ft().customError}var OO;OO||(OO={});var Zu={};St(Zu,{ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,date:()=>sme,datetime:()=>ime,duration:()=>cme,time:()=>ame});function ime(t){return Lh(Ga,t)}function sme(t){return Fh(Xa,t)}function ame(t){return Vh(Ya,t)}function cme(t){return qh(Qa,t)}var V={...rp,...Cx,iso:Zu},ume=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 lme(t,e){let r=t.$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":e??"draft-2020-12"}function SH(t,e){return t.map((r,o)=>o<e?r:r.optional())}function dme(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function pme(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:dme(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function fme(t,e){return V.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(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function NO(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=NO(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=NO(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var mme=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),hme=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function ng(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(ng):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>mme.has(e)?ng(r):!hme.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(ng))}function EH(t){return t===1?"element":"elements"}function gme(t,e){return V.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=NO(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(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${EH(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${EH(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function IH(t,e){if(t!==!1)return t===void 0||t===!0?V.any():mn(t,e)}var yme=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function kH(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return V.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return V.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=pme(n,e),s=mn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return V.null();if(n.length===0)return V.never();if(n.length===1)return V.literal(n[0]);if(n.every(s=>typeof s=="string"))return V.enum(n);let i=n.map(s=>V.literal(s));return i.length<2?i[0]:V.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return V.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return kH(s,e)});return n.length===0?V.never():n.length===1?n[0]:V.union(n)}if(!r)return V.any();let o;switch(r){case"string":{let n=V.string();if(t.format){let i=t.format;i==="email"?n=n.check(V.email()):i==="uri"||i==="uri-reference"?n=n.check(V.url()):i==="uuid"||i==="guid"?n=n.check(V.uuid()):i==="date-time"?n=n.check(V.iso.datetime({offset:!0})):i==="date"?n=n.check(V.iso.date()):i==="time"?n=n.check(V.regex(yme)):i==="duration"?n=n.check(V.iso.duration()):i==="hostname"?n=n.check(V.hostname()):i==="ipv4"?n=n.check(V.ipv4()):i==="ipv6"?n=n.check(V.ipv6()):i==="mac"?n=n.check(V.mac()):i==="cidr"?n=n.check(V.cidrv4()):i==="cidr-v6"?n=n.check(V.cidrv6()):i==="base64"?n=n.check(V.base64()):i==="base64url"?n=n.check(V.base64url()):i==="e164"?n=n.check(V.e164()):i==="credit_card"?n=n.check(V.creditCard()):i==="iban"?n=n.check(V.iban()):i==="jwt"?n=n.check(V.jwt()):i==="emoji"?n=n.check(V.emoji()):i==="nanoid"?n=n.check(V.nanoid()):i==="cuid"?n=n.check(V.cuid()):i==="cuid2"?n=n.check(V.cuid2()):i==="ulid"?n=n.check(V.ulid()):i==="xid"?n=n.check(V.xid()):i==="ksuid"&&(n=n.check(V.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?V.number().int():V.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=V.boolean();break}case"null":{o=V.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?mn(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=mn(f,e);_r(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let g of f){let y=mn(d[g],e),w=V.string().regex(new RegExp(g));p.push(V.looseRecord(w,y))}let h=[];if(Object.keys(n).length>0&&h.push(V.object(n).passthrough()),h.push(...p),h.length===0)o=V.object({}).passthrough();else if(h.length===1)o=h[0];else{let g=V.intersection(h[0],h[1]);for(let y=2;y<h.length;y++)g=V.intersection(g,h[y]);o=g}if(t.additionalProperties===!1){let g=Object.keys(n),y=f.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!vo(b.value))return;let _=[];for(let I of Object.keys(b.value))g.includes(I)||y.some($=>$.test(I))||_.push(I);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=V.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=mn(f,e)}o=fme(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>mn(d,e)),c=SH(a,s),u=Array.isArray(i)?void 0:IH(i,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>mn(d,e)),c=SH(a,s),u=IH(t.additionalItems,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(i!==void 0){let s=mn(i,e),a=V.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=V.array(V.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=gme(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?mn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function mn(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r=kH(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>mn(u,e)),c=V.union(a);r=o?V.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>mn(u,e)),c=V.xor(a);r=o?V.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:V.any();else{let a=o?r:mn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=V.intersection(a,mn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=V.nullable(r)),t.readOnly===!0&&(r=V.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!ng(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!ng(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))ume.has(a)||_r(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function $H(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=lme(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??xr};return mn(r,i)}var AH=Symbol("z.visit/resolving");function og(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===AH)return new $d({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,AH);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,f={};for(let h of l){let g=n(u[h]);g!==u[h]&&(d=!0),f[h]=g}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?We(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:We(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let h=n(p);h!==p&&(l=!0),d.push(h)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?We(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:We(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:We(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?We(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:We(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:We(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:We(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:We(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return We(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(t)}function TH(t){return og(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:st(r.options)}})}function vme(t,e){if(!e?.length)return t;let r=t._zod.def;return We(t,yo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function PH(t){return vme(t.out,t.checks)}function wme(t){return t.in._zod.traits.has("$ZodTransform")?PH(t):t.in}function RH(t){return og(t,{pipe:e=>wme(e._zod.def),default:(e,r)=>r?ct(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function CH(t){return og(t,{pipe:e=>PH(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var DO={};St(DO,{bigint:()=>Sme,boolean:()=>xme,date:()=>Eme,number:()=>_me,string:()=>bme});function bme(t){return jR(Xd,t)}function _me(t){return UR(Yd,t)}function xme(t){return LR(Qd,t)}function Sme(t){return FR(ep,t)}function Eme(t){return VR(Jh,t)}var ig={name:"@tomato414941/foundation",version:"19.1.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs","foundation-executor":"dist/agent.mjs"},files:["dist/cli.mjs","dist/agent.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"&&m.config({jitless:!0});function kme(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[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())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[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(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var OH=m.string().trim().max(8192).refine(t=>kme(t)!==null,"Use an OpenSSH public key from a .pub file."),sS=m.object({authorizedKeys:m.array(OH).max(32)}).strict(),k2e=sS.extend({revision:m.number().int().positive().optional()}),zO=sS.extend({host:m.string().min(1).max(253).nullable(),port:m.number().int().min(1).max(65535),username:m.string().regex(/^[a-z_][a-z0-9_-]*$/),workingDirectory:m.string().startsWith("/").max(4096),hostKey:OH.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),$2e=zO.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])});var np=new TextEncoder,op=new TextDecoder,NH=new TextDecoder("utf-8",{fatal:!0}),aS=2**32;function hn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function jO(t,e,r){if(e<0||e>=aS)throw new RangeError(`value must be >= 0 and <= ${aS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function MO(t){let e=Math.floor(t/aS),r=t%aS,o=new Uint8Array(8);return jO(o,e,0),jO(o,r,4),o}function cS(t){let e=new Uint8Array(4);return jO(e,t),e}var $me=/[^\x00-\x7f]/;function Ir(t){if(typeof t=="string"&&t.length>=128){if($me.test(t))throw new TypeError("non-ASCII string encountered in encode()");return np.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function DH(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function zH(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function uS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var ta=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Wu=class extends ta{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},dt=class extends ta{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},ec=class extends ta{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},U=class extends ta{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},At=class extends ta{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var sg=class extends ta{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var lS=class extends ta{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var Ame="The input to be decoded is not correctly encoded.";function Ju(t){try{return zH(typeof t=="string"?t:op.decode(t),!0)}catch(e){throw new TypeError(Ame,{cause:e})}}function Nt(t){return DH(typeof t=="string"?np.encode(t):t,!0)}function Yn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Yt(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function tc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function bo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function Dn(t,e,r){try{return Ju(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function dS(t,e,r){try{return Ir(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function ip(t,e,r){let o;try{o=JSON.parse(NH.decode(Ju(t)))}catch{throw new e(r)}if(!Yt(o))throw new e(r);return o}var pS={__proto__:null,b64:!0},fS={__proto__:null};function ag(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function mS(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function rc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"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 t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new dt(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function hS(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new At('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Gu(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!Yt(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var Tme=t=>t[Symbol.toStringTag],Pme=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function oi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(Yt(e)){if(s=HO(e),typeof s.kty!="string")throw jH(o,e,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(Pme(t,s,r),s.kty==="oct")return Ju(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!FO(e))throw jH(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${Tme(e)} instances must be of type "${l}" for the ${o} algorithm`);if(nc(e))return e;if(a=e,a.type==="secret")return a.export()}UO||=new WeakMap;let c=e,u=UO.get(c);if(u?.[o])return u[o];if(u||UO.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Rme[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await ap(t,s)}var UO,Rme={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function yS(t){if(!nc(t))throw new Error("CryptoKey instance expected")}var nc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},LO=t=>t?.[Symbol.toStringTag]==="KeyObject",FO=t=>nc(t)||LO(t);function MH(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var ra=(t,...e)=>MH("Key must be ",t,...e);function jH(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(MH(`Key for the ${t} algorithm must be `,e,...o))}var gS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function VO(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function sp(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function qO(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw gS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw gS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw gS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw gS(e.length,"algorithm.length");VO(t,r)}function vS(t){return{__proto__:null,...t}}function HO(t){let e=vS(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.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');e.key_ops=o}return e}function wS(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function ap(t,e,r){if(!t.kty.includes(e.kty))throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function ii(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),qO(t,e,r),t}var Xu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function bS(t,e){let r=t.byteLength<<3;if(r!==e)throw new U(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var Cme=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function UH(t,e){if(e.length<<3!==t.ivBits)throw new U("Invalid Initialization Vector length")}async function LH(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(ra(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function FH(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Ome(t,e,r,o,n){let[i,s,a]=await LH(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=hn(n,o,c,MO(n.length*8)),l=await FH(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Nme(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function Dme(t,e,r,o,n,i){let[s,a,c]=await LH(t,e,"decrypt"),u=hn(i,o,r,MO(i.length*8)),l=await FH(a,u,c);try{if(await Nme(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new ec}async function _S(t,e,r,o,n){if(!nc(r)&&!(r instanceof Uint8Array))throw new TypeError(ra(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?UH(t,o):o=Cme(t),r instanceof Uint8Array&&bS(r,t.cekBits),t.cbc)return Ome(t,e,r,o,n);let i=await ii(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function xS(t,e,r,o,n,i){if(!nc(e)&&!(e instanceof Uint8Array))throw new TypeError(ra(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new U("JWE Initialization Vector missing");if(!n)throw new U("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new U("Invalid Authentication Tag length");if(UH(t,o),e instanceof Uint8Array&&bS(e,t.cekBits),t.cbc)return Dme(t,e,r,o,n,i);let s=await ii(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,hn(r,n)))}catch{throw new ec}}function cg(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var zme=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],jme=[[],["deriveBits"]],IS=[[],[]];function SS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:zme,ops:["wrapKey","unwrapKey"]}}function ES(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:jme,ops:[void 0,"deriveBits"]}}function cp(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:IS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function BO(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:IS,ops:["deriveBits","deriveBits"]}}var na=cg({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:IS,ops:["encrypt","decrypt"]},"RSA-OAEP":SS(1),"RSA-OAEP-256":SS(256),"RSA-OAEP-384":SS(384),"RSA-OAEP-512":SS(512),"ECDH-ES":ES("direct-key-agreement"),"ECDH-ES+A128KW":ES("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":ES("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":ES("key-agreement-with-key-wrapping"),A128KW:cp(128),A192KW:cp(192),A256KW:cp(256),A128GCMKW:cp(128,!0),A192GCMKW:cp(192,!0),A256GCMKW:cp(256,!0),"PBES2-HS256+A128KW":BO(),"PBES2-HS384+A192KW":BO(),"PBES2-HS512+A256KW":BO()}),Mme=["encrypt","decrypt"];function up(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:IS,ops:Mme,cekBits:t,ivBits:e?128:96,cbc:e}}var Ume=cg({A128GCM:up(128),A192GCM:up(192),A256GCM:up(256),"A128CBC-HS256":up(256,!0),"A192CBC-HS384":up(384,!0),"A256CBC-HS512":up(512,!0)});function VH(t,e){throw new dt(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function si(t){return(typeof t=="string"?na[t]:void 0)??VH("alg","Algorithm")}function ai(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function Yu(t){return(typeof t=="string"?Ume[t]:void 0)??VH("enc","Encryption Algorithm")}function qH(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");VO(t,e)}async function Lme(t,e,r){let o=await ii(e,si(t).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 Fme(t,e,r){let o=await ii(e,si(t).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 BH(t,e,r){qO(e,si(t).subtle,r),sp(t,e)}async function KH(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new U("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new U("PBES2 Count Input must be a positive integer");let n=hn(Ir(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await ii(o,si(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KO(t){return hn(cS(t.length),t)}async function Vme(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await uS("sha256",hn(cS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function ZH(t,e,r,o,n=new Uint8Array,i=new Uint8Array){qH(t),qH(e,"deriveBits");let s=hn(KO(Ir(r)),KO(n),KO(i),cS(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return Vme(a,o,s)}function WH(t){yS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new dt("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function kS(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new U(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return Dn(r,e,U)}}function JH(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new U('JOSE Header "apu" and "apv" values must be distinct')}}function qme(t){if(t===void 0)throw new U("JWE Encrypted Key missing")}function HH(t){if(t!==void 0)throw new U("Encountered unexpected JWE Encrypted Key")}function Hme(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function GH(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return HH(o),r;let c=a==="direct-key-agreement";switch(c?HH(o):qme(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Yt(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(h=>Object.hasOwn(u,h)))throw new U('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');WH(r);let l=await ap(t,u),d=kS(n,"apu"),f=kS(n,"apv");JH(d,f);let p=await ZH(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return yS(r),BH(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new U('JOSE Header "p2c" (PBES2 Count) missing or invalid');Hme(i);let u=i??1e4;if(n.p2c>u)throw new U('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new U('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=Dn(n.p2s,"p2s",U);r=await KH(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new U('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new U('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=Dn(n.iv,"iv",U),l=Dn(n.tag,"tag",U);if(u.byteLength!==12)throw new U("Invalid Initialization Vector length");if(l.byteLength!==16)throw new U("Invalid Authentication Tag length");return xS(Yu(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Fme(s.slice(-6),r,o)}async function $S(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=ai(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await oi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Xu(e):void 0;l&&bS(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{WH(u);let{apu:p,apv:h}=i;p!==void 0&&Yn(p,'"apu"'),h!==void 0&&Yn(h,'"apv"');let g=p??kS(o,"apu"),y=h??kS(o,"apv");JH(g,y);let w;i.epk!==void 0?w=await oi(t,i.epk,"decrypt"):w=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,_=w;if(!_.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');_=await b.getPublicKey(w,[])}let{x:I,y:$,crv:C,kty:B}=await b.exportKey("jwk",_),Q=a==="direct-key-agreement",we=await ZH(u,w,Q?e.alg:s,Q?e.cekBits:parseInt(s.slice(-5,-2),10),g,y),xe={x:I,crv:C,kty:B};if(B==="EC"&&(xe.y=$),f={epk:xe},p!==void 0&&(f.apu=Nt(p)),h!==void 0&&(f.apv=Nt(h)),Q)return[we,void 0,f];u=we;break}case"RSA-OAEP":{yS(u),BH(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:h=crypto.getRandomValues(new Uint8Array(16))}=i;u=await KH(h,s,p,u),f={p2c:p,p2s:Nt(h)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let h=await _S(Yu(s.slice(0,-2)),l,u,p,new Uint8Array);d=h.ciphertext,f={iv:Nt(h.iv),tag:Nt(h.tag)}}}if(d??=await Lme(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,f]}function AS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new dt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new U('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function XH(t){if(typeof globalThis[t]>"u")throw new dt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function YH(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.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 U("Decompressed plaintext exceeded the configured limit")}return hn(...n)}async function QH(t){return XH("CompressionStream"),YH(new CompressionStream("deflate-raw"),t)}async function eB(t,e){return XH("DecompressionStream"),YH(new DecompressionStream("deflate-raw"),t,e)}function tB(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new U("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new U("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new U("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new U("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new U("JWE AAD incorrect type");if(s!==void 0&&!Yt(s))throw new U("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function rB(t){let e,r;try{let{header:o}=t;if(Yt(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function nB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new U("JWE Encrypted Key incorrect type");if(r!==void 0&&!Yt(r))throw new U("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new U("JOSE Header missing")}function ZO(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=ip(e,U,"JWE Protected Header is invalid")),[s,Dn(r,"ciphertext",U),o!==void 0?Dn(o,"iv",U):void 0,n!==void 0?Dn(n,"tag",U):void 0,dS((e??"")+(i!==void 0?`.${i}`:""),"aad",U)]}function TS(t){return[t&&ag("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&ag("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function WO(t,e,r,o=ZO(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!tc(n,u,l))throw new U("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,h,g,y,w]=e,{encrypted_key:b}=t;rc(U,fS,g,n,f),AS(f,n);let{alg:_,enc:I}=f;if(typeof _!="string"||!_)throw new U("missing JWE Algorithm (alg) in JWE Header");let $=na[_];if(b===""&&(!$||!ai($)))throw new U("JWE Encrypted Key incorrect type");let C=$?.mode==="integrated-encryption";if(!C&&(typeof I!="string"||!I))throw new U("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(_)||!p&&_.startsWith("PBES2"))throw new Wu('"alg" (Algorithm) Header Parameter value not allowed');let B;if(C){if(I!==void 0)throw new U('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new U("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new U("JWE Authentication Tag must be empty for integrated encryption")}else{if(h&&!h.has(I))throw new Wu('"enc" (Encryption Algorithm) Header Parameter value not allowed');B=Yu(I)}let Q;if(b!==void 0)try{Q=Dn(b,"encrypted_key",U)}catch(Ce){if(!$||!ai($))throw Ce;Q=new Uint8Array}let we=!1;typeof r=="function"&&(r=await r(n,t),we=!0);let xe=$??si(_);ai(xe)&&Q===void 0&&(Q=new Uint8Array);let Xe=await oi(xe.mode==="direct-encryption"?B:xe,r,"decrypt"),re;if(xe.mode==="integrated-encryption")re=await xe.decrypt(Xe,Q,i,c,n,f);else{let Ce=B,J;try{J=await GH(xe,Ce,Xe,Q,f,y),ai(xe)&&J instanceof Uint8Array&&J.byteLength<<3!==Ce.cekBits&&(J=Xu(Ce))}catch(Ct){if(Ct instanceof TypeError||Ct instanceof U||Ct instanceof dt)throw Ct;J=Xu(Ce)}re=await xS(Ce,J,i,s,a,c)}if(f.zip==="DEF"){let Ce=w??25e4;if(Ce===0)throw new dt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ce!==1/0&&(!Number.isSafeInteger(Ce)||Ce<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");re=await eB(re,Ce).catch(J=>{throw J instanceof U?J:new U("Failed to decompress plaintext",{cause:J})})}return{plaintext:re,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:Dn(d,"aad",U)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...we&&{key:Xe}}}async function oB(t,e,r){if(t instanceof Uint8Array&&(t=op.decode(t)),typeof t!="string")throw new U("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new U("Invalid Compact JWE");return WO({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function ug(t,e,r){return oB(t,TS(r),e)}async function JO(t,e,r){if(!Yt(t))throw new U("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new U("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Yt))throw new U("JWE Recipients missing or incorrect type");if(!n.length)throw new U("JWE Recipients has no members");let i,s,a;try{i=TS(r),s=tB(t),a=ZO(s)}catch{throw new ec}let c=n.map(u=>rB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?na[l]:void 0;if(d&&!ai(d))throw new U(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return nB(l),await WO(l,i,e,a)}catch{}throw new ec}function PS(t,e,r){if(!tc(t,e,r))throw new U("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function GO(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new U("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Yn(s,"JWE Additional Authenticated Data"),a!==void 0&&Yn(a,"JWE Content Encryption Key"),c!==void 0&&Yn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Gu(U,o)[0],t[1]=o),n!==void 0&&(n=Gu(U,n)[0],t[2]=n),!r&&i!==void 0&&(i=Gu(U,i)[0],t[3]=i),u!==void 0&&!Yt(u))throw new TypeError("JWE Key Management Parameters must be an object");PS(o,n,i);let d={...o,...n,...i};mS(U,o),rc(U,fS,l,o,d),AS(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new U('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=na[f];if(h?.mode==="integrated-encryption"){if(p!==void 0)throw new U('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 ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,h]}if(typeof p!="string"||!p)throw new U('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,Yu(p),h]}async function XO(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,h]=t,g=a,y=c,w=i??si(o.alg),b,_,I;w.mode==="integrated-encryption"?I=await oi(w,r,"encrypt"):[I,b,_]=await $S(w,n,r,o,d,p),_&&(h?y=y?{...y,..._}:_:g=g?{...g,..._}:_,PS(g,y,u));let $=g?Nt(JSON.stringify(g)):"",C=l?.byteLength?Nt(l):void 0,B=Ir(C?`${$}.${C}`:$),Q=s;o.zip==="DEF"&&(Q=await QH(Q).catch(Ce=>{throw new U("Failed to compress plaintext",{cause:Ce})}));let we,xe,Xe;w.mode==="integrated-encryption"?[b,we]=await w.encrypt(I,Q,B,g,o,p):{ciphertext:we,tag:xe,iv:Xe}=await _S(n,Q,I,f,B);let re={ciphertext:Nt(we)};return Xe&&(re.iv=Nt(Xe)),xe&&(re.tag=Nt(xe)),b?.byteLength&&(re.encrypted_key=Nt(b)),C&&(re.aad=C),g&&(re.protected=$),u&&(re.unprotected=u),y&&(re.header=y),re}async function iB(t,e,r){return XO(t,GO(t,r),e)}function sB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var YO=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return bo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return bo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},lg=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new YO(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return bo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return bo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new U("at least one recipient must be added");Yn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let h of this.#t){let[g,y,w,b]=h.state,_=[this.#e,o,g,n,this.#o,void 0,void 0,y,b,e],I=GO(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,I,w]);let[{alg:$,enc:C},,B]=I;if(e&&B&&!ai(B))throw new U(`"${$}" alg may only have a single recipient`);if(!r)r=C;else if(r!==C)throw new U('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,h]of i)h[2]??=si(h[0].alg);let[s,a,c]=i[0],u=e?Xu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await XO(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let h=1;h<i.length;h++){let[g,[y,w,b],_]=i[h],I=g[2],[,$,C]=await $S(b,w,_,y,u,g[7]),B={encrypted_key:Nt($)};if(I||C){let Q={...I,...C};C&&PS(g[1],Q,g[3]),B.header=Q}p.recipients.push(B)}return p}};var dg=[["verify"],["sign"]];function QO(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:dg}}function lp(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:dg,minRsaBits:2048}}function eN(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:dg}}function aB(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:dg}}function tN(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:dg}}var rN=cg({HS256:QO(256),HS384:QO(384),HS512:QO(512),RS256:lp(256),RS384:lp(384),RS512:lp(512),PS256:lp(256,32),PS384:lp(384,48),PS512:lp(512,64),ES256:eN("P-256",256),ES384:eN("P-384",384),ES512:eN("P-521",512),EdDSA:aB(),Ed25519:aB(),"ML-DSA-44":tN(44),"ML-DSA-65":tN(65),"ML-DSA-87":tN(87)});function RS(t){let e=typeof t=="string"?rN[t]:void 0;if(!e)throw new dt(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function cB(t){return[t&&ag("algorithms",t.algorithms),t?.crit]}function Bme(t){return t===void 0?{}:ip(t,At,"JWS Protected Header is invalid")}function Kme(t){try{return Ir(t)}catch{throw new At("JWS Compact Serialization payload must use only ASCII characters")}}async function Zme(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Bme(i);if(!tc(c,s))throw new At("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=hS(c,rc(At,pS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new At('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new Wu('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new At("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new At("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let h=RS(d),g=hn(i!==void 0?Ir(i):new Uint8Array,Ir("."),typeof f=="string"?e[2]??=dS(f,"payload",At):f),y=Dn(t.signature,"signature",At),w=await oi(h,r,"verify"),b=await ii(w,h.subtle,"verify");h.minRsaBits&&sp(h.alg,b);let _=!1;try{_=await crypto.subtle.verify(h.signing,b,y,g)}catch{}if(!_)throw new lS;let I={payload:typeof f=="string"?Dn(f,"payload",At):f};return i!==void 0&&(I.protectedHeader=c),s!==void 0&&(I.unprotectedHeader=s),p?[{...I,key:w},l]:[I,l]}async function uB(t,e,r){if(t instanceof Uint8Array&&(t=op.decode(t)),typeof t!="string")throw new At("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new At("Invalid Compact JWS");return Zme({payload:n,protected:o,signature:i},e,r,Kme)}async function nN(t,e,r){let[o]=await uB(t,cB(r),e);return o}var dp=class{#e;constructor(e){Yn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return bo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return bo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return bo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return bo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return sB(await iB([...this.#e],e,r))}};async function Wme(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=Gu(At,n);n=w[0],a=Nt(w[1])}if(i!==void 0&&(i=Gu(At,i)[0]),!n&&!i)throw new At("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!tc(n,i))throw new At("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};mS(At,n);let u=hS(n,rc(At,pS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new At('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=RS(l),f="",p=o,h;if(u){let w=t[4];w?(f=w[0]??=Nt(o),p=w[1]??=Ir(f)):(f=Nt(o),h=np.encode(`${a}.${f}`))}h??=hn(Ir(a),Ir("."),p);let g=await ii(await oi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&sp(d.alg,g);let y={signature:Nt(new Uint8Array(await crypto.subtle.sign(d.signing,g,h))),payload:f};return n&&(y.protected=a),i&&(y.header=i),[y,u]}async function lB(t,e,r,o,n){let[i]=await Wme([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var pg=class{#e;#t;constructor(e){Yn(e,"payload"),this.#e=e}setProtectedHeader(e){return bo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return lB(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var oN='"alg" (Algorithm)';function iN(t='JWK "alg" (Algorithm) Parameter'){throw new dt(`Invalid or unsupported ${t} value`)}function fg(t,e){return(typeof t=="string"?rN[t]??na[t]:void 0)??iN(e)}async function oc(t){if(LO(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Nt(t)};if(!nc(t))throw new TypeError(ra(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var oa=(t,e)=>{if(typeof t!="string"||!t)throw new sg(`${e} missing or invalid`)};async function sN(t,e){let r;if(Yt(t)){if(r=vS(t),typeof r.kty!="string")throw new TypeError(ra(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(FO(t))r=vS(await oc(t));else throw new TypeError(ra(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":oa(r.alg,'"alg" (Algorithm) Parameter'),oa(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":oa(r.crv,'"crv" (Curve) Parameter'),oa(r.x,'"x" (X Coordinate) Parameter'),oa(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":oa(r.crv,'"crv" (Subtype of Key Pair) Parameter'),oa(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":oa(r.e,'"e" (Exponent) Parameter'),oa(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 sg('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new dt('"kty" (Key Type) Parameter missing or unsupported')}let n=Ir(JSON.stringify(o));return Nt(await uS(e,n))}async function _o(t,e,r){if(!Yt(t))throw new TypeError("JWK must be an object");let o=HO(t),n=wS(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)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 Ju(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return ap(fg(e),o,n)}case"RSA":case"EC":case"OKP":return ap(fg(e),o,n);default:throw new dt('Unsupported "kty" (Key Type) Parameter value')}}function aN(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return ip(e,TypeError,r)}function Jme(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new dt("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function mg(t,e){let r=wS(e?.extractable),o=fg(t,oN);o.secret&&iN(oN);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new dt("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&&e?.crv!==void 0&&e.crv!==o.crv)throw new dt(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jme(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var mB=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),hB=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),dB=m.string().min(1).max(128),pB=m.string().min(1).max(16384),Gme=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:dB,secretAccessKey:pB}).strict(),m.object({kind:m.literal("session"),accessKeyId:dB,secretAccessKey:pB,sessionToken:m.string().min(1).max(16384),expiresAt:m.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),m.object({kind:m.literal("environment")}).strict()]),Xme=m.object({arn:hB,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),ia=m.object({authentication:Gme,region:mB,role:Xme.optional()}).strict(),CS=m.object({accountId:m.string().regex(/^\d{12}$/),principalId:m.string().min(1).max(256),arn:m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),OS=ia.extend({sourceIdentity:CS.optional(),identity:CS.optional()}).strict();function pp(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function fB(t){return{...t,arn:pp(t.arn)}}function gB(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:fB(t.sourceIdentity)}:{},...t.identity?{identity:fB(t.identity)}:{}}}var NS=m.object({authentication:m.enum(["access_key","session","environment"]),region:mB,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:hB.optional(),expiresAt:m.number().int().positive().optional()}).strict();function yB(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var vB=m.object({method:m.enum(["GET","POST","PUT","DELETE","PATCH"]),path:m.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),hg=m.object({account:m.string().min(1),identities:m.array(m.string()),user:m.string().nullable(),description:m.string().nullable(),roles:m.array(m.string()).nullable(),credentialId:m.number().int().positive(),rules:m.array(vB),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function wB(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return vB.parse({method:r[1],path:r[2]})})}typeof window<"u"&&m.config({jitless:!0});var x=m.uuid(),ne=m.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),be=m.iso.datetime(),ur=m.json(),pt=m.record(m.string(),ur),_B=m.enum(["ja","en"]),xB=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var SB=m.enum(["variable","connection","service","method","app","object","environment","function","keyring"]),Kr=m.object({kty:m.literal("EC"),crv:m.literal("P-256"),x:m.string().min(40).max(50),y:m.string().min(40).max(50)}).strict(),Yme=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:x}).strict(),MS=m.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return Yme.safeParse(aN(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Qn=m.object({protected:m.string().max(2048),iv:m.string().max(64),ciphertext:m.string().max(2e6),tag:m.string().max(64),aad:m.string().max(2048).optional(),recipients:m.array(m.object({encrypted_key:m.string().max(2048),header:m.object({kid:x,epk:Kr.optional(),alg:m.string().optional()}).passthrough()})).min(1).max(100)}).strict(),uVe=m.object({id:x,name:ne,publicKey:Kr}),ic=m.object({id:x,name:ne,owner:m.object({id:x,name:ne}).nullable(),createdAt:be,permissions:m.array(xB),createKinds:m.array(SB),publicKey:Kr.nullable()}),EB=m.object({id:x,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:be,lastUsedAt:be.nullable(),expiresAt:be.nullable(),canOpen:m.boolean()}),IB=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),Qme=m.object({subjectId:x,relation:IB,objectId:x}).strict(),lVe=Qme.extend({objectType:m.enum(["principal",...SB.options]),subjectName:ne,objectName:ne,createdAt:be}),dVe=m.object({error:m.object({code:m.string(),message:m.string(),details:ur.optional()})}),pVe=m.object({ok:m.literal(!0)}),ehe=m.object({value:m.string().min(1).max(200),label:m.string().min(1).max(200),values:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).default({})}).strict(),US=m.object({name:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:m.string(),secret:m.boolean().optional(),inputType:m.enum(["text","password"]).optional(),required:m.boolean().optional(),placeholder:m.string().optional(),note:m.string().optional(),pattern:m.string().optional(),choices:m.array(ehe).min(1).max(100).optional(),defaultValue:m.string().max(1e3).optional(),when:m.object({field:m.string(),values:m.array(m.string()).min(1)}).strict().optional(),visibility:m.enum(["application","connection"]).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),cN=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),the=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.union([m.string(),m.array(m.union([m.string().max(8192),m.object({pointer:m.string().max(1e3)}).strict()])).min(1).max(32)])),uN=m.object({values:m.array(m.object({id:m.string(),name:m.string(),description:m.string().optional()})).optional(),default:m.array(m.string()).default([]),required:m.array(m.string()).optional(),separator:m.string().default(" "),docs:m.url().optional()}),Qu=m.string().min(1).max(4096),zS=m.union([m.string(),m.array(m.string()).min(1)]),rhe=m.object({browserTokenExchange:m.enum(["available","unavailable","unknown"]).optional(),application:m.enum(["required","implicit"]).default("required"),grantType:m.enum(["authorization_code","client_credentials"]).optional(),issuer:m.url().optional(),registrationUrl:m.url().optional(),authorizeUrl:Qu.optional(),tokenUrl:Qu,identity:m.object({url:Qu.optional(),from:m.enum(["token","app"]).optional(),method:m.enum(["GET","POST"]).default("GET"),id:zS.default("/id"),name:zS.default("/name"),headers:m.record(m.string(),m.string()).default({})}).optional(),revoke:m.object({url:Qu,style:m.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:m.enum(["body","basic","none"]).optional(),tokenOnly:m.literal(!0).optional()}).optional(),clientAuth:m.enum(["body","basic","none"]).default("body"),pkce:m.boolean().default(!0),tokenFormat:m.enum(["form","json"]).default("form"),okPointer:m.string().optional(),authorizeParams:m.record(m.string(),m.string()).default({}),tokenParams:m.record(m.string(),m.string()).default({}),defaults:m.record(m.string(),m.string()).default({}),scopes:uN.default({default:[],separator:" "}),fields:m.array(US).default([]),outputs:cN.default({ACCESS_TOKEN:"/accessToken"}),adapter:m.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:m.array(m.string()).default([]),hint:m.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),nhe=m.object({fields:m.array(US).min(1),outputs:the,resolver:m.literal("vultr-role").optional(),bindFields:m.boolean().optional(),constants:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).optional(),identity:m.object({url:Qu,headers:m.record(m.string(),m.string()),id:zS,name:zS}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),lN=m.enum(["oauth","token","aws","ovh","approval"]),ohe=m.object({hint:m.string().optional()}).strict(),ihe=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:Qu,fields:m.array(US).min(1),scopes:uN.default({default:[],separator:`
|
|
129
|
-
`}),outputs:cN,hint:m.string().optional()}).strict(),fp=m.string().regex(/^[A-Z_][A-Z0-9_]*$/),bB=m.union([m.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),m.object({output:fp}).strict()]),LS=m.object({urlField:m.string().min(1).max(100).optional(),authentication:m.discriminatedUnion("kind",[m.object({kind:m.literal("none")}).strict(),m.object({kind:m.literal("bearer"),token:fp}).strict(),m.object({kind:m.literal("basic"),username:fp,password:fp}).strict(),m.object({kind:m.literal("header"),name:bB,value:fp}).strict(),m.object({kind:m.literal("query"),name:bB,value:fp}).strict()])}).strict(),vg={name:ne,docs:m.url().optional(),console:Qu.optional(),http:LS.optional(),preparation:m.object({scopeSelection:m.enum(["optional","required","hidden"]).default("optional"),instructions:m.array(m.union([m.string().max(2e3),m.object({ja:m.string().max(2e3),en:m.string().max(2e3)}).strict()])).max(10).default([]),docs:m.boolean().default(!1)}).strict().optional()},FS=m.object({...vg,kind:m.literal("oauth"),config:rhe}).strict(),VS=m.object({...vg,kind:m.literal("token"),config:nhe}).strict(),qS=m.object({...vg,kind:m.literal("aws"),config:ohe}).strict(),HS=m.object({...vg,kind:m.literal("ovh"),config:ihe}).strict(),BS=m.object({...vg,kind:m.literal("approval"),config:m.object({adapter:m.literal("runpod-flash"),fields:m.array(US).default([]),scopes:uN.default({default:[],separator:" "}),outputs:cN,hint:m.string().optional()}).strict()}).strict(),sc=m.discriminatedUnion("kind",[FS,VS,qS,HS,BS]),gg={id:m.string().min(1),builtin:m.boolean(),availability:m.enum(["ready","app-required","unavailable"]),defaultName:ne,registration:m.object({kind:m.enum(["input","authorization"]),device:m.enum(["browser","cli"]),browserExchange:m.enum(["available","unavailable","unknown"]),tokenAlternatives:m.array(m.string())}).strict()},wg=m.discriminatedUnion("kind",[FS.extend(gg),VS.extend(gg),qS.extend(gg),HS.extend(gg),BS.extend(gg)]),yg=m.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),dN=m.object({name:ne,logo:m.string().regex(/^[a-z0-9-]+$/).optional(),api:m.url().optional(),docs:m.url().optional(),console:m.url().optional(),targets:m.array(m.object({id:yg,name:ne,api:m.url().optional(),methods:m.array(yg).min(1)}).strict()).max(32).optional()}).strict(),she=dN.extend({methods:m.record(yg,m.string().min(1))}).strict(),kB=dN.extend({methods:m.record(yg,m.union([m.string().min(1),sc]))}).strict(),fVe=dN.extend({id:m.string(),builtin:m.boolean(),methods:m.record(yg,wg)}),$B=m.object({id:x,output:m.string().min(1).max(100).optional()}).strict(),AB=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),pN=m.object({name:m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:$B,format:m.enum(["text","file","json"]).default("text"),pointer:m.string().optional()}).strict(),ahe=m.object({pointer:m.string().max(500),parts:m.array(m.union([m.string().max(8192),$B])).min(1).max(32)}).strict(),ac=m.object({url:m.string().min(1).max(4096).optional(),connectionId:x.optional(),method:m.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:m.record(m.string(),m.string().max(8192)).default({}),body:m.string().max(1e6).optional(),json:ur.optional(),form:m.record(m.string(),m.string()).optional(),bindings:m.array(ahe).max(32).default([])}).strict().refine(t=>!!(t.url||t.connectionId),{message:"Choose a connection or enter a destination URL."}),cc=m.object({command:m.array(m.string().max(8192)).min(1).max(100),stdin:m.string().max(1e6).optional(),timeoutSeconds:m.number().int().min(1).max(3600).default(60),inputs:m.array(pN).max(32).default([])}).strict(),TB=m.discriminatedUnion("kind",[cc.omit({stdin:!0}).extend({kind:m.literal("command")}).strict(),m.object({kind:m.literal("http"),request:ac,responseFormat:m.enum(["text","json"]).default("json")}).strict()]),eo=m.object({description:m.string().max(2e3).default(""),program:TB,parameters:m.array(m.object({name:m.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:m.string().max(100),type:m.enum(["string","number","boolean","json"]).default("string"),required:m.boolean().default(!0),default:ur.optional()}).strict()).max(32).default([]),result:m.enum(["text","json"]).default("json")}).strict(),el=m.object({expiresAt:be.nullable().default(null)}).strict(),PB=m.object({version:m.number().int().nonnegative(),environmentId:x.nullable(),inputAccess:el,state:m.enum(["publication_required","unconfigured","configured","approval_required","unavailable","expired"])}).strict(),sa={id:x,ownerId:x,name:ne,createdAt:be,updatedAt:be,version:m.number().int().positive(),permissions:m.array(xB)},che=m.enum(["starting","running","stopping","stopped","failed"]),uhe=m.enum(["manual","idle","timeout","quota","capacity","payment"]),lhe=m.object({state:m.enum(["pending","failed","complete"]),error:m.string().nullable()}),dhe=m.object({idleSeconds:m.number().int().min(60).max(2147483647).nullable().default(null),maxSeconds:m.number().int().min(60).max(2147483647).nullable().default(null)}).strict(),RB=m.object({size:m.enum(["small","medium","large"]).default("small"),lifetime:dhe.default({idleSeconds:null,maxSeconds:null}),ssh:sS.optional()}).strict(),fN={recipients:m.array(x).default([]),executors:m.array(x).default([]),custodyRevision:m.number().int().positive().nullable().default(null)},phe=m.object({...sa,kind:m.literal("variable"),data:m.object({...fN,bytes:m.number().int().nonnegative()})}),fhe=m.object({...sa,kind:m.literal("connection"),data:m.object({...fN,methodId:m.string(),fields:m.record(m.string(),m.string()).default({}),settings:m.array(m.object({name:m.string(),label:m.string(),value:m.string()})).default([]),methodName:m.string(),methodKind:lN,http:LS.optional(),services:m.array(m.object({id:m.string(),name:ne})).default([]),account:m.string(),accountId:m.string().nullable().default(null),accountVerified:m.boolean().default(!1),scopes:m.array(m.string()),scopesStatus:m.enum(["unknown","requested","reported"]).default("unknown"),outputs:m.array(m.string()),state:m.enum(["ready","reconnect","review","disconnecting","uncertain"]),revocable:m.boolean().default(!1),appId:x.nullable(),generation:x.optional(),authorizationDigest:m.string().optional(),aws:NS.optional(),ovh:hg.optional()})}),mhe=m.object({...sa,kind:m.literal("service"),data:she}),hhe=m.object({...sa,kind:m.literal("method"),data:sc}),ghe=m.object({...sa,kind:m.literal("app"),data:m.object({...fN,methodId:m.string(),clientId:m.string(),fields:m.record(m.string(),m.string()).default({}),generation:x.optional()})}),yhe=m.object({...sa,kind:m.literal("object"),data:m.object({size:m.number().int().nonnegative(),contentType:m.string()})}),vhe=m.object({...sa,kind:m.literal("environment"),data:RB.extend({executorId:x.optional(),operatorId:x.optional(),driver:m.enum(["attached","managed"]).optional(),capabilities:m.array(m.string()).optional(),isolation:m.enum(["process","container"]).optional(),manifestDigest:m.string().optional(),processes:m.object({workingDirectory:m.string()}).optional(),ssh:zO.optional(),awsPrincipal:m.string().optional(),state:che,connected:m.boolean(),deletion:lhe.optional(),startedAt:be.nullable(),stoppedAt:be.nullable(),stopReason:uhe.nullable().default(null),lastActiveAt:be,error:m.string().nullable()})}),KS=m.object({...sa,kind:m.literal("function"),data:eo.omit({program:!0}).extend({program:TB.optional()})}),whe=m.object({...sa,kind:m.literal("keyring"),data:m.object({revision:m.number().int().positive(),signature:m.string()})}),Ut=m.discriminatedUnion("kind",[phe,fhe,mhe,hhe,ghe,yhe,vhe,KS,whe]),mVe=m.discriminatedUnion("kind",[m.object({kind:m.literal("service"),name:ne,definition:kB}).strict(),m.object({kind:m.literal("method"),name:ne,definition:sc}).strict(),m.object({kind:m.literal("environment"),name:ne.optional(),options:RB}).strict()]),hVe=m.object({version:m.number().int().positive(),name:ne.optional(),definition:m.union([kB,sc]).optional()}).strict(),ci=m.object({name:m.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:pt}).strict(),ZS=ci.extend({inputs:m.array(m.object({pointer:m.string(),label:m.string().min(1).max(100),secret:m.boolean().default(!1),multiline:m.boolean().default(!1),site:m.url().optional()}).strict()).max(16).default([])}),jS=m.object({ja:m.string(),en:m.string()}).strict(),mN=ZS.extend({title:jS,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:m.object({required:m.boolean(),reason:jS.nullable()}).strict()}),CB=m.object({to:x.optional(),executionId:x.optional(),message:m.string().max(1e3).default(""),operations:m.array(ZS).min(1).max(8).optional(),expiresInMinutes:m.number().int().min(1).max(1440).default(30)}).strict().superRefine((t,e)=>{!!t.executionId==!!t.operations&&e.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),DS=m.object({id:x,name:ne}),OB=m.discriminatedUnion("kind",[m.object({kind:m.literal("line"),subject:DS,relation:IB,object:DS}),m.object({kind:m.literal("transfer"),item:DS,to:DS})]),WS=m.object({id:x,executionId:x,from:ic.pick({id:!0,name:!0}),to:ic.pick({id:!0,name:!0}).nullable(),message:m.string(),purpose:m.enum(["input","approval"]),state:m.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:be,expiresAt:be,url:m.url(),code:m.string().optional(),returnUrl:m.url().nullable(),refreshUrl:m.url().nullable(),canRespond:m.boolean(),canCancel:m.boolean()}),gVe=m.object({id:x,name:ne,publicKey:Kr,state:m.enum(["pending","approving","approved"]),principalId:x.nullable(),createdAt:be,expiresAt:be}),yVe=m.object({available:m.boolean(),required:m.boolean(),active:m.boolean(),payer:ic.pick({id:!0,name:!0}).nullable()}),vVe=m.object({storageBytes:m.number().nonnegative(),storageLimit:m.number().positive(),computeSeconds:m.number().nonnegative(),computeLimit:m.number().positive(),month:m.string()}),wVe=m.object({id:m.string(),actorId:x.nullable(),action:m.string(),targetId:x.nullable(),createdAt:be,details:pt}),bVe=m.object({returnUrl:m.url().optional(),refreshUrl:m.url().optional()}).strict(),lr=t=>m.object({items:m.array(t),next:m.string().nullable().default(null)}),_Ve=m.object({id:x}),xVe=m.object({owner:x}),bhe=m.object({limit:m.coerce.number().int().min(1).max(200).default(100),after:m.string().optional()}),SVe=bhe.extend({object:x.optional(),subject:x.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var _he=m.object({email:m.boolean(),environments:m.boolean(),ssh:m.boolean(),objects:m.boolean(),payments:m.boolean()}),JS=m.object({principal:ic.nullable(),credentialId:x.nullable(),wrappedKey:MS.nullable(),requestId:x.nullable(),server:m.object({name:ne}),features:_he,principals:m.array(ic)}),$Ve=m.object({email:m.email().max(254),returnTo:m.string().max(2048).optional(),locale:_B.default("ja"),principalId:x.optional()}).strict(),AVe=m.object({intent:m.enum(["register","authenticate"]),name:ne.optional(),principalId:x.optional(),credentialId:x.optional(),returnTo:m.string().max(2048).optional()}).strict(),TVe=m.object({challengeId:x,credential:m.json(),publicKey:Kr.optional(),existingPublicKey:Kr.optional(),wrappedKey:MS.optional()}).strict();var xhe=new TextEncoder,She=new TextDecoder,bg="ECDH-ES+A256KW",hN="A256GCM",Ye=t=>xhe.encode(t),gn=t=>She.decode(t);function aa(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function GS(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function XS(){let t=await mg(bg,{crv:"P-256",extractable:!0});return{publicKey:Kr.parse(await oc(t.publicKey)),privateKey:await oc(t.privateKey)}}async function uc(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new lg(t).setProtectedHeader({enc:hN}).setAdditionalAuthenticatedData(Ye(r));for(let n of e)o.addRecipient(await _o(n.publicKey,bg)).setUnprotectedHeader({alg:bg,kid:n.id});return Qn.parse(await o.encrypt())}async function xo(t,e,r,o){if(t.aad!==aa(Ye(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await _o(e,bg);return(await JO({...t,recipients:[n]},i,{keyManagementAlgorithms:[bg],contentEncryptionAlgorithms:[hN]})).plaintext}async function Ehe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:Ye("Foundation"),info:Ye("passkey encryption key")},e,256))}async function NB(t,e,r){let o=await ug(t,await Ehe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[hN]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(gn(o.plaintext))}var Dt=m.string().regex(/^[A-Za-z0-9_-]{43}$/),zt=m.string().min(100).max(4e6),DB=Kr.extend({d:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}),_g=m.object({encryption:DB,signing:DB}).strict(),bt=m.object({id:x,principalId:x,generation:m.number().int().positive(),previous:Dt.nullable(),encryption:Kr,signing:Kr}).strict();function P(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,P).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+P(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function mp(t){return sN(Kr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function oe(t){return aa(new Uint8Array(await crypto.subtle.digest("SHA-256",Ye(P(t)))))}async function tl(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",Ye(P(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function zB(){let[t,e]=await Promise.all([XS(),mg("ES256",{crv:"P-256",extractable:!0})]),r=await oc(e.privateKey);return _g.parse({encryption:t.privateKey,signing:r})}function YS(t){return Kr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function jB(t,e){return bt.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:YS(e.encryption),signing:YS(e.signing)})}async function Jt(t,e,r){let o=e instanceof CryptoKey?e:await _o(e,"ES256");return new pg(Ye(P(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Zr(t,e,r,o){if(P(await xg(e,r,o))!==P(t))throw new Error("The signature does not authorize this content.")}async function xg(t,e,r){let o=await nN(t,await _o(Kr.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(P(i)!==n)throw new Error("Sign canonical JSON content.");return i}var ca=m.object({binding:bt,signature:zt}).strict();async function gN(t,e){if(await ua(t),await mp(e.encryption)!==await mp(t.encryption)||await mp(e.signing)!==await mp(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await Jt(t,e.signing,"key-binding")}}async function ua(t){let e=bt.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await mp(e.encryption)===await mp(e.signing))throw new Error("Use separate encryption and signing keys.");await _o(e.encryption,"ECDH-ES+A256KW"),await _o(e.signing,"ES256")}async function QS(t){let{binding:e,signature:r}=ca.parse(t);return await ua(e),await Zr(e,r,e.signing,"key-binding"),e}var MB=m.object({ownerId:x,name:ne,resourceId:x.optional(),version:m.number().int().positive().optional(),environmentIds:m.array(x).max(32).optional()}).strict(),UB=MB.extend({value:m.literal("").optional()}),yN=MB.extend({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}),hp=m.object({ownerId:x,name:ne,definition:eo,resourceId:x.optional(),version:m.number().int().positive().optional()}).strict(),e0=m.object({functionId:x,functionVersion:m.number().int().positive(),version:m.number().int().nonnegative(),environmentId:x.nullable(),inputAccess:el.default({expiresAt:null})}).strict(),vN=m.object({ownerId:x,connectionId:x,environmentId:x}).strict(),LB=m.object({ownerId:x,connectionId:x,version:m.number().int().positive(),users:m.array(x).max(32),expiresAt:m.iso.datetime().optional()}).strict(),FB=m.object({ownerId:x,methodId:m.string().min(1).max(200),connectionId:x.optional(),name:ne.optional(),appId:x.optional(),redirectUri:m.url().optional(),users:m.array(x).max(32).optional(),scopes:m.array(m.string().min(1).max(1e3)).max(200).optional(),methodDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:m.string().max(1e3).optional(),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}).strict(),t0=m.object({ownerId:x,environmentId:x.optional(),operation:m.union([m.object({kind:m.literal("http"),request:ac}).strict(),cc.extend({kind:m.literal("command")}),m.object({kind:m.enum(["http","command"]),programId:x,programDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:m.record(m.string(),ne).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),r0=m.object({name:ci.shape.name,title:jS,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:mN.shape.environment,input:pt}).strict(),VB=m.object({id:x.optional(),operations:m.array(ZS).min(1).max(8),responderId:x.optional(),message:m.string().max(1e3).default(""),expiresInMinutes:m.number().int().min(1).max(1440).default(1440)}).strict(),qB=m.object({values:m.array(pt).max(8).default([]),configuration:m.array(pt).max(8).default([]),code:m.string().max(20).optional()}).strict(),gp=m.object({index:m.number().int().nonnegative(),invocation:ci,approval:m.object({id:x,index:m.number().int().nonnegative()}).strict().optional(),continuation:m.object({kind:m.enum(["connection","run"]),id:x}).strict().nullable()}).strict(),Ee=m.object({id:x,actorId:x,ownerId:x,requests:m.array(x),steps:m.array(m.object({index:m.number().int().nonnegative(),name:ci.shape.name,state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:m.array(m.object({kind:m.enum(["run","function","process"]),id:x}).strict())}).strict()),creator:ic.pick({id:!0,name:!0}),operations:m.array(mN),approval:m.object({requestId:x.nullable(),proposal:OB.nullable()}).strict().nullable(),canContinue:m.boolean(),canCancel:m.boolean(),url:m.url(),code:m.string().optional(),error:m.object({code:m.string(),message:m.string()}).strict().nullable(),index:m.number().int().nonnegative(),state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:m.enum(["approval","input","execution"]).nullable(),waiting:gp.nullable(),results:m.array(ur.nullable()),createdAt:m.iso.datetime(),expiresAt:m.iso.datetime()}).strict(),HB=m.object({id:x,index:m.number().int().nonnegative(),invocation:ci,continuationId:x.optional()}).strict();var vp=m.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ge={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},Ihe=m.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),KB=t=>t===ge.executionResult?14e5:1e6,ie={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},Sg=m.enum([ie.http,ie.command,ie.function,ie.connect,ie.refresh,ie.revoke]);var khe={[ge.value]:[ie.http,ie.command,ie.function],[ge.tokenSet]:[ie.http,ie.command,ie.function,ie.refresh,ie.revoke],[ge.clientCredential]:[ie.connect,ie.refresh,ie.revoke],[ge.executionResult]:[]},lc=t=>khe[t],ZB=t=>lc(t).filter(e=>e===ie.function||e===ie.refresh),wN=t=>t===ge.tokenSet,$he=m.object({id:x,digest:Dt}).strict(),Ahe=m.object({actor:bt,executor:bt,operations:m.array(Sg).min(1).max(6),functionDigests:m.array(Dt).max(100).default([]),origins:m.array(vp).max(100).default([]),callerProgram:m.boolean().default(!1),expiresAt:be}).strict(),The=m.object({function:$he,executor:bt,operations:m.array(Sg).min(1).max(6),expiresAt:be.nullable()}).strict(),Phe=m.union([Ahe,The]);function nl(t,e=Date.now()){return t.expiresAt===null||Date.parse(t.expiresAt)>e}function n0(t){return t.expiresAt===null?1/0:Date.parse(t.expiresAt)}var kr=m.object({format:m.literal(2),origin:vp,id:x,ownerId:x,contentType:Ihe,revision:m.number().int().positive(),authorities:m.array(bt).min(1).max(100),readers:m.array(bt).min(1).max(100),grants:m.array(Phe).max(100),observers:m.array(x).max(100).optional(),producers:m.array(m.object({executor:bt,runId:x,expiresAt:be,materialRevision:m.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),BB=m.object({ownerId:x,authorities:m.array(bt).min(1).max(100)}).strict(),WB=m.object({origin:vp,id:x,revision:m.number().int().positive(),from:BB,to:BB,policyDigest:Dt,previous:Dt.nullable(),signerId:x}).strict(),Rhe=WB.extend({signature:zt}),bN=m.array(Rhe).max(16),Eg=m.object({policy:kr,authorityId:x,signature:zt,lineage:bN.optional()}).strict(),$r=m.object({policy:kr,authorityId:x,authorization:zt,lineage:bN.optional(),materialRevision:m.number().int().positive(),updatedAt:be,creationRunId:x.nullable(),metadata:pt,sealed:Qn,signerId:x,signature:zt}).strict(),rl=t=>({ownerId:t.ownerId,authorities:t.authorities});async function JB(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||P(r.to)!==P(o.from))||o.previous!==(r?await oe(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await Zr(i,n,s.signing,"authority-handoff"),r=o}if(r&&P(r.to)!==P(rl(t)))throw new Error("Use the authorities approved by the latest handoff.")}function _N(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function o0(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=P(rl(t));return r===P(rl(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&P(o.from)===r)}async function GB(t,e,r,o){let n=[...t?.lineage??[]];if(t&&P(rl(t.policy))!==P(rl(e))){if(await ui(t),!t.policy.authorities.some(s=>P(s)===P(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=WB.parse({origin:e.origin,id:e.id,revision:e.revision,from:rl(t.policy),to:rl(e),policyDigest:await oe(e),previous:n.length?await oe(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await Jt(i,o.signing,"authority-handoff")})}return n.length?{lineage:bN.parse(n)}:{}}async function i0(t){let e=kr.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await ua(n);let i=P(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!lc(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==ie.function&&i!==ie.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===ie.http||i===ie.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(ie.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function s0(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function dc(t,e){return P({purpose:"resource",policyDigest:await oe(t),materialRevision:e})}async function ol(t,e,r,o,n,i,s){if(t.byteLength>KB(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await i0(e),c=await GB(s,a,o,n);if(!a.authorities.some(f=>P(f)===P(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await uc(t,s0(a).map(f=>({id:f.id,publicKey:f.encryption})),await dc(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await Jt(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ge.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=$r.parse({...l,signature:await Jt(l,n.signing,"resource")});return await ui(d),d}async function ui(t){let e=$r.parse(t),{signature:r,...o}=e;await i0(e.policy),await JB(e.policy,e.lineage);let n=_N(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await oe(e.policy))throw new Error("The handoff approves a different access policy.");await Zr(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&(e.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(wN(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(ie.refresh)&&nl(u,Date.parse(e.updatedAt)))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Zr(o,r,s.signing,"resource");let a=s0(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(P(a)!==P(c)||e.sealed.aad!==aa(Ye(await dc(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function XB(t,e,r,o,n=t.metadata){let i=await ui(t);if(!wN(i.policy.contentType)||!(i.policy.authorities.some(f=>P(f)===P(r))||i.policy.grants.some(f=>P(f.executor)===P(r)&&f.operations.includes(ie.refresh)&&nl(f))))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await uc(e,s0(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await dc(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await Jt(l,o.signing,"resource")};return await ui(d),d}async function a0(t,e,r,o){let n=await i0(t);if(!n.authorities.some(s=>P(s)===P(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await GB(o,n,e,r),authorityId:e.id,signature:await Jt(n,r.signing,"access-policy")};return await Ig(i),i}async function Ig(t){let e=Eg.parse(t);await i0(e.policy),await JB(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await oe(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await Zr(e.policy,e.signature,o.signing,"access-policy"),e}async function YB(t,e,r,o,n,i){let s=await Ig(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&P(f.executor)===P(o)&&(a.contentType===ge.executionResult||Date.parse(f.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>KB(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await uc(t,s0(a).map(f=>({id:f.id,publicKey:f.encryption})),await dc(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await Jt(l,n.signing,"resource")};return await ui(d),d}async function il(t,e,r){let o=await ui(t);if(!o.policy.readers.some(n=>P(n)===P(e)))throw new Error("This identity cannot reveal the content.");return xo(o.sealed,r,e.id,await dc(o.policy,o.materialRevision))}var Che=m.object({id:x,policyDigest:Dt,materialRevision:m.number().int().positive(),authorizationDigest:Dt.optional()}).strict();async function Ohe(t,e){return e.id===t.policy.id&&e.policyDigest===await oe(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||wN(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var c0=m.object({format:m.literal(2),id:x,origin:vp,ownerId:x,approval:m.object({id:x,index:m.number().int().min(0).max(7)}).strict().optional(),operationContext:HB.optional(),actor:bt,environmentId:x,executor:bt,environmentDigest:Dt,operation:Sg,functionDigest:Dt.nullable(),functionId:x.optional(),operationDigest:Dt,sources:m.array(Che).max(100),resultRecipients:m.array(bt).min(1).max(100),resultApproval:Eg.optional(),createdAt:be,expiresAt:be}).strict(),kg=m.object({intent:c0,signature:zt,sealed:Qn}).strict();async function u0(t,e){return P({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await oe(t)})}async function QB(t,e,r){if(c0.parse(t),await oe(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await uc(Ye(P(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await u0(t,"input"))};return kg.parse({...o,signature:await Jt(o,r.signing,"run")})}async function yp(t,e,r={}){let o=await ui(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await Ohe(o,i))throw new Error("The input changed after this execution was authorized.");if(P(e.actor)===P(e.executor)&&n.readers.some(c=>P(c)===P(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?P(c.actor)===P(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&P(c.executor)===P(e.executor)&&c.operations.includes(e.operation)&&nl(c,r.now)&&n0(c)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===ie.function||e.operation===ie.refresh:e.operation===ie.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||!r.destinationPending&&c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==ie.command&&e.operation!==ie.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function $g(t,e,r,o={}){let n=o.destination;await yp(t,e,{now:o.now,...typeof n=="function"?{destinationPending:!0}:{destination:n}});let i=await xo(t.sealed,r.encryption,e.executor.id,await dc(t.policy,t.materialRevision));return typeof n=="function"&&await yp(t,e,{now:o.now,destination:n(i)}),i}var SN=5,eK=1,Nhe=m.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Dhe=m.object({format:m.literal(3),id:x,origin:vp,ownerId:x,name:ne,executor:bt,operatorId:x,driver:m.literal("attached"),capabilities:m.array(Sg).min(1).max(6),functionVersion:m.number().int().positive().optional(),httpVersion:m.number().int().positive().optional(),resultVersion:m.literal(1).optional(),isolation:m.enum(["process","container"]),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),functionImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:Nhe.optional(),revision:m.number().int().positive()}).strict(),EN=m.object({manifest:Dhe,signature:zt}).strict();async function IN(t){let e=EN.parse(t),{manifest:r}=e;if(await ua(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(ie.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");return await Zr(r,e.signature,r.executor.signing,"environment"),e}async function tK(t,e){let{manifest:r}=await IN(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await oe(r)||P(e.executor)!==P(r.executor)||!r.capabilities.includes(e.operation)||e.operation===ie.function&&r.functionVersion!==SN)throw new Error("This environment does not authorize the requested execution.")}var l0=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),kN=m.object({ok:m.boolean(),result:ur.nullable(),error:m.object({code:m.string().max(100),message:m.string().max(1e3)}).nullable()}).strict(),rK={id:x,intentDigest:Dt,executorId:x,state:m.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:be},nK=m.object({...rK,sealed:Qn,signature:zt}).strict(),oK=m.object({...rK,format:m.literal(2),accessDigest:Dt,proofDigest:Dt,approval:Eg,content:$r,previousDigest:Dt.optional(),previous:nK.optional(),signature:zt}).strict(),d0=m.union([nK,oK]),zhe=m.object({result:kN,proof:zt}).strict(),iK=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function sK(t,e,r,o,n,i){await Ig(n);let s={format:2,id:t.id,intentDigest:await oe(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await oe(n),...i?{previousDigest:await oe(i)}:{}},a=await Jt({...s,resultDigest:await oe(r)},o.signing,"execution-result"),c=Ye(P({result:kN.parse(r),proof:a}));if(c.byteLength>14e5)throw new xN;let u=await YB(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await oe(a)},d=oK.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await Jt(l,o.signing,"receipt")});return await $N(d,t),d}var xN=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function $N(t,e){let r=d0.parse(t);if("content"in r){await Zr(iK(r),r.signature,e.executor.signing,"receipt");let i=await Ig(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await oe(e)||r.executorId!==e.executor.id||r.accessDigest!==await oe(i)||i.authorityId!==e.actor.id||!s.authorities.some(a=>P(a)===P(e.actor))||s.id!==e.id||s.origin!==e.origin||s.ownerId!==e.ownerId||s.contentType!==ge.executionResult||s.grants.length||e.resultApproval&&P(e.resultApproval)!==P(i))throw new Error("The result does not belong to the requested execution.");if(!e.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await oe(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await $N(r.previous,e),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await ui(r.content),!o0(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(e.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:o,...n}=r;if(await Zr(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await oe(e)||r.executorId!==e.executor.id||r.sealed.aad!==aa(Ye(await u0(e,"result")))||P(r.sealed.recipients.map(i=>i.header.kid).sort())!==P(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function aK(t,e,r,o){if(await $N(t,e),"content"in t){if(!t.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await xo(t.content.sealed,o.encryption,r,await dc(t.content.policy,t.content.materialRevision)),a=zhe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await oe(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=iK(t);if(await Zr({...u,resultDigest:await oe(a.result)},a.proof,e.executor.signing,"execution-result"),t.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await xo(t.sealed,o.encryption,r,await u0(e,"result")),i=kN.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var jhe=m.enum(["http","command","function","connect","refresh","revoke"]),yn=m.object({id:x,ownerId:x,actorId:x,environmentId:x,kind:jhe,state:l0,intent:c0,requestSignature:zt,receipt:d0.nullable(),error:m.string().nullable(),createdAt:be,startedAt:be.nullable(),finishedAt:be.nullable()}).strict(),p0=m.object({name:ne,approval:Eg}).strict(),eqe=m.object({kind:m.literal("function"),functionId:x,definition:eo,arguments:pt.default({}),outputs:m.record(m.string(),p0).default({})}).strict(),sl=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:ac,save:m.record(m.string(),p0).default({})}).strict(),m.object({kind:m.literal("command"),...cc.shape}).strict(),m.object({kind:m.enum(["connect","refresh","revoke"]),input:ur}).strict()]);var wp=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},pc=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,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=m.object({error:m.object({code:m.string(),message:m.string()})}).parse(await n.json())}catch{throw new wp("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new wp(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await this.response(e,r),i=n.status===204?null:await n.json();return o?o.parse(i):i}async session(){return this.json("/api/session",{},JS)}};import{chmod as Mhe,lstat as Uhe,mkdir as Lhe,open as AN,readFile as uK,rename as Fhe,rm as Vhe}from"node:fs/promises";import{dirname as qhe,join as TN,resolve as Hhe}from"node:path";import{homedir as Bhe}from"node:os";import{randomUUID as Khe}from"node:crypto";var PN=m.object({origin:m.url(),principalId:m.uuid(),token:m.string().min(20),keys:_g.nullable(),binding:bt.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),lK=m.object({current:m.uuid(),identities:m.array(PN).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function la(){return TN(process.env.XDG_CONFIG_HOME||TN(Bhe(),".config"),"foundation","identity.json")}function bp(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function RN(){try{let t=la(),e=await Uhe(t);if(!e.isFile()||e.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&e.mode&63&&await Mhe(t,384),lK.parse(JSON.parse(await uK(t,"utf8")))}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function dK(){let t=await RN();return(t?.identities??[]).map(e=>({...e,current:e.principalId===t.current}))}async function pK(t){let e=await RN();if(!e?.identities.some(r=>r.principalId===t))throw new Error("No saved identity has principal "+t+". Run foundation identity list.");await fc(la(),JSON.stringify({...e,current:t},null,2)+`
|
|
128
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function GV(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;GV(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 t.anyOf,t.type=r.length===1?r[0]:r}var XV=new Set(["type","properties","required","additionalProperties"]),WV=["oneOf","anyOf"];function JV(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function HR(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!XV.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??JV(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:HR(a)??{allOf:a};_r(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=JV(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 Zfe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of XV)if(n in t)return;let r=e.filter(n=>WV.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=HR(e);else{let n=r[0],i=WV.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>HR([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,Hh(t,o))}function Ja(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.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 p=t.seen.get(d),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Hh(u,h),Hh(u,l),a._zod.parent===d)for(let y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(h.$ref&&p.def)for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())GV(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.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 t.intersections)for(let u of a.get(c)??[])Zfe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Hh(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,_r(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Kd(e,"input",t.processors),output:Kd(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function fn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return fn(o.element,r);if(o.type==="set")return fn(o.valueType,r);if(o.type==="lazy")return fn(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 fn(o.innerType,r);if(o.type==="intersection")return fn(o.left,r)||fn(o.right,r);if(o.type==="record"||o.type==="map")return fn(o.keyType,r)||fn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:fn(o.in,r)||fn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(fn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(fn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(fn(n,r))return!0;return!!(o.rest&&fn(o.rest,r))}return!1}var BR=(t,e={})=>r=>{let o=Za({...r,processors:e});return it(t,o),Wa(o,t),Ja(o,t)},Kd=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Za({...n??{},target:i,io:e,processors:r});return it(t,s),Wa(s,t),Ja(s,t)};var Zd=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},Wd=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},YV=(t,e)=>{Zd(t,"minimum",e),Wd(t,"maximum",e)},rq=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},nq=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},oq=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},iq=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},QV=(t,e)=>Zd(t,"minimum",e.minimum),eq=(t,e)=>Wd(t,"maximum",e.maximum),tq=t=>(e,r)=>{iq(e,r.format);let[o,n]=t[r.format];Zd(e,"minimum",o),Wd(e,"maximum",n)},Wfe={greater_than:(t,e)=>Zd(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>Wd(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>rq(t,e.value),number_format:tq(Wm),bigint_format:tq(Jm),min_length:QV,max_length:eq,length_equals:(t,e)=>YV(t,e.length),min_size:QV,max_size:eq,size_equals:(t,e)=>YV(t,e.size),string_format:(t,e)=>{iq(t,e.format),e.pattern&&nq(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>oq(t,e.mime)};function nr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)Wfe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Zd(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Zd(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Wd(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Wd(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&rq(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&oq(e,n.mime);for(let i of n.patterns??[])nq(e,i);return e}var Jfe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Gfe=new Map([[Lb,CP],[uh,OP]]),sq=t=>Gfe.get(t)??t,WR=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=nr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=Jfe[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(sq);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},JR=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=nr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let h=new Set;for(let w of a)Number.isFinite(w)&&w!==0?h.add(Math.abs(w)):rr(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[g,...y]=h;g!==void 0&&(n.multipleOf=g),y.length&&(n.allOf=[...n.allOf??[],...y.map(w=>({multipleOf:w}))])}},GR=(t,e,r,o)=>{r.type="boolean"},XR=(t,e,r,o)=>{rr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},YR=(t,e,r,o)=>{rr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},QR=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},eC=(t,e,r,o)=>{rr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},tC=(t,e,r,o)=>{rr(t,e,r,o,"Void cannot be represented in JSON Schema")},rC=(t,e,r,o)=>{r.not={}},nC=(t,e,r,o)=>{},oC=(t,e,r,o)=>{},iC=(t,e,r,o)=>{rr(t,e,r,o,"Date cannot be represented in JSON Schema")},sC=(t,e,r,o)=>{let n=t._zod.def,i=cd(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},aC=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(rr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(rr(t,e,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,e.target==="draft-04"||e.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},cC=(t,e,r,o)=>{rr(t,e,r,o,"NaN cannot be represented in JSON Schema")},uC=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},lC=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=nr(t);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})))},dC=(t,e,r,o)=>{r.type="boolean"},pC=(t,e,r,o)=>{rr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},fC=(t,e,r,o)=>{rr(t,e,r,o,"Function types cannot be represented in JSON Schema")},mC=(t,e,r,o)=>{rr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},hC=(t,e,r,o)=>{rr(t,e,r,o,"Map cannot be represented in JSON Schema")},gC=(t,e,r,o)=>{rr(t,e,r,o,"Set cannot be represented in JSON Schema")},yC=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=nr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=it(i.element,e,{...o,path:[...o.path,"items"]})};function Bh(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?Bh(e.out):e.type==="catch"?Bh(e.innerType):t._zod.optin}var vC=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&rr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)_r(n.properties,u,it(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?Bh(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=it(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},Tx=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>it(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},wC=(t,e,r,o)=>{let n=t._zod.def,i=it(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=it(n.right,e,{...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,e.intersections.push(c)},bC=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((g,y)=>it(g,e,{...o,path:[...o.path,s,y]})),u=i.rest?it(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let g=i.items[l-1];if(!(e.io==="input"?Bh(g)!==void 0:g._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:h}=nr(t);typeof p=="number"&&(n.minItems=p),typeof h=="number"&&(n.maxItems=h)};function KR(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let h=t.get(e)?.def;if(!h)return e;let g=KR(t,h,r);return g===h?e:g}for(let h of["anyOf","oneOf"]){let g=e[h];if(!Array.isArray(g))continue;let y=g.map(w=>KR(t,w,r));y.some((w,b)=>w!==g[b])&&(e={...e,[h]:y})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(h=>typeof h=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(h=>typeof h=="number"?String(h):h):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Qs:rh).source)),p}var ZR=new WeakMap;function Xfe(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of ZR.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=KR(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var _C=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=nr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=it(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)_r(n.patternProperties,sq(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=it(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=ZR.get(e);l||(l=[],ZR.set(e,l),e.deferred.push(()=>Xfe(e))),l.push(t)}n.additionalProperties=it(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&Bh(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))}},xC=(t,e,r,o)=>{let n=t._zod.def,i=it(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},SC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},EC=Symbol();function aq(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(rr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),EC):JSON.parse(s)}var IC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=aq(n.defaultValue,t,e,r,o);s!==EC&&(r.default=s)},kC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=aq(n.defaultValue,t,e,r,o);s!==EC&&(r._prefault=s)},$C=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{rr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},AC=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;it(s,e,o);let a=e.seen.get(t);a.ref=s},TC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},PC=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},Px=(t,e,r,o)=>{let n=t._zod.def;it(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},RC=(t,e,r,o)=>{let n=t._zod.innerType;it(n,e,o);let i=e.seen.get(t);i.ref=n},Ax={string:WR,number:JR,boolean:GR,bigint:XR,symbol:YR,null:QR,undefined:eC,void:tC,never:rC,any:nC,unknown:oC,date:iC,enum:sC,literal:aC,nan:cC,template_literal:uC,file:lC,success:dC,custom:pC,function:fC,transform:mC,map:hC,set:gC,array:yC,object:vC,union:Tx,intersection:wC,tuple:bC,record:_C,nullable:xC,nonoptional:SC,default:IC,prefault:kC,catch:$C,pipe:AC,readonly:TC,promise:PC,optional:Px,lazy:RC};function Vu(t,e){if("_idmap"in t){let o=t,n=Za({...e,processors:Ax}),i={};for(let c of o._idmap.entries()){let[u,l]=c;it(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Wa(n,l),_r(s,u,Ja(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=Za({...e,processors:Ax});return it(t,r),Wa(r,t),Ja(r,t)}var Rx=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(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Za({processors:Ax,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return it(e,this.ctx,r)}emit(e,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,Wa(this.ctx,e);let o=Ja(this.ctx,e),{"~standard":n,...i}=o;return i}};var cq={};var rp={};St(rp,{ZodAny:()=>GC,ZodArray:()=>eO,ZodBase64:()=>Gx,ZodBase64URL:()=>Xx,ZodBigInt:()=>ep,ZodBigIntFormat:()=>eS,ZodBoolean:()=>Qd,ZodCIDRv4:()=>Wx,ZodCIDRv6:()=>Jx,ZodCUID:()=>Fx,ZodCUID2:()=>Vx,ZodCatch:()=>wO,ZodCodec:()=>eg,ZodCreditCard:()=>BC,ZodCustom:()=>tg,ZodCustomStringFormat:()=>Hu,ZodDate:()=>Jh,ZodDefault:()=>fO,ZodDiscriminatedUnion:()=>rO,ZodE164:()=>Yx,ZodEmail:()=>jx,ZodEmoji:()=>Ux,ZodEnum:()=>Gd,ZodExactOptional:()=>nS,ZodFile:()=>uO,ZodFunction:()=>TO,ZodGUID:()=>Mx,ZodIBAN:()=>KC,ZodIPv4:()=>Kx,ZodIPv6:()=>Zx,ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,ZodInstanceOf:()=>CO,ZodIntersection:()=>nO,ZodJWT:()=>Qx,ZodKSUID:()=>Bx,ZodLazy:()=>kO,ZodLiteral:()=>cO,ZodMAC:()=>HC,ZodMap:()=>sO,ZodNaN:()=>_O,ZodNanoID:()=>Lx,ZodNever:()=>YC,ZodNonOptional:()=>oS,ZodNull:()=>JC,ZodNullable:()=>pO,ZodNumber:()=>Yd,ZodNumberFormat:()=>Bu,ZodObject:()=>Gh,ZodOptional:()=>Ku,ZodPipe:()=>Qh,ZodPrefault:()=>hO,ZodPreprocess:()=>xO,ZodPromise:()=>AO,ZodReadonly:()=>SO,ZodRecord:()=>Jd,ZodSet:()=>aO,ZodString:()=>Xd,ZodStringFormat:()=>ut,ZodSuccess:()=>vO,ZodSymbol:()=>ZC,ZodTemplateLiteral:()=>IO,ZodTransform:()=>lO,ZodTuple:()=>oO,ZodType:()=>Se,ZodULID:()=>qx,ZodURL:()=>Zh,ZodUUID:()=>Qi,ZodUndefined:()=>WC,ZodUnion:()=>Xh,ZodUnknown:()=>XC,ZodVoid:()=>QC,ZodXID:()=>Hx,ZodXor:()=>tO,_ZodString:()=>zx,_default:()=>mO,_function:()=>gH,any:()=>Xq,array:()=>Oe,base64:()=>Rq,base64url:()=>Cq,bigint:()=>Kq,boolean:()=>Wt,catch:()=>bO,check:()=>yH,cidrv4:()=>Tq,cidrv6:()=>Pq,codec:()=>pH,creditCard:()=>Nq,cuid:()=>_q,cuid2:()=>xq,currencyCode:()=>Lq,custom:()=>iS,date:()=>Qq,describe:()=>vH,discriminatedUnion:()=>Yh,e164:()=>Oq,email:()=>dq,emoji:()=>wq,enum:()=>Er,exactOptional:()=>dO,file:()=>cH,float32:()=>Vq,float64:()=>qq,function:()=>gH,guid:()=>pq,hash:()=>Fq,hex:()=>Uq,hostname:()=>Mq,httpUrl:()=>vq,iban:()=>Dq,instanceof:()=>bH,int:()=>Nx,int32:()=>Hq,int64:()=>Zq,intersection:()=>tp,invertCodec:()=>fH,ipv4:()=>kq,ipv6:()=>Aq,json:()=>xH,jwt:()=>zq,keyof:()=>eH,ksuid:()=>Iq,lazy:()=>$O,literal:()=>G,looseObject:()=>Sr,looseRecord:()=>oH,mac:()=>$q,map:()=>iH,meta:()=>wH,nan:()=>dH,nanoid:()=>bq,nativeEnum:()=>aH,never:()=>tS,nonoptional:()=>yO,null:()=>Wh,nullable:()=>Kh,nullish:()=>uH,number:()=>Je,object:()=>q,optional:()=>ct,partialRecord:()=>nH,pipe:()=>Dx,prefault:()=>gO,preprocess:()=>rg,promise:()=>hH,readonly:()=>EO,record:()=>lt,refine:()=>PO,set:()=>sH,strictObject:()=>tH,string:()=>k,stringFormat:()=>jq,stringbool:()=>_H,success:()=>lH,superRefine:()=>RO,symbol:()=>Jq,templateLiteral:()=>mH,transform:()=>rS,tuple:()=>iO,uint32:()=>Bq,uint64:()=>Wq,ulid:()=>Sq,undefined:()=>Gq,union:()=>st,unknown:()=>ht,url:()=>yq,uuid:()=>fq,uuidv4:()=>mq,uuidv6:()=>hq,uuidv7:()=>gq,void:()=>Yq,xid:()=>Eq,xor:()=>rH});var Cx={};St(Cx,{endsWith:()=>Md,gt:()=>Xi,gte:()=>Xn,includes:()=>zd,length:()=>Fu,lowercase:()=>Nd,lt:()=>Gi,lte:()=>Gn,maxLength:()=>Lu,maxSize:()=>Ba,mime:()=>Ld,minLength:()=>ea,minSize:()=>Yi,multipleOf:()=>Ha,negative:()=>yx,nonnegative:()=>wx,nonpositive:()=>vx,normalize:()=>Fd,overwrite:()=>ri,positive:()=>gx,properties:()=>Ud,property:()=>bx,regex:()=>Od,size:()=>Uu,slugify:()=>Bd,startsWith:()=>jd,toLowerCase:()=>qd,toUpperCase:()=>Hd,trim:()=>Vd,uppercase:()=>Dd});var uq=new WeakSet([Object.prototype,Error.prototype]);function Ox(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var lq=(t,e)=>{pP.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);uq.has(r)||(uq.add(r),Ox(r,"format",o=>n=>eh(o,n)),Ox(r,"flatten",o=>n=>Qm(o,n)),Ox(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,ud,2)}),Ox(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,ud,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Qfe=S("ZodError",lq),Nn=S("ZodError",lq,void 0,{Parent:Error});var CC=md(Nn),OC=hd(Nn),NC=gd(Nn),DC=vd(Nn),zC=tb(Nn),jC=rb(Nn),MC=nb(Nn),UC=ob(Nn),LC=ib(Nn),FC=sb(Nn),VC=ab(Nn),qC=cb(Nn);function tme(){cr.localeError||Ft(U_())}function qu(){cr.memoizer||Ft({memoizer:yh()})}var Se=S("ZodType",(t,e)=>(tme(),de.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(A.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return We(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(PO(t,e))},superRefine(t,e){return this.check(RO(t,e))},overwrite(t){return this.check(ri(t))},optional(){return ct(this)},exactOptional(){return dO(this)},nullable(){return Kh(this)},nullish(){return ct(Kh(this))},nonoptional(t){return yO(this,t)},array(){return Oe(this)},or(t){return st([this,t])},and(t){return tp(this,t)},transform(t){return Dx(this,rS(t))},default(t){return mO(this,t)},prefault(t){return gO(this,t)},catch(t){return bO(this,t)},pipe(t){return Dx(this,t)},readonly(){return EO(this)},describe(t){let e=this.clone();return xr.add(e,{description:t}),e},meta(...t){if(t.length===0)return xr.get(this);let e=this.clone();return xr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return A.hide(this,"~standard",{...wb(this),jsonSchema:{input:Kd(this,"input"),output:Kd(this,"output")}})},set"~standard"(t){A.own(this,"~standard",t)},parse:function t(e,r){return CC(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await OC(this,e,r,{callee:t})},safeParse(t,e){return NC(this,t,e)},async safeParseAsync(t,e){return DC(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){A.own(this,"spa",t)},validate(t,e){return bd(this,t,e)},validateAsync(t,e){return _d(this,t,e)},encode:function t(e,r){return zC(this,e,r,{callee:t})},decode:function t(e,r){return jC(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await MC(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await UC(this,e,r,{callee:t})},safeEncode(t,e){return LC(this,t,e)},safeDecode(t,e){return FC(this,t,e)},async safeEncodeAsync(t,e){return VC(this,t,e)},async safeDecodeAsync(t,e){return qC(this,t,e)},toJSONSchema(t){return BR(this,{})(t)},get description(){return xr.get(this)?.description},get _def(){return this._zod.def}}),zx=S("_ZodString",(t,e)=>{qa.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WR(t,r,o,n)},A.derived({format:t=>nr(t).format??null,minLength:t=>nr(t).minimum??null,maxLength:t=>nr(t).maximum??null},{regex(...t){return this.check(Od(...t))},includes(...t){return this.check(zd(...t))},startsWith(...t){return this.check(jd(...t))},endsWith(...t){return this.check(Md(...t))},min(...t){return this.check(ea(...t))},max(...t){return this.check(Lu(...t))},length(...t){return this.check(Fu(...t))},nonempty(...t){return this.check(ea(1,...t))},lowercase(t){return this.check(Nd(t))},uppercase(t){return this.check(Dd(t))},trim(){return this.check(Vd())},normalize(...t){return this.check(Fd(...t))},toLowerCase(){return this.check(qd())},toUpperCase(){return this.check(Hd())},slugify(){return this.check(Bd())}})),Xd=S("ZodString",(t,e)=>{qa.init(t,e),zx.init(t,e)},{email(t){return this.check(wh(jx,t))},url(t){return this.check(Cd(Zh,t))},jwt(t){return this.check(Uh(Qx,t))},emoji(t){return this.check(Ih(Ux,t))},guid(t){return this.check(bh(Mx,t))},uuid(t){return this.check(_h(Qi,t))},uuidv4(t){return this.check(xh(Qi,t))},uuidv6(t){return this.check(Sh(Qi,t))},uuidv7(t){return this.check(Eh(Qi,t))},nanoid(t){return this.check(kh(Lx,t))},cuid(t){return this.check($h(Fx,t))},cuid2(t){return this.check(Ah(Vx,t))},ulid(t){return this.check(Th(qx,t))},base64(t){return this.check(zh(Gx,t))},base64url(t){return this.check(jh(Xx,t))},xid(t){return this.check(Ph(Hx,t))},ksuid(t){return this.check(Rh(Bx,t))},ipv4(t){return this.check(Ch(Kx,t))},ipv6(t){return this.check(Oh(Zx,t))},cidrv4(t){return this.check(Nh(Wx,t))},cidrv6(t){return this.check(Dh(Jx,t))},e164(t){return this.check(Mh(Yx,t))},datetime(t){return this.check(Lh(Ga,t))},date(t){return this.check(Fh(Xa,t))},time(t){return this.check(Vh(Ya,t))},duration(t){return this.check(qh(Qa,t))}});function k(t){return Z_(Xd,t)}var ut=S("ZodStringFormat",(t,e)=>{Qe.init(t,e),zx.init(t,e)}),Ga=S("ZodISODateTime",(t,e)=>{_R.init(t,e),ut.init(t,e)}),Xa=S("ZodISODate",(t,e)=>{xR.init(t,e),ut.init(t,e)}),Ya=S("ZodISOTime",(t,e)=>{SR.init(t,e),ut.init(t,e)}),Qa=S("ZodISODuration",(t,e)=>{ER.init(t,e),ut.init(t,e)}),jx=S("ZodEmail",(t,e)=>{xb.init(t,e),ut.init(t,e)});function dq(t){return wh(jx,t)}var Mx=S("ZodGUID",(t,e)=>{bb.init(t,e),ut.init(t,e)});function pq(t){return bh(Mx,t)}var Qi=S("ZodUUID",(t,e)=>{_b.init(t,e),ut.init(t,e)});function fq(t){return _h(Qi,t)}function mq(t){return xh(Qi,t)}function hq(t){return Sh(Qi,t)}function gq(t){return Eh(Qi,t)}var Zh=S("ZodURL",(t,e)=>{kb.init(t,e),ut.init(t,e)});function yq(t){return Cd(Zh,t)}function vq(t){return Cd(Zh,{protocol:th,hostname:DP,...A.normalizeParams(t)})}var Ux=S("ZodEmoji",(t,e)=>{$b.init(t,e),ut.init(t,e)});function wq(t){return Ih(Ux,t)}var Lx=S("ZodNanoID",(t,e)=>{Ab.init(t,e),ut.init(t,e)});function bq(t){return kh(Lx,t)}var Fx=S("ZodCUID",(t,e)=>{Tb.init(t,e),ut.init(t,e)});function _q(t){return $h(Fx,t)}var Vx=S("ZodCUID2",(t,e)=>{Pb.init(t,e),ut.init(t,e)});function xq(t){return Ah(Vx,t)}var qx=S("ZodULID",(t,e)=>{Rb.init(t,e),ut.init(t,e)});function Sq(t){return Th(qx,t)}var Hx=S("ZodXID",(t,e)=>{Cb.init(t,e),ut.init(t,e)});function Eq(t){return Ph(Hx,t)}var Bx=S("ZodKSUID",(t,e)=>{Ob.init(t,e),ut.init(t,e)});function Iq(t){return Rh(Bx,t)}var Kx=S("ZodIPv4",(t,e)=>{Nb.init(t,e),ut.init(t,e)});function kq(t){return Ch(Kx,t)}var HC=S("ZodMAC",(t,e)=>{zb.init(t,e),ut.init(t,e)});function $q(t){return W_(HC,t)}var Zx=S("ZodIPv6",(t,e)=>{Db.init(t,e),ut.init(t,e)});function Aq(t){return Oh(Zx,t)}var Wx=S("ZodCIDRv4",(t,e)=>{jb.init(t,e),ut.init(t,e)});function Tq(t){return Nh(Wx,t)}var Jx=S("ZodCIDRv6",(t,e)=>{Ub.init(t,e),ut.init(t,e)});function Pq(t){return Dh(Jx,t)}var Gx=S("ZodBase64",(t,e)=>{Fb.init(t,e),ut.init(t,e)});function Rq(t){return zh(Gx,t)}var Xx=S("ZodBase64URL",(t,e)=>{qb.init(t,e),ut.init(t,e)});function Cq(t){return jh(Xx,t)}var Yx=S("ZodE164",(t,e)=>{Hb.init(t,e),ut.init(t,e)});function Oq(t){return Mh(Yx,t)}var BC=S("ZodCreditCard",(t,e)=>{Kb.init(t,e),ut.init(t,e)});function Nq(t){return J_(BC,t)}var KC=S("ZodIBAN",(t,e)=>{Wb.init(t,e),ut.init(t,e)});function Dq(t){return G_(KC,t)}var Qx=S("ZodJWT",(t,e)=>{Gb.init(t,e),ut.init(t,e)});function zq(t){return Uh(Qx,t)}var Hu=S("ZodCustomStringFormat",(t,e)=>{Xb.init(t,e),ut.init(t,e)});function jq(t,e,r={}){return Ka(Hu,t,e,r)}function Mq(t){return Ka(Hu,"hostname",NP,t)}function Uq(t){return Ka(Hu,"hex",JP,t)}function Lq(t){return Ka(Hu,"currency_code",jP,t)}function Fq(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Jn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Ka(Hu,o,n,e)}var Yd=S("ZodNumber",(t,e)=>{lh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JR(t,r,o,n),t.isFinite=!0},A.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=nr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=nr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=nr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>nr(t).format??null},{gt(t,e){return this.check(Xi(t,e))},gte(t,e){return this.check(Xn(t,e))},min(t,e){return this.check(Xn(t,e))},lt(t,e){return this.check(Gi(t,e))},lte(t,e){return this.check(Gn(t,e))},max(t,e){return this.check(Gn(t,e))},int(t){return this.check(Nx(t))},safe(t){return this.check(Nx(t))},positive(t){return this.check(Xi(0,t))},nonnegative(t){return this.check(Xn(0,t))},negative(t){return this.check(Gi(0,t))},nonpositive(t){return this.check(Gn(0,t))},multipleOf(t,e){return this.check(Ha(t,e))},step(t,e){return this.check(Ha(t,e))},finite(){return this}}));function Je(t){return X_(Yd,t)}var Bu=S("ZodNumberFormat",(t,e)=>{Yb.init(t,e),Yd.init(t,e)});function Nx(t){return Y_(Bu,t)}function Vq(t){return Q_(Bu,t)}function qq(t){return ex(Bu,t)}function Hq(t){return tx(Bu,t)}function Bq(t){return rx(Bu,t)}var Qd=S("ZodBoolean",(t,e)=>{Ed.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GR(t,r,o,n)});function Wt(t){return nx(Qd,t)}var ep=S("ZodBigInt",(t,e)=>{dh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XR(t,r,o,n)},A.derived({minValue:t=>nr(t).minimum??null,maxValue:t=>nr(t).maximum??null,format:t=>nr(t).format??null},{gte(t,e){return this.check(Xn(t,e))},min(t,e){return this.check(Xn(t,e))},gt(t,e){return this.check(Xi(t,e))},lt(t,e){return this.check(Gi(t,e))},lte(t,e){return this.check(Gn(t,e))},max(t,e){return this.check(Gn(t,e))},positive(t){return this.check(Xi(BigInt(0),t))},negative(t){return this.check(Gi(BigInt(0),t))},nonpositive(t){return this.check(Gn(BigInt(0),t))},nonnegative(t){return this.check(Xn(BigInt(0),t))},multipleOf(t,e){return this.check(Ha(t,e))}}));function Kq(t){return ox(ep,t)}var eS=S("ZodBigIntFormat",(t,e)=>{Qb.init(t,e),ep.init(t,e)});function Zq(t){return ix(eS,t)}function Wq(t){return sx(eS,t)}var ZC=S("ZodSymbol",(t,e)=>{e_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YR(t,r,o,n)});function Jq(t){return ax(ZC,t)}var WC=S("ZodUndefined",(t,e)=>{t_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eC(t,r,o,n)});function Gq(t){return cx(WC,t)}var JC=S("ZodNull",(t,e)=>{r_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QR(t,r,o,n)});function Wh(t){return ux(JC,t)}var GC=S("ZodAny",(t,e)=>{n_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nC(t,r,o,n)});function Xq(){return lx(GC)}var XC=S("ZodUnknown",(t,e)=>{o_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oC(t,r,o,n)});function ht(){return dx(XC)}var YC=S("ZodNever",(t,e)=>{i_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rC(t,r,o,n)});function tS(t){return px(YC,t)}var QC=S("ZodVoid",(t,e)=>{s_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tC(t,r,o,n)});function Yq(t){return fx(QC,t)}var Jh=S("ZodDate",(t,e)=>{a_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iC(t,r,o,n),t.min=(r,o)=>t.check(Xn(r,o)),t.max=(r,o)=>t.check(Gn(r,o))},A.derived({minDate:t=>{let{minimum:e}=nr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=nr(t);return e?new Date(e):null}},{}));function Qq(t){return mx(Jh,t)}var eO=S("ZodArray",(t,e)=>{qu(),c_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yC(t,r,o,n),t.element=e.element},{min(t,e){return this.check(ea(t,e))},nonempty(t){return this.check(ea(1,t))},max(t,e){return this.check(Lu(t,e))},length(t,e){return this.check(Fu(t,e))},unwrap(){return this.element}});function Oe(t,e){return qR(eO,t,e)}function eH(t){let e=t._zod.def.shape;return Er(Object.keys(e))}var Gh=S("ZodObject",(t,e)=>{qu(),IR.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vC(t,r,o,n),A.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Er(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(A.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ht()}))},loose(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ht()}))},strict(){return this.clone(A.mergeDefs(this._zod.def,{catchall:tS()}))},strip(){return this.clone(A.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return A.extend(this,t)},safeExtend(t){return A.safeExtend(this,t)},merge(t){return A.merge(this,t)},pick(t){return A.pick(this,t)},omit(t){return A.omit(this,t)},partial(...t){return A.partial(Ku,this,t[0])},exactPartial(...t){return A.partial(nS,this,t[0],"exactPartial")},required(...t){return A.required(oS,this,t[0])}});function q(t,e){let r={type:"object",shape:t??{},...A.normalizeParams(e)};return new Gh(r)}function tH(t,e){return new Gh({type:"object",shape:t,catchall:tS(),...A.normalizeParams(e)})}function Sr(t,e){return new Gh({type:"object",shape:t,catchall:ht(),...A.normalizeParams(e)})}var Xh=S("ZodUnion",(t,e)=>{Id.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tx(t,r,o,n),t.options=e.options});function st(t,e){return new Xh({type:"union",options:t,...A.normalizeParams(e)})}var tO=S("ZodXor",(t,e)=>{Xh.init(t,e),l_.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tx(t,r,o,n),t.options=e.options});function rH(t,e){return new tO({type:"union",options:t,inclusive:!1,...A.normalizeParams(e)})}var rO=S("ZodDiscriminatedUnion",(t,e)=>{Xh.init(t,e),d_.init(t,e)});function Yh(t,e,r){return new rO({type:"union",options:e,discriminator:t,...A.normalizeParams(r)})}var nO=S("ZodIntersection",(t,e)=>{p_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wC(t,r,o,n)});function tp(t,e){return new nO({type:"intersection",left:t,right:e})}var oO=S("ZodTuple",(t,e)=>{qu(),ph.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bC(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Ku({type:"optional",innerType:e}))})}});function iO(t,e,r){let o=e instanceof de,n=o?r:e,i=o?e:null;return new oO({type:"tuple",items:t,rest:i,...A.normalizeParams(n)})}var Jd=S("ZodRecord",(t,e)=>{qu(),f_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_C(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function lt(t,e,r){return!e||!e._zod?new Jd({type:"record",keyType:k(),valueType:t,...A.normalizeParams(e)}):new Jd({type:"record",keyType:t,valueType:e,...A.normalizeParams(r)})}function nH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,...A.normalizeParams(r),partial:!0})}function oH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,mode:"loose",...A.normalizeParams(r)})}var sO=S("ZodMap",(t,e)=>{qu(),m_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hC(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Yi(...r)),t.nonempty=r=>t.check(Yi(1,r)),t.max=(...r)=>t.check(Ba(...r)),t.size=(...r)=>t.check(Uu(...r))});function iH(t,e,r){return new sO({type:"map",keyType:t,valueType:e,...A.normalizeParams(r)})}var aO=S("ZodSet",(t,e)=>{qu(),h_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gC(t,r,o,n),t.min=(...r)=>t.check(Yi(...r)),t.nonempty=r=>t.check(Yi(1,r)),t.max=(...r)=>t.check(Ba(...r)),t.size=(...r)=>t.check(Uu(...r))});function sH(t,e){return new aO({type:"set",valueType:t,...A.normalizeParams(e)})}var Gd=S("ZodEnum",(t,e)=>{g_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(o,n,i)=>sC(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Gd({...e,checks:[],...A.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.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 Gd({...e,checks:[],...A.normalizeParams(n),entries:i})}});function Er(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Gd({type:"enum",entries:r,...A.normalizeParams(e)})}function aH(t,e){return new Gd({type:"enum",entries:t,...A.normalizeParams(e)})}var cO=S("ZodLiteral",(t,e)=>{y_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aC(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function G(t,e){return new cO({type:"literal",values:Array.isArray(t)?t:[t],...A.normalizeParams(e)})}var uO=S("ZodFile",(t,e)=>{v_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lC(t,r,o,n),t.min=(r,o)=>t.check(Yi(r,o)),t.max=(r,o)=>t.check(Ba(r,o)),t.mime=(r,o)=>t.check(Ld(Array.isArray(r)?r:[r],o))});function cH(t){return _x(uO,t)}var lO=S("ZodTransform",(t,e)=>{qu(),w_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mC(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Va(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(A.issue(i,r.value,e));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=t),r.issues.push(A.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function rS(t){return new lO({type:"transform",transform:t})}var Ku=S("ZodOptional",(t,e)=>{fh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ct(t){return new Ku({type:"optional",innerType:t})}var nS=S("ZodExactOptional",(t,e)=>{b_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function dO(t){return new nS({type:"optional",innerType:t})}var pO=S("ZodNullable",(t,e)=>{__.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Kh(t){return new pO({type:"nullable",innerType:t})}function uH(t){return ct(Kh(t))}var fO=S("ZodDefault",(t,e)=>{x_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function mO(t,e){return new fO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var hO=S("ZodPrefault",(t,e)=>{S_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function gO(t,e){return new hO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var oS=S("ZodNonOptional",(t,e)=>{E_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yO(t,e){return new oS({type:"nonoptional",innerType:t,...A.normalizeParams(e)})}var vO=S("ZodSuccess",(t,e)=>{I_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function lH(t){return new vO({type:"success",innerType:t})}var wO=S("ZodCatch",(t,e)=>{k_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$C(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function bO(t,e){return new wO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:A.constantCatch(e)})}var _O=S("ZodNaN",(t,e)=>{$_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cC(t,r,o,n)});function dH(t){return hx(_O,t)}var Qh=S("ZodPipe",(t,e)=>{mh.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AC(t,r,o,n),t.in=e.in,t.out=e.out});function Dx(t,e){return new Qh({type:"pipe",in:t,out:e})}var eg=S("ZodCodec",(t,e)=>{Qh.init(t,e),kd.init(t,e)});function pH(t,e,r){return new eg({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function fH(t){let e=t._zod.def;return new eg({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var xO=S("ZodPreprocess",(t,e)=>{Qh.init(t,e),$R.init(t,e)}),SO=S("ZodReadonly",(t,e)=>{A_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function EO(t){return new SO({type:"readonly",innerType:t})}var IO=S("ZodTemplateLiteral",(t,e)=>{T_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uC(t,r,o,n)});function mH(t,e){return new IO({type:"template_literal",parts:t,...A.normalizeParams(e)})}var kO=S("ZodLazy",(t,e)=>{$d.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RC(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function $O(t){return new kO({type:"lazy",getter:t})}var AO=S("ZodPromise",(t,e)=>{R_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PC(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function hH(t){return new AO({type:"promise",innerType:t})}var TO=S("ZodFunction",(t,e)=>{P_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fC(t,r,o,n)});function gH(t){return new TO({type:"function",input:Array.isArray(t?.input)?iO(t?.input):t?.input??Oe(ht()),output:t?.output??ht()})}var tg=S("ZodCustom",(t,e)=>{C_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pC(t,r,o,n)});function yH(t){let e=new at({check:"custom"});return e._zod.check=t,e}function iS(t,e){return xx(tg,t??(()=>!0),e)}function PO(t,e={}){return Sx(tg,t,e)}function RO(t,e){return Ex(t,e)}var vH=Ix,wH=kx,CO=S("ZodInstanceOf",(t,e)=>{tg.init(t,e)},{properties(t,e){return this.check(Ud(t,e))}});function bH(t,e={}){let r=new CO({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...A.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var _H=(...t)=>$x({Codec:eg,Boolean:Qd,String:Xd},...t);function xH(t){let e=$O(()=>st([k(t),Je(),Wt(),Wh(),Oe(e),lt(k(),e)]));return e}function rg(t,e){return new xO({type:"pipe",in:rS(t),out:e})}var rme={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 nme(t){Ft({customError:t})}function ome(){return Ft().customError}var OO;OO||(OO={});var Zu={};St(Zu,{ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,date:()=>sme,datetime:()=>ime,duration:()=>cme,time:()=>ame});function ime(t){return Lh(Ga,t)}function sme(t){return Fh(Xa,t)}function ame(t){return Vh(Ya,t)}function cme(t){return qh(Qa,t)}var V={...rp,...Cx,iso:Zu},ume=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 lme(t,e){let r=t.$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":e??"draft-2020-12"}function SH(t,e){return t.map((r,o)=>o<e?r:r.optional())}function dme(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function pme(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:dme(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function fme(t,e){return V.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(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function NO(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=NO(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=NO(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var mme=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),hme=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function ng(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(ng):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>mme.has(e)?ng(r):!hme.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(ng))}function EH(t){return t===1?"element":"elements"}function gme(t,e){return V.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=NO(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(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${EH(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${EH(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function IH(t,e){if(t!==!1)return t===void 0||t===!0?V.any():mn(t,e)}var yme=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function kH(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return V.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return V.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=pme(n,e),s=mn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return V.null();if(n.length===0)return V.never();if(n.length===1)return V.literal(n[0]);if(n.every(s=>typeof s=="string"))return V.enum(n);let i=n.map(s=>V.literal(s));return i.length<2?i[0]:V.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return V.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return kH(s,e)});return n.length===0?V.never():n.length===1?n[0]:V.union(n)}if(!r)return V.any();let o;switch(r){case"string":{let n=V.string();if(t.format){let i=t.format;i==="email"?n=n.check(V.email()):i==="uri"||i==="uri-reference"?n=n.check(V.url()):i==="uuid"||i==="guid"?n=n.check(V.uuid()):i==="date-time"?n=n.check(V.iso.datetime({offset:!0})):i==="date"?n=n.check(V.iso.date()):i==="time"?n=n.check(V.regex(yme)):i==="duration"?n=n.check(V.iso.duration()):i==="hostname"?n=n.check(V.hostname()):i==="ipv4"?n=n.check(V.ipv4()):i==="ipv6"?n=n.check(V.ipv6()):i==="mac"?n=n.check(V.mac()):i==="cidr"?n=n.check(V.cidrv4()):i==="cidr-v6"?n=n.check(V.cidrv6()):i==="base64"?n=n.check(V.base64()):i==="base64url"?n=n.check(V.base64url()):i==="e164"?n=n.check(V.e164()):i==="credit_card"?n=n.check(V.creditCard()):i==="iban"?n=n.check(V.iban()):i==="jwt"?n=n.check(V.jwt()):i==="emoji"?n=n.check(V.emoji()):i==="nanoid"?n=n.check(V.nanoid()):i==="cuid"?n=n.check(V.cuid()):i==="cuid2"?n=n.check(V.cuid2()):i==="ulid"?n=n.check(V.ulid()):i==="xid"?n=n.check(V.xid()):i==="ksuid"&&(n=n.check(V.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?V.number().int():V.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=V.boolean();break}case"null":{o=V.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?mn(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=mn(f,e);_r(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let g of f){let y=mn(d[g],e),w=V.string().regex(new RegExp(g));p.push(V.looseRecord(w,y))}let h=[];if(Object.keys(n).length>0&&h.push(V.object(n).passthrough()),h.push(...p),h.length===0)o=V.object({}).passthrough();else if(h.length===1)o=h[0];else{let g=V.intersection(h[0],h[1]);for(let y=2;y<h.length;y++)g=V.intersection(g,h[y]);o=g}if(t.additionalProperties===!1){let g=Object.keys(n),y=f.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!vo(b.value))return;let _=[];for(let I of Object.keys(b.value))g.includes(I)||y.some($=>$.test(I))||_.push(I);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=V.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=mn(f,e)}o=fme(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>mn(d,e)),c=SH(a,s),u=Array.isArray(i)?void 0:IH(i,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>mn(d,e)),c=SH(a,s),u=IH(t.additionalItems,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(i!==void 0){let s=mn(i,e),a=V.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=V.array(V.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=gme(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?mn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function mn(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r=kH(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>mn(u,e)),c=V.union(a);r=o?V.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>mn(u,e)),c=V.xor(a);r=o?V.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:V.any();else{let a=o?r:mn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=V.intersection(a,mn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=V.nullable(r)),t.readOnly===!0&&(r=V.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!ng(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!ng(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))ume.has(a)||_r(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function $H(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=lme(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??xr};return mn(r,i)}var AH=Symbol("z.visit/resolving");function og(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===AH)return new $d({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,AH);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,f={};for(let h of l){let g=n(u[h]);g!==u[h]&&(d=!0),f[h]=g}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?We(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:We(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let h=n(p);h!==p&&(l=!0),d.push(h)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?We(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:We(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:We(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?We(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:We(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:We(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:We(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:We(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return We(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(t)}function TH(t){return og(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:st(r.options)}})}function vme(t,e){if(!e?.length)return t;let r=t._zod.def;return We(t,yo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function PH(t){return vme(t.out,t.checks)}function wme(t){return t.in._zod.traits.has("$ZodTransform")?PH(t):t.in}function RH(t){return og(t,{pipe:e=>wme(e._zod.def),default:(e,r)=>r?ct(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function CH(t){return og(t,{pipe:e=>PH(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var DO={};St(DO,{bigint:()=>Sme,boolean:()=>xme,date:()=>Eme,number:()=>_me,string:()=>bme});function bme(t){return jR(Xd,t)}function _me(t){return UR(Yd,t)}function xme(t){return LR(Qd,t)}function Sme(t){return FR(ep,t)}function Eme(t){return VR(Jh,t)}var ig={name:"@tomato414941/foundation",version:"21.0.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs","foundation-executor":"dist/agent.mjs"},files:["dist/cli.mjs","dist/agent.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"&&m.config({jitless:!0});function kme(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[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())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[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(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var OH=m.string().trim().max(8192).refine(t=>kme(t)!==null,"Use an OpenSSH public key from a .pub file."),sS=m.object({authorizedKeys:m.array(OH).max(32)}).strict(),k2e=sS.extend({revision:m.number().int().positive().optional()}),zO=sS.extend({host:m.string().min(1).max(253).nullable(),port:m.number().int().min(1).max(65535),username:m.string().regex(/^[a-z_][a-z0-9_-]*$/),workingDirectory:m.string().startsWith("/").max(4096),hostKey:OH.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),$2e=zO.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])});var np=new TextEncoder,op=new TextDecoder,NH=new TextDecoder("utf-8",{fatal:!0}),aS=2**32;function hn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function jO(t,e,r){if(e<0||e>=aS)throw new RangeError(`value must be >= 0 and <= ${aS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function MO(t){let e=Math.floor(t/aS),r=t%aS,o=new Uint8Array(8);return jO(o,e,0),jO(o,r,4),o}function cS(t){let e=new Uint8Array(4);return jO(e,t),e}var $me=/[^\x00-\x7f]/;function Ir(t){if(typeof t=="string"&&t.length>=128){if($me.test(t))throw new TypeError("non-ASCII string encountered in encode()");return np.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function DH(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function zH(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function uS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var ta=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Wu=class extends ta{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},dt=class extends ta{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},ec=class extends ta{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},U=class extends ta{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},At=class extends ta{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var sg=class extends ta{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var lS=class extends ta{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var Ame="The input to be decoded is not correctly encoded.";function Ju(t){try{return zH(typeof t=="string"?t:op.decode(t),!0)}catch(e){throw new TypeError(Ame,{cause:e})}}function Nt(t){return DH(typeof t=="string"?np.encode(t):t,!0)}function Yn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Yt(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function tc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function bo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function Dn(t,e,r){try{return Ju(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function dS(t,e,r){try{return Ir(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function ip(t,e,r){let o;try{o=JSON.parse(NH.decode(Ju(t)))}catch{throw new e(r)}if(!Yt(o))throw new e(r);return o}var pS={__proto__:null,b64:!0},fS={__proto__:null};function ag(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function mS(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function rc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"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 t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new dt(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function hS(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new At('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Gu(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!Yt(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var Tme=t=>t[Symbol.toStringTag],Pme=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function oi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(Yt(e)){if(s=HO(e),typeof s.kty!="string")throw jH(o,e,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(Pme(t,s,r),s.kty==="oct")return Ju(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!FO(e))throw jH(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${Tme(e)} instances must be of type "${l}" for the ${o} algorithm`);if(nc(e))return e;if(a=e,a.type==="secret")return a.export()}UO||=new WeakMap;let c=e,u=UO.get(c);if(u?.[o])return u[o];if(u||UO.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Rme[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await ap(t,s)}var UO,Rme={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function yS(t){if(!nc(t))throw new Error("CryptoKey instance expected")}var nc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},LO=t=>t?.[Symbol.toStringTag]==="KeyObject",FO=t=>nc(t)||LO(t);function MH(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var ra=(t,...e)=>MH("Key must be ",t,...e);function jH(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(MH(`Key for the ${t} algorithm must be `,e,...o))}var gS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function VO(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function sp(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function qO(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw gS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw gS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw gS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw gS(e.length,"algorithm.length");VO(t,r)}function vS(t){return{__proto__:null,...t}}function HO(t){let e=vS(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.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');e.key_ops=o}return e}function wS(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function ap(t,e,r){if(!t.kty.includes(e.kty))throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function ii(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),qO(t,e,r),t}var Xu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function bS(t,e){let r=t.byteLength<<3;if(r!==e)throw new U(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var Cme=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function UH(t,e){if(e.length<<3!==t.ivBits)throw new U("Invalid Initialization Vector length")}async function LH(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(ra(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function FH(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Ome(t,e,r,o,n){let[i,s,a]=await LH(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=hn(n,o,c,MO(n.length*8)),l=await FH(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Nme(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function Dme(t,e,r,o,n,i){let[s,a,c]=await LH(t,e,"decrypt"),u=hn(i,o,r,MO(i.length*8)),l=await FH(a,u,c);try{if(await Nme(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new ec}async function _S(t,e,r,o,n){if(!nc(r)&&!(r instanceof Uint8Array))throw new TypeError(ra(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?UH(t,o):o=Cme(t),r instanceof Uint8Array&&bS(r,t.cekBits),t.cbc)return Ome(t,e,r,o,n);let i=await ii(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function xS(t,e,r,o,n,i){if(!nc(e)&&!(e instanceof Uint8Array))throw new TypeError(ra(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new U("JWE Initialization Vector missing");if(!n)throw new U("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new U("Invalid Authentication Tag length");if(UH(t,o),e instanceof Uint8Array&&bS(e,t.cekBits),t.cbc)return Dme(t,e,r,o,n,i);let s=await ii(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,hn(r,n)))}catch{throw new ec}}function cg(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var zme=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],jme=[[],["deriveBits"]],IS=[[],[]];function SS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:zme,ops:["wrapKey","unwrapKey"]}}function ES(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:jme,ops:[void 0,"deriveBits"]}}function cp(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:IS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function BO(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:IS,ops:["deriveBits","deriveBits"]}}var na=cg({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:IS,ops:["encrypt","decrypt"]},"RSA-OAEP":SS(1),"RSA-OAEP-256":SS(256),"RSA-OAEP-384":SS(384),"RSA-OAEP-512":SS(512),"ECDH-ES":ES("direct-key-agreement"),"ECDH-ES+A128KW":ES("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":ES("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":ES("key-agreement-with-key-wrapping"),A128KW:cp(128),A192KW:cp(192),A256KW:cp(256),A128GCMKW:cp(128,!0),A192GCMKW:cp(192,!0),A256GCMKW:cp(256,!0),"PBES2-HS256+A128KW":BO(),"PBES2-HS384+A192KW":BO(),"PBES2-HS512+A256KW":BO()}),Mme=["encrypt","decrypt"];function up(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:IS,ops:Mme,cekBits:t,ivBits:e?128:96,cbc:e}}var Ume=cg({A128GCM:up(128),A192GCM:up(192),A256GCM:up(256),"A128CBC-HS256":up(256,!0),"A192CBC-HS384":up(384,!0),"A256CBC-HS512":up(512,!0)});function VH(t,e){throw new dt(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function si(t){return(typeof t=="string"?na[t]:void 0)??VH("alg","Algorithm")}function ai(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function Yu(t){return(typeof t=="string"?Ume[t]:void 0)??VH("enc","Encryption Algorithm")}function qH(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");VO(t,e)}async function Lme(t,e,r){let o=await ii(e,si(t).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 Fme(t,e,r){let o=await ii(e,si(t).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 BH(t,e,r){qO(e,si(t).subtle,r),sp(t,e)}async function KH(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new U("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new U("PBES2 Count Input must be a positive integer");let n=hn(Ir(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await ii(o,si(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KO(t){return hn(cS(t.length),t)}async function Vme(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await uS("sha256",hn(cS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function ZH(t,e,r,o,n=new Uint8Array,i=new Uint8Array){qH(t),qH(e,"deriveBits");let s=hn(KO(Ir(r)),KO(n),KO(i),cS(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return Vme(a,o,s)}function WH(t){yS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new dt("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function kS(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new U(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return Dn(r,e,U)}}function JH(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new U('JOSE Header "apu" and "apv" values must be distinct')}}function qme(t){if(t===void 0)throw new U("JWE Encrypted Key missing")}function HH(t){if(t!==void 0)throw new U("Encountered unexpected JWE Encrypted Key")}function Hme(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function GH(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return HH(o),r;let c=a==="direct-key-agreement";switch(c?HH(o):qme(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Yt(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(h=>Object.hasOwn(u,h)))throw new U('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');WH(r);let l=await ap(t,u),d=kS(n,"apu"),f=kS(n,"apv");JH(d,f);let p=await ZH(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return yS(r),BH(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new U('JOSE Header "p2c" (PBES2 Count) missing or invalid');Hme(i);let u=i??1e4;if(n.p2c>u)throw new U('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new U('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=Dn(n.p2s,"p2s",U);r=await KH(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new U('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new U('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=Dn(n.iv,"iv",U),l=Dn(n.tag,"tag",U);if(u.byteLength!==12)throw new U("Invalid Initialization Vector length");if(l.byteLength!==16)throw new U("Invalid Authentication Tag length");return xS(Yu(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Fme(s.slice(-6),r,o)}async function $S(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=ai(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await oi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Xu(e):void 0;l&&bS(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{WH(u);let{apu:p,apv:h}=i;p!==void 0&&Yn(p,'"apu"'),h!==void 0&&Yn(h,'"apv"');let g=p??kS(o,"apu"),y=h??kS(o,"apv");JH(g,y);let w;i.epk!==void 0?w=await oi(t,i.epk,"decrypt"):w=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,_=w;if(!_.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');_=await b.getPublicKey(w,[])}let{x:I,y:$,crv:C,kty:B}=await b.exportKey("jwk",_),Q=a==="direct-key-agreement",we=await ZH(u,w,Q?e.alg:s,Q?e.cekBits:parseInt(s.slice(-5,-2),10),g,y),xe={x:I,crv:C,kty:B};if(B==="EC"&&(xe.y=$),f={epk:xe},p!==void 0&&(f.apu=Nt(p)),h!==void 0&&(f.apv=Nt(h)),Q)return[we,void 0,f];u=we;break}case"RSA-OAEP":{yS(u),BH(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:h=crypto.getRandomValues(new Uint8Array(16))}=i;u=await KH(h,s,p,u),f={p2c:p,p2s:Nt(h)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let h=await _S(Yu(s.slice(0,-2)),l,u,p,new Uint8Array);d=h.ciphertext,f={iv:Nt(h.iv),tag:Nt(h.tag)}}}if(d??=await Lme(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,f]}function AS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new dt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new U('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function XH(t){if(typeof globalThis[t]>"u")throw new dt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function YH(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.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 U("Decompressed plaintext exceeded the configured limit")}return hn(...n)}async function QH(t){return XH("CompressionStream"),YH(new CompressionStream("deflate-raw"),t)}async function eB(t,e){return XH("DecompressionStream"),YH(new DecompressionStream("deflate-raw"),t,e)}function tB(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new U("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new U("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new U("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new U("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new U("JWE AAD incorrect type");if(s!==void 0&&!Yt(s))throw new U("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function rB(t){let e,r;try{let{header:o}=t;if(Yt(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function nB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new U("JWE Encrypted Key incorrect type");if(r!==void 0&&!Yt(r))throw new U("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new U("JOSE Header missing")}function ZO(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=ip(e,U,"JWE Protected Header is invalid")),[s,Dn(r,"ciphertext",U),o!==void 0?Dn(o,"iv",U):void 0,n!==void 0?Dn(n,"tag",U):void 0,dS((e??"")+(i!==void 0?`.${i}`:""),"aad",U)]}function TS(t){return[t&&ag("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&ag("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function WO(t,e,r,o=ZO(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!tc(n,u,l))throw new U("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,h,g,y,w]=e,{encrypted_key:b}=t;rc(U,fS,g,n,f),AS(f,n);let{alg:_,enc:I}=f;if(typeof _!="string"||!_)throw new U("missing JWE Algorithm (alg) in JWE Header");let $=na[_];if(b===""&&(!$||!ai($)))throw new U("JWE Encrypted Key incorrect type");let C=$?.mode==="integrated-encryption";if(!C&&(typeof I!="string"||!I))throw new U("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(_)||!p&&_.startsWith("PBES2"))throw new Wu('"alg" (Algorithm) Header Parameter value not allowed');let B;if(C){if(I!==void 0)throw new U('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new U("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new U("JWE Authentication Tag must be empty for integrated encryption")}else{if(h&&!h.has(I))throw new Wu('"enc" (Encryption Algorithm) Header Parameter value not allowed');B=Yu(I)}let Q;if(b!==void 0)try{Q=Dn(b,"encrypted_key",U)}catch(Ce){if(!$||!ai($))throw Ce;Q=new Uint8Array}let we=!1;typeof r=="function"&&(r=await r(n,t),we=!0);let xe=$??si(_);ai(xe)&&Q===void 0&&(Q=new Uint8Array);let Xe=await oi(xe.mode==="direct-encryption"?B:xe,r,"decrypt"),re;if(xe.mode==="integrated-encryption")re=await xe.decrypt(Xe,Q,i,c,n,f);else{let Ce=B,J;try{J=await GH(xe,Ce,Xe,Q,f,y),ai(xe)&&J instanceof Uint8Array&&J.byteLength<<3!==Ce.cekBits&&(J=Xu(Ce))}catch(Ct){if(Ct instanceof TypeError||Ct instanceof U||Ct instanceof dt)throw Ct;J=Xu(Ce)}re=await xS(Ce,J,i,s,a,c)}if(f.zip==="DEF"){let Ce=w??25e4;if(Ce===0)throw new dt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ce!==1/0&&(!Number.isSafeInteger(Ce)||Ce<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");re=await eB(re,Ce).catch(J=>{throw J instanceof U?J:new U("Failed to decompress plaintext",{cause:J})})}return{plaintext:re,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:Dn(d,"aad",U)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...we&&{key:Xe}}}async function oB(t,e,r){if(t instanceof Uint8Array&&(t=op.decode(t)),typeof t!="string")throw new U("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new U("Invalid Compact JWE");return WO({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function ug(t,e,r){return oB(t,TS(r),e)}async function JO(t,e,r){if(!Yt(t))throw new U("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new U("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Yt))throw new U("JWE Recipients missing or incorrect type");if(!n.length)throw new U("JWE Recipients has no members");let i,s,a;try{i=TS(r),s=tB(t),a=ZO(s)}catch{throw new ec}let c=n.map(u=>rB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?na[l]:void 0;if(d&&!ai(d))throw new U(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return nB(l),await WO(l,i,e,a)}catch{}throw new ec}function PS(t,e,r){if(!tc(t,e,r))throw new U("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function GO(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new U("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Yn(s,"JWE Additional Authenticated Data"),a!==void 0&&Yn(a,"JWE Content Encryption Key"),c!==void 0&&Yn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Gu(U,o)[0],t[1]=o),n!==void 0&&(n=Gu(U,n)[0],t[2]=n),!r&&i!==void 0&&(i=Gu(U,i)[0],t[3]=i),u!==void 0&&!Yt(u))throw new TypeError("JWE Key Management Parameters must be an object");PS(o,n,i);let d={...o,...n,...i};mS(U,o),rc(U,fS,l,o,d),AS(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new U('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=na[f];if(h?.mode==="integrated-encryption"){if(p!==void 0)throw new U('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 ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,h]}if(typeof p!="string"||!p)throw new U('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,Yu(p),h]}async function XO(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,h]=t,g=a,y=c,w=i??si(o.alg),b,_,I;w.mode==="integrated-encryption"?I=await oi(w,r,"encrypt"):[I,b,_]=await $S(w,n,r,o,d,p),_&&(h?y=y?{...y,..._}:_:g=g?{...g,..._}:_,PS(g,y,u));let $=g?Nt(JSON.stringify(g)):"",C=l?.byteLength?Nt(l):void 0,B=Ir(C?`${$}.${C}`:$),Q=s;o.zip==="DEF"&&(Q=await QH(Q).catch(Ce=>{throw new U("Failed to compress plaintext",{cause:Ce})}));let we,xe,Xe;w.mode==="integrated-encryption"?[b,we]=await w.encrypt(I,Q,B,g,o,p):{ciphertext:we,tag:xe,iv:Xe}=await _S(n,Q,I,f,B);let re={ciphertext:Nt(we)};return Xe&&(re.iv=Nt(Xe)),xe&&(re.tag=Nt(xe)),b?.byteLength&&(re.encrypted_key=Nt(b)),C&&(re.aad=C),g&&(re.protected=$),u&&(re.unprotected=u),y&&(re.header=y),re}async function iB(t,e,r){return XO(t,GO(t,r),e)}function sB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var YO=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return bo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return bo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},lg=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new YO(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return bo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return bo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new U("at least one recipient must be added");Yn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let h of this.#t){let[g,y,w,b]=h.state,_=[this.#e,o,g,n,this.#o,void 0,void 0,y,b,e],I=GO(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,I,w]);let[{alg:$,enc:C},,B]=I;if(e&&B&&!ai(B))throw new U(`"${$}" alg may only have a single recipient`);if(!r)r=C;else if(r!==C)throw new U('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,h]of i)h[2]??=si(h[0].alg);let[s,a,c]=i[0],u=e?Xu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await XO(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let h=1;h<i.length;h++){let[g,[y,w,b],_]=i[h],I=g[2],[,$,C]=await $S(b,w,_,y,u,g[7]),B={encrypted_key:Nt($)};if(I||C){let Q={...I,...C};C&&PS(g[1],Q,g[3]),B.header=Q}p.recipients.push(B)}return p}};var dg=[["verify"],["sign"]];function QO(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:dg}}function lp(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:dg,minRsaBits:2048}}function eN(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:dg}}function aB(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:dg}}function tN(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:dg}}var rN=cg({HS256:QO(256),HS384:QO(384),HS512:QO(512),RS256:lp(256),RS384:lp(384),RS512:lp(512),PS256:lp(256,32),PS384:lp(384,48),PS512:lp(512,64),ES256:eN("P-256",256),ES384:eN("P-384",384),ES512:eN("P-521",512),EdDSA:aB(),Ed25519:aB(),"ML-DSA-44":tN(44),"ML-DSA-65":tN(65),"ML-DSA-87":tN(87)});function RS(t){let e=typeof t=="string"?rN[t]:void 0;if(!e)throw new dt(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function cB(t){return[t&&ag("algorithms",t.algorithms),t?.crit]}function Bme(t){return t===void 0?{}:ip(t,At,"JWS Protected Header is invalid")}function Kme(t){try{return Ir(t)}catch{throw new At("JWS Compact Serialization payload must use only ASCII characters")}}async function Zme(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Bme(i);if(!tc(c,s))throw new At("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=hS(c,rc(At,pS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new At('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new Wu('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new At("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new At("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let h=RS(d),g=hn(i!==void 0?Ir(i):new Uint8Array,Ir("."),typeof f=="string"?e[2]??=dS(f,"payload",At):f),y=Dn(t.signature,"signature",At),w=await oi(h,r,"verify"),b=await ii(w,h.subtle,"verify");h.minRsaBits&&sp(h.alg,b);let _=!1;try{_=await crypto.subtle.verify(h.signing,b,y,g)}catch{}if(!_)throw new lS;let I={payload:typeof f=="string"?Dn(f,"payload",At):f};return i!==void 0&&(I.protectedHeader=c),s!==void 0&&(I.unprotectedHeader=s),p?[{...I,key:w},l]:[I,l]}async function uB(t,e,r){if(t instanceof Uint8Array&&(t=op.decode(t)),typeof t!="string")throw new At("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new At("Invalid Compact JWS");return Zme({payload:n,protected:o,signature:i},e,r,Kme)}async function nN(t,e,r){let[o]=await uB(t,cB(r),e);return o}var dp=class{#e;constructor(e){Yn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return bo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return bo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return bo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return bo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return sB(await iB([...this.#e],e,r))}};async function Wme(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=Gu(At,n);n=w[0],a=Nt(w[1])}if(i!==void 0&&(i=Gu(At,i)[0]),!n&&!i)throw new At("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!tc(n,i))throw new At("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};mS(At,n);let u=hS(n,rc(At,pS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new At('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=RS(l),f="",p=o,h;if(u){let w=t[4];w?(f=w[0]??=Nt(o),p=w[1]??=Ir(f)):(f=Nt(o),h=np.encode(`${a}.${f}`))}h??=hn(Ir(a),Ir("."),p);let g=await ii(await oi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&sp(d.alg,g);let y={signature:Nt(new Uint8Array(await crypto.subtle.sign(d.signing,g,h))),payload:f};return n&&(y.protected=a),i&&(y.header=i),[y,u]}async function lB(t,e,r,o,n){let[i]=await Wme([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var pg=class{#e;#t;constructor(e){Yn(e,"payload"),this.#e=e}setProtectedHeader(e){return bo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return lB(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var oN='"alg" (Algorithm)';function iN(t='JWK "alg" (Algorithm) Parameter'){throw new dt(`Invalid or unsupported ${t} value`)}function fg(t,e){return(typeof t=="string"?rN[t]??na[t]:void 0)??iN(e)}async function oc(t){if(LO(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Nt(t)};if(!nc(t))throw new TypeError(ra(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var oa=(t,e)=>{if(typeof t!="string"||!t)throw new sg(`${e} missing or invalid`)};async function sN(t,e){let r;if(Yt(t)){if(r=vS(t),typeof r.kty!="string")throw new TypeError(ra(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(FO(t))r=vS(await oc(t));else throw new TypeError(ra(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":oa(r.alg,'"alg" (Algorithm) Parameter'),oa(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":oa(r.crv,'"crv" (Curve) Parameter'),oa(r.x,'"x" (X Coordinate) Parameter'),oa(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":oa(r.crv,'"crv" (Subtype of Key Pair) Parameter'),oa(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":oa(r.e,'"e" (Exponent) Parameter'),oa(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 sg('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new dt('"kty" (Key Type) Parameter missing or unsupported')}let n=Ir(JSON.stringify(o));return Nt(await uS(e,n))}async function _o(t,e,r){if(!Yt(t))throw new TypeError("JWK must be an object");let o=HO(t),n=wS(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)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 Ju(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return ap(fg(e),o,n)}case"RSA":case"EC":case"OKP":return ap(fg(e),o,n);default:throw new dt('Unsupported "kty" (Key Type) Parameter value')}}function aN(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return ip(e,TypeError,r)}function Jme(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new dt("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function mg(t,e){let r=wS(e?.extractable),o=fg(t,oN);o.secret&&iN(oN);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new dt("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&&e?.crv!==void 0&&e.crv!==o.crv)throw new dt(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:Jme(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var mB=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),hB=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),dB=m.string().min(1).max(128),pB=m.string().min(1).max(16384),Gme=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:dB,secretAccessKey:pB}).strict(),m.object({kind:m.literal("session"),accessKeyId:dB,secretAccessKey:pB,sessionToken:m.string().min(1).max(16384),expiresAt:m.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),m.object({kind:m.literal("environment")}).strict()]),Xme=m.object({arn:hB,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),ia=m.object({authentication:Gme,region:mB,role:Xme.optional()}).strict(),CS=m.object({accountId:m.string().regex(/^\d{12}$/),principalId:m.string().min(1).max(256),arn:m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),OS=ia.extend({sourceIdentity:CS.optional(),identity:CS.optional()}).strict();function pp(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function fB(t){return{...t,arn:pp(t.arn)}}function gB(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:fB(t.sourceIdentity)}:{},...t.identity?{identity:fB(t.identity)}:{}}}var NS=m.object({authentication:m.enum(["access_key","session","environment"]),region:mB,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:hB.optional(),expiresAt:m.number().int().positive().optional()}).strict();function yB(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var vB=m.object({method:m.enum(["GET","POST","PUT","DELETE","PATCH"]),path:m.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),hg=m.object({account:m.string().min(1),identities:m.array(m.string()),user:m.string().nullable(),description:m.string().nullable(),roles:m.array(m.string()).nullable(),credentialId:m.number().int().positive(),rules:m.array(vB),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function wB(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return vB.parse({method:r[1],path:r[2]})})}typeof window<"u"&&m.config({jitless:!0});var x=m.uuid(),ne=m.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),be=m.iso.datetime(),ur=m.json(),pt=m.record(m.string(),ur),_B=m.enum(["ja","en"]),xB=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var SB=m.enum(["variable","connection","service","method","app","object","environment","function","keyring"]),Kr=m.object({kty:m.literal("EC"),crv:m.literal("P-256"),x:m.string().min(40).max(50),y:m.string().min(40).max(50)}).strict(),Yme=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:x}).strict(),MS=m.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return Yme.safeParse(aN(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Qn=m.object({protected:m.string().max(2048),iv:m.string().max(64),ciphertext:m.string().max(2e6),tag:m.string().max(64),aad:m.string().max(2048).optional(),recipients:m.array(m.object({encrypted_key:m.string().max(2048),header:m.object({kid:x,epk:Kr.optional(),alg:m.string().optional()}).passthrough()})).min(1).max(100)}).strict(),uVe=m.object({id:x,name:ne,publicKey:Kr}),ic=m.object({id:x,name:ne,owner:m.object({id:x,name:ne}).nullable(),createdAt:be,permissions:m.array(xB),createKinds:m.array(SB),publicKey:Kr.nullable()}),EB=m.object({id:x,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:be,lastUsedAt:be.nullable(),expiresAt:be.nullable(),canOpen:m.boolean()}),IB=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),Qme=m.object({subjectId:x,relation:IB,objectId:x}).strict(),lVe=Qme.extend({objectType:m.enum(["principal",...SB.options]),subjectName:ne,objectName:ne,createdAt:be}),dVe=m.object({error:m.object({code:m.string(),message:m.string(),details:ur.optional()})}),pVe=m.object({ok:m.literal(!0)}),ehe=m.object({value:m.string().min(1).max(200),label:m.string().min(1).max(200),values:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).default({})}).strict(),US=m.object({name:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:m.string(),secret:m.boolean().optional(),inputType:m.enum(["text","password"]).optional(),required:m.boolean().optional(),placeholder:m.string().optional(),note:m.string().optional(),pattern:m.string().optional(),choices:m.array(ehe).min(1).max(100).optional(),defaultValue:m.string().max(1e3).optional(),when:m.object({field:m.string(),values:m.array(m.string()).min(1)}).strict().optional(),visibility:m.enum(["application","connection"]).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),cN=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),the=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.union([m.string(),m.array(m.union([m.string().max(8192),m.object({pointer:m.string().max(1e3)}).strict()])).min(1).max(32)])),uN=m.object({values:m.array(m.object({id:m.string(),name:m.string(),description:m.string().optional()})).optional(),default:m.array(m.string()).default([]),required:m.array(m.string()).optional(),separator:m.string().default(" "),docs:m.url().optional()}),Qu=m.string().min(1).max(4096),zS=m.union([m.string(),m.array(m.string()).min(1)]),rhe=m.object({browserTokenExchange:m.enum(["available","unavailable","unknown"]).optional(),application:m.enum(["required","implicit"]).default("required"),grantType:m.enum(["authorization_code","client_credentials"]).optional(),issuer:m.url().optional(),registrationUrl:m.url().optional(),authorizeUrl:Qu.optional(),tokenUrl:Qu,identity:m.object({url:Qu.optional(),from:m.enum(["token","app"]).optional(),method:m.enum(["GET","POST"]).default("GET"),id:zS.default("/id"),name:zS.default("/name"),headers:m.record(m.string(),m.string()).default({})}).optional(),revoke:m.object({url:Qu,style:m.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:m.enum(["body","basic","none"]).optional(),tokenOnly:m.literal(!0).optional()}).optional(),clientAuth:m.enum(["body","basic","none"]).default("body"),pkce:m.boolean().default(!0),tokenFormat:m.enum(["form","json"]).default("form"),okPointer:m.string().optional(),authorizeParams:m.record(m.string(),m.string()).default({}),tokenParams:m.record(m.string(),m.string()).default({}),defaults:m.record(m.string(),m.string()).default({}),scopes:uN.default({default:[],separator:" "}),fields:m.array(US).default([]),outputs:cN.default({ACCESS_TOKEN:"/accessToken"}),adapter:m.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:m.array(m.string()).default([]),hint:m.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),nhe=m.object({fields:m.array(US).min(1),outputs:the,resolver:m.literal("vultr-role").optional(),bindFields:m.boolean().optional(),constants:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).optional(),identity:m.object({url:Qu,headers:m.record(m.string(),m.string()),id:zS,name:zS}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),lN=m.enum(["oauth","token","aws","ovh","approval"]),ohe=m.object({hint:m.string().optional()}).strict(),ihe=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:Qu,fields:m.array(US).min(1),scopes:uN.default({default:[],separator:`
|
|
129
|
+
`}),outputs:cN,hint:m.string().optional()}).strict(),fp=m.string().regex(/^[A-Z_][A-Z0-9_]*$/),bB=m.union([m.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),m.object({output:fp}).strict()]),LS=m.object({urlField:m.string().min(1).max(100).optional(),authentication:m.discriminatedUnion("kind",[m.object({kind:m.literal("none")}).strict(),m.object({kind:m.literal("bearer"),token:fp}).strict(),m.object({kind:m.literal("basic"),username:fp,password:fp}).strict(),m.object({kind:m.literal("header"),name:bB,value:fp}).strict(),m.object({kind:m.literal("query"),name:bB,value:fp}).strict()])}).strict(),vg={name:ne,docs:m.url().optional(),console:Qu.optional(),http:LS.optional(),preparation:m.object({scopeSelection:m.enum(["optional","required","hidden"]).default("optional"),instructions:m.array(m.union([m.string().max(2e3),m.object({ja:m.string().max(2e3),en:m.string().max(2e3)}).strict()])).max(10).default([]),docs:m.boolean().default(!1)}).strict().optional()},FS=m.object({...vg,kind:m.literal("oauth"),config:rhe}).strict(),VS=m.object({...vg,kind:m.literal("token"),config:nhe}).strict(),qS=m.object({...vg,kind:m.literal("aws"),config:ohe}).strict(),HS=m.object({...vg,kind:m.literal("ovh"),config:ihe}).strict(),BS=m.object({...vg,kind:m.literal("approval"),config:m.object({adapter:m.literal("runpod-flash"),fields:m.array(US).default([]),scopes:uN.default({default:[],separator:" "}),outputs:cN,hint:m.string().optional()}).strict()}).strict(),sc=m.discriminatedUnion("kind",[FS,VS,qS,HS,BS]),gg={id:m.string().min(1),builtin:m.boolean(),availability:m.enum(["ready","app-required","unavailable"]),defaultName:ne,registration:m.object({kind:m.enum(["input","authorization"]),device:m.enum(["browser","cli"]),browserExchange:m.enum(["available","unavailable","unknown"]),tokenAlternatives:m.array(m.string())}).strict()},wg=m.discriminatedUnion("kind",[FS.extend(gg),VS.extend(gg),qS.extend(gg),HS.extend(gg),BS.extend(gg)]),yg=m.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),dN=m.object({name:ne,logo:m.string().regex(/^[a-z0-9-]+$/).optional(),api:m.url().optional(),docs:m.url().optional(),console:m.url().optional(),targets:m.array(m.object({id:yg,name:ne,api:m.url().optional(),methods:m.array(yg).min(1)}).strict()).max(32).optional()}).strict(),she=dN.extend({methods:m.record(yg,m.string().min(1))}).strict(),kB=dN.extend({methods:m.record(yg,m.union([m.string().min(1),sc]))}).strict(),fVe=dN.extend({id:m.string(),builtin:m.boolean(),methods:m.record(yg,wg)}),$B=m.object({id:x,output:m.string().min(1).max(100).optional()}).strict(),AB=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),pN=m.object({name:m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:$B,format:m.enum(["text","file","json"]).default("text"),pointer:m.string().optional()}).strict(),ahe=m.object({pointer:m.string().max(500),parts:m.array(m.union([m.string().max(8192),$B])).min(1).max(32)}).strict(),ac=m.object({url:m.string().min(1).max(4096).optional(),connectionId:x.optional(),method:m.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:m.record(m.string(),m.string().max(8192)).default({}),body:m.string().max(1e6).optional(),json:ur.optional(),form:m.record(m.string(),m.string()).optional(),bindings:m.array(ahe).max(32).default([])}).strict().refine(t=>!!(t.url||t.connectionId),{message:"Choose a connection or enter a destination URL."}),cc=m.object({command:m.array(m.string().max(8192)).min(1).max(100),stdin:m.string().max(1e6).optional(),timeoutSeconds:m.number().int().min(1).max(3600).default(60),inputs:m.array(pN).max(32).default([])}).strict(),TB=m.discriminatedUnion("kind",[cc.omit({stdin:!0}).extend({kind:m.literal("command")}).strict(),m.object({kind:m.literal("http"),request:ac,responseFormat:m.enum(["text","json"]).default("json")}).strict()]),eo=m.object({description:m.string().max(2e3).default(""),program:TB,parameters:m.array(m.object({name:m.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:m.string().max(100),type:m.enum(["string","number","boolean","json"]).default("string"),required:m.boolean().default(!0),default:ur.optional()}).strict()).max(32).default([]),result:m.enum(["text","json"]).default("json")}).strict(),el=m.object({expiresAt:be.nullable().default(null)}).strict(),PB=m.object({version:m.number().int().nonnegative(),environmentId:x.nullable(),inputAccess:el,state:m.enum(["publication_required","unconfigured","configured","approval_required","unavailable","expired"])}).strict(),sa={id:x,ownerId:x,name:ne,createdAt:be,updatedAt:be,version:m.number().int().positive(),permissions:m.array(xB)},che=m.enum(["starting","running","stopping","stopped","failed"]),uhe=m.enum(["manual","idle","timeout","quota","capacity","payment"]),lhe=m.object({state:m.enum(["pending","failed","complete"]),error:m.string().nullable()}),dhe=m.object({idleSeconds:m.number().int().min(60).max(2147483647).nullable().default(null),maxSeconds:m.number().int().min(60).max(2147483647).nullable().default(null)}).strict(),RB=m.object({size:m.enum(["small","medium","large"]).default("small"),lifetime:dhe.default({idleSeconds:null,maxSeconds:null}),ssh:sS.optional()}).strict(),fN={recipients:m.array(x).default([]),executors:m.array(x).default([]),custodyRevision:m.number().int().positive().nullable().default(null)},phe=m.object({...sa,kind:m.literal("variable"),data:m.object({...fN,bytes:m.number().int().nonnegative()})}),fhe=m.object({...sa,kind:m.literal("connection"),data:m.object({...fN,methodId:m.string(),fields:m.record(m.string(),m.string()).default({}),settings:m.array(m.object({name:m.string(),label:m.string(),value:m.string()})).default([]),methodName:m.string(),methodKind:lN,http:LS.optional(),services:m.array(m.object({id:m.string(),name:ne})).default([]),account:m.string(),accountId:m.string().nullable().default(null),accountVerified:m.boolean().default(!1),scopes:m.array(m.string()),scopesStatus:m.enum(["unknown","requested","reported"]).default("unknown"),outputs:m.array(m.string()),state:m.enum(["ready","reconnect","review","disconnecting","uncertain"]),revocable:m.boolean().default(!1),appId:x.nullable(),generation:x.optional(),authorizationDigest:m.string().optional(),aws:NS.optional(),ovh:hg.optional()})}),mhe=m.object({...sa,kind:m.literal("service"),data:she}),hhe=m.object({...sa,kind:m.literal("method"),data:sc}),ghe=m.object({...sa,kind:m.literal("app"),data:m.object({...fN,methodId:m.string(),clientId:m.string(),fields:m.record(m.string(),m.string()).default({}),generation:x.optional()})}),yhe=m.object({...sa,kind:m.literal("object"),data:m.object({size:m.number().int().nonnegative(),contentType:m.string()})}),vhe=m.object({...sa,kind:m.literal("environment"),data:RB.extend({executorId:x.optional(),operatorId:x.optional(),driver:m.enum(["attached","managed"]).optional(),capabilities:m.array(m.string()).optional(),isolation:m.enum(["process","container"]).optional(),manifestDigest:m.string().optional(),processes:m.object({workingDirectory:m.string()}).optional(),ssh:zO.optional(),awsPrincipal:m.string().optional(),state:che,connected:m.boolean(),deletion:lhe.optional(),startedAt:be.nullable(),stoppedAt:be.nullable(),stopReason:uhe.nullable().default(null),lastActiveAt:be,error:m.string().nullable()})}),KS=m.object({...sa,kind:m.literal("function"),data:eo.omit({program:!0}).extend({program:TB.optional()})}),whe=m.object({...sa,kind:m.literal("keyring"),data:m.object({revision:m.number().int().positive(),signature:m.string()})}),Ut=m.discriminatedUnion("kind",[phe,fhe,mhe,hhe,ghe,yhe,vhe,KS,whe]),mVe=m.discriminatedUnion("kind",[m.object({kind:m.literal("service"),name:ne,definition:kB}).strict(),m.object({kind:m.literal("method"),name:ne,definition:sc}).strict(),m.object({kind:m.literal("environment"),name:ne.optional(),options:RB}).strict()]),hVe=m.object({version:m.number().int().positive(),name:ne.optional(),definition:m.union([kB,sc]).optional()}).strict(),ci=m.object({name:m.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:pt}).strict(),ZS=ci.extend({inputs:m.array(m.object({pointer:m.string(),label:m.string().min(1).max(100),secret:m.boolean().default(!1),multiline:m.boolean().default(!1),site:m.url().optional()}).strict()).max(16).default([])}),jS=m.object({ja:m.string(),en:m.string()}).strict(),mN=ZS.extend({title:jS,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:m.object({required:m.boolean(),reason:jS.nullable()}).strict()}),CB=m.object({to:x.optional(),executionId:x.optional(),message:m.string().max(1e3).default(""),operations:m.array(ZS).min(1).max(8).optional(),expiresInMinutes:m.number().int().min(1).max(1440).default(30)}).strict().superRefine((t,e)=>{!!t.executionId==!!t.operations&&e.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),DS=m.object({id:x,name:ne}),OB=m.discriminatedUnion("kind",[m.object({kind:m.literal("line"),subject:DS,relation:IB,object:DS}),m.object({kind:m.literal("transfer"),item:DS,to:DS})]),WS=m.object({id:x,executionId:x,from:ic.pick({id:!0,name:!0}),to:ic.pick({id:!0,name:!0}).nullable(),message:m.string(),purpose:m.enum(["input","approval"]),state:m.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:be,expiresAt:be,url:m.url(),code:m.string().optional(),returnUrl:m.url().nullable(),refreshUrl:m.url().nullable(),canRespond:m.boolean(),canCancel:m.boolean()}),gVe=m.object({id:x,name:ne,publicKey:Kr,state:m.enum(["pending","approving","approved"]),principalId:x.nullable(),createdAt:be,expiresAt:be}),yVe=m.object({available:m.boolean(),required:m.boolean(),active:m.boolean(),payer:ic.pick({id:!0,name:!0}).nullable()}),vVe=m.object({storageBytes:m.number().nonnegative(),storageLimit:m.number().positive(),computeSeconds:m.number().nonnegative(),computeLimit:m.number().positive(),month:m.string()}),wVe=m.object({id:m.string(),actorId:x.nullable(),action:m.string(),targetId:x.nullable(),createdAt:be,details:pt}),bVe=m.object({returnUrl:m.url().optional(),refreshUrl:m.url().optional()}).strict(),lr=t=>m.object({items:m.array(t),next:m.string().nullable().default(null)}),_Ve=m.object({id:x}),xVe=m.object({owner:x}),bhe=m.object({limit:m.coerce.number().int().min(1).max(200).default(100),after:m.string().optional()}),SVe=bhe.extend({object:x.optional(),subject:x.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var _he=m.object({email:m.boolean(),environments:m.boolean(),ssh:m.boolean(),storage:m.boolean(),payments:m.boolean()}),JS=m.object({principal:ic.nullable(),credentialId:x.nullable(),wrappedKey:MS.nullable(),requestId:x.nullable(),server:m.object({name:ne}),features:_he,principals:m.array(ic)}),$Ve=m.object({email:m.email().max(254),returnTo:m.string().max(2048).optional(),locale:_B.default("ja"),principalId:x.optional()}).strict(),AVe=m.object({intent:m.enum(["register","authenticate"]),name:ne.optional(),principalId:x.optional(),credentialId:x.optional(),returnTo:m.string().max(2048).optional()}).strict(),TVe=m.object({challengeId:x,credential:m.json(),publicKey:Kr.optional(),existingPublicKey:Kr.optional(),wrappedKey:MS.optional()}).strict();var xhe=new TextEncoder,She=new TextDecoder,bg="ECDH-ES+A256KW",hN="A256GCM",Ye=t=>xhe.encode(t),gn=t=>She.decode(t);function aa(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function GS(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function XS(){let t=await mg(bg,{crv:"P-256",extractable:!0});return{publicKey:Kr.parse(await oc(t.publicKey)),privateKey:await oc(t.privateKey)}}async function uc(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new lg(t).setProtectedHeader({enc:hN}).setAdditionalAuthenticatedData(Ye(r));for(let n of e)o.addRecipient(await _o(n.publicKey,bg)).setUnprotectedHeader({alg:bg,kid:n.id});return Qn.parse(await o.encrypt())}async function xo(t,e,r,o){if(t.aad!==aa(Ye(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await _o(e,bg);return(await JO({...t,recipients:[n]},i,{keyManagementAlgorithms:[bg],contentEncryptionAlgorithms:[hN]})).plaintext}async function Ehe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:Ye("Foundation"),info:Ye("passkey encryption key")},e,256))}async function NB(t,e,r){let o=await ug(t,await Ehe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[hN]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(gn(o.plaintext))}var Dt=m.string().regex(/^[A-Za-z0-9_-]{43}$/),zt=m.string().min(100).max(4e6),DB=Kr.extend({d:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}),_g=m.object({encryption:DB,signing:DB}).strict(),bt=m.object({id:x,principalId:x,generation:m.number().int().positive(),previous:Dt.nullable(),encryption:Kr,signing:Kr}).strict();function P(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,P).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+P(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function mp(t){return sN(Kr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function oe(t){return aa(new Uint8Array(await crypto.subtle.digest("SHA-256",Ye(P(t)))))}async function tl(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",Ye(P(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function zB(){let[t,e]=await Promise.all([XS(),mg("ES256",{crv:"P-256",extractable:!0})]),r=await oc(e.privateKey);return _g.parse({encryption:t.privateKey,signing:r})}function YS(t){return Kr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function jB(t,e){return bt.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:YS(e.encryption),signing:YS(e.signing)})}async function Jt(t,e,r){let o=e instanceof CryptoKey?e:await _o(e,"ES256");return new pg(Ye(P(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Zr(t,e,r,o){if(P(await xg(e,r,o))!==P(t))throw new Error("The signature does not authorize this content.")}async function xg(t,e,r){let o=await nN(t,await _o(Kr.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(P(i)!==n)throw new Error("Sign canonical JSON content.");return i}var ca=m.object({binding:bt,signature:zt}).strict();async function gN(t,e){if(await ua(t),await mp(e.encryption)!==await mp(t.encryption)||await mp(e.signing)!==await mp(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await Jt(t,e.signing,"key-binding")}}async function ua(t){let e=bt.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await mp(e.encryption)===await mp(e.signing))throw new Error("Use separate encryption and signing keys.");await _o(e.encryption,"ECDH-ES+A256KW"),await _o(e.signing,"ES256")}async function QS(t){let{binding:e,signature:r}=ca.parse(t);return await ua(e),await Zr(e,r,e.signing,"key-binding"),e}var MB=m.object({ownerId:x,name:ne,resourceId:x.optional(),version:m.number().int().positive().optional(),environmentIds:m.array(x).max(32).optional()}).strict(),UB=MB.extend({value:m.literal("").optional()}),yN=MB.extend({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}),hp=m.object({ownerId:x,name:ne,definition:eo,resourceId:x.optional(),version:m.number().int().positive().optional()}).strict(),e0=m.object({functionId:x,functionVersion:m.number().int().positive(),version:m.number().int().nonnegative(),environmentId:x.nullable(),inputAccess:el.default({expiresAt:null})}).strict(),vN=m.object({ownerId:x,connectionId:x,environmentId:x}).strict(),LB=m.object({ownerId:x,connectionId:x,version:m.number().int().positive(),users:m.array(x).max(32),expiresAt:m.iso.datetime().optional()}).strict(),FB=m.object({ownerId:x,methodId:m.string().min(1).max(200),connectionId:x.optional(),name:ne.optional(),appId:x.optional(),redirectUri:m.url().optional(),users:m.array(x).max(32).optional(),scopes:m.array(m.string().min(1).max(1e3)).max(200).optional(),methodDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:m.string().max(1e3).optional(),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}).strict(),t0=m.object({ownerId:x,environmentId:x.optional(),operation:m.union([m.object({kind:m.literal("http"),request:ac}).strict(),cc.extend({kind:m.literal("command")}),m.object({kind:m.enum(["http","command"]),programId:x,programDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:m.record(m.string(),ne).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),r0=m.object({name:ci.shape.name,title:jS,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:mN.shape.environment,input:pt}).strict(),VB=m.object({id:x.optional(),operations:m.array(ZS).min(1).max(8),responderId:x.optional(),message:m.string().max(1e3).default(""),expiresInMinutes:m.number().int().min(1).max(1440).default(1440)}).strict(),qB=m.object({values:m.array(pt).max(8).default([]),configuration:m.array(pt).max(8).default([]),code:m.string().max(20).optional()}).strict(),gp=m.object({index:m.number().int().nonnegative(),invocation:ci,approval:m.object({id:x,index:m.number().int().nonnegative()}).strict().optional(),continuation:m.object({kind:m.enum(["connection","run"]),id:x}).strict().nullable()}).strict(),Ee=m.object({id:x,actorId:x,ownerId:x,requests:m.array(x),steps:m.array(m.object({index:m.number().int().nonnegative(),name:ci.shape.name,state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:m.array(m.object({kind:m.enum(["run","function","process"]),id:x}).strict())}).strict()),creator:ic.pick({id:!0,name:!0}),operations:m.array(mN),approval:m.object({requestId:x.nullable(),proposal:OB.nullable()}).strict().nullable(),canContinue:m.boolean(),canCancel:m.boolean(),url:m.url(),code:m.string().optional(),error:m.object({code:m.string(),message:m.string()}).strict().nullable(),index:m.number().int().nonnegative(),state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:m.enum(["approval","input","execution"]).nullable(),waiting:gp.nullable(),results:m.array(ur.nullable()),createdAt:m.iso.datetime(),expiresAt:m.iso.datetime()}).strict(),HB=m.object({id:x,index:m.number().int().nonnegative(),invocation:ci,continuationId:x.optional()}).strict();var vp=m.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ge={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},Ihe=m.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),KB=t=>t===ge.executionResult?14e5:1e6,ie={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},Sg=m.enum([ie.http,ie.command,ie.function,ie.connect,ie.refresh,ie.revoke]);var khe={[ge.value]:[ie.http,ie.command,ie.function],[ge.tokenSet]:[ie.http,ie.command,ie.function,ie.refresh,ie.revoke],[ge.clientCredential]:[ie.connect,ie.refresh,ie.revoke],[ge.executionResult]:[]},lc=t=>khe[t],ZB=t=>lc(t).filter(e=>e===ie.function||e===ie.refresh),wN=t=>t===ge.tokenSet,$he=m.object({id:x,digest:Dt}).strict(),Ahe=m.object({actor:bt,executor:bt,operations:m.array(Sg).min(1).max(6),functionDigests:m.array(Dt).max(100).default([]),origins:m.array(vp).max(100).default([]),callerProgram:m.boolean().default(!1),expiresAt:be}).strict(),The=m.object({function:$he,executor:bt,operations:m.array(Sg).min(1).max(6),expiresAt:be.nullable()}).strict(),Phe=m.union([Ahe,The]);function nl(t,e=Date.now()){return t.expiresAt===null||Date.parse(t.expiresAt)>e}function n0(t){return t.expiresAt===null?1/0:Date.parse(t.expiresAt)}var kr=m.object({format:m.literal(2),origin:vp,id:x,ownerId:x,contentType:Ihe,revision:m.number().int().positive(),authorities:m.array(bt).min(1).max(100),readers:m.array(bt).min(1).max(100),grants:m.array(Phe).max(100),observers:m.array(x).max(100).optional(),producers:m.array(m.object({executor:bt,runId:x,expiresAt:be,materialRevision:m.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),BB=m.object({ownerId:x,authorities:m.array(bt).min(1).max(100)}).strict(),WB=m.object({origin:vp,id:x,revision:m.number().int().positive(),from:BB,to:BB,policyDigest:Dt,previous:Dt.nullable(),signerId:x}).strict(),Rhe=WB.extend({signature:zt}),bN=m.array(Rhe).max(16),Eg=m.object({policy:kr,authorityId:x,signature:zt,lineage:bN.optional()}).strict(),$r=m.object({policy:kr,authorityId:x,authorization:zt,lineage:bN.optional(),materialRevision:m.number().int().positive(),updatedAt:be,creationRunId:x.nullable(),metadata:pt,sealed:Qn,signerId:x,signature:zt}).strict(),rl=t=>({ownerId:t.ownerId,authorities:t.authorities});async function JB(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||P(r.to)!==P(o.from))||o.previous!==(r?await oe(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await Zr(i,n,s.signing,"authority-handoff"),r=o}if(r&&P(r.to)!==P(rl(t)))throw new Error("Use the authorities approved by the latest handoff.")}function _N(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function o0(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=P(rl(t));return r===P(rl(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&P(o.from)===r)}async function GB(t,e,r,o){let n=[...t?.lineage??[]];if(t&&P(rl(t.policy))!==P(rl(e))){if(await ui(t),!t.policy.authorities.some(s=>P(s)===P(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=WB.parse({origin:e.origin,id:e.id,revision:e.revision,from:rl(t.policy),to:rl(e),policyDigest:await oe(e),previous:n.length?await oe(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await Jt(i,o.signing,"authority-handoff")})}return n.length?{lineage:bN.parse(n)}:{}}async function i0(t){let e=kr.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await ua(n);let i=P(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!lc(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==ie.function&&i!==ie.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===ie.http||i===ie.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(ie.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function s0(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function dc(t,e){return P({purpose:"resource",policyDigest:await oe(t),materialRevision:e})}async function ol(t,e,r,o,n,i,s){if(t.byteLength>KB(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await i0(e),c=await GB(s,a,o,n);if(!a.authorities.some(f=>P(f)===P(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await uc(t,s0(a).map(f=>({id:f.id,publicKey:f.encryption})),await dc(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await Jt(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ge.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=$r.parse({...l,signature:await Jt(l,n.signing,"resource")});return await ui(d),d}async function ui(t){let e=$r.parse(t),{signature:r,...o}=e;await i0(e.policy),await JB(e.policy,e.lineage);let n=_N(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await oe(e.policy))throw new Error("The handoff approves a different access policy.");await Zr(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&(e.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(wN(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(ie.refresh)&&nl(u,Date.parse(e.updatedAt)))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Zr(o,r,s.signing,"resource");let a=s0(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(P(a)!==P(c)||e.sealed.aad!==aa(Ye(await dc(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function XB(t,e,r,o,n=t.metadata){let i=await ui(t);if(!wN(i.policy.contentType)||!(i.policy.authorities.some(f=>P(f)===P(r))||i.policy.grants.some(f=>P(f.executor)===P(r)&&f.operations.includes(ie.refresh)&&nl(f))))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await uc(e,s0(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await dc(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await Jt(l,o.signing,"resource")};return await ui(d),d}async function a0(t,e,r,o){let n=await i0(t);if(!n.authorities.some(s=>P(s)===P(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await GB(o,n,e,r),authorityId:e.id,signature:await Jt(n,r.signing,"access-policy")};return await Ig(i),i}async function Ig(t){let e=Eg.parse(t);await i0(e.policy),await JB(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await oe(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await Zr(e.policy,e.signature,o.signing,"access-policy"),e}async function YB(t,e,r,o,n,i){let s=await Ig(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&P(f.executor)===P(o)&&(a.contentType===ge.executionResult||Date.parse(f.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>KB(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await uc(t,s0(a).map(f=>({id:f.id,publicKey:f.encryption})),await dc(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await Jt(l,n.signing,"resource")};return await ui(d),d}async function il(t,e,r){let o=await ui(t);if(!o.policy.readers.some(n=>P(n)===P(e)))throw new Error("This identity cannot reveal the content.");return xo(o.sealed,r,e.id,await dc(o.policy,o.materialRevision))}var Che=m.object({id:x,policyDigest:Dt,materialRevision:m.number().int().positive(),authorizationDigest:Dt.optional()}).strict();async function Ohe(t,e){return e.id===t.policy.id&&e.policyDigest===await oe(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||wN(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var c0=m.object({format:m.literal(2),id:x,origin:vp,ownerId:x,approval:m.object({id:x,index:m.number().int().min(0).max(7)}).strict().optional(),operationContext:HB.optional(),actor:bt,environmentId:x,executor:bt,environmentDigest:Dt,operation:Sg,functionDigest:Dt.nullable(),functionId:x.optional(),operationDigest:Dt,sources:m.array(Che).max(100),resultRecipients:m.array(bt).min(1).max(100),resultApproval:Eg.optional(),createdAt:be,expiresAt:be}).strict(),kg=m.object({intent:c0,signature:zt,sealed:Qn}).strict();async function u0(t,e){return P({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await oe(t)})}async function QB(t,e,r){if(c0.parse(t),await oe(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await uc(Ye(P(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await u0(t,"input"))};return kg.parse({...o,signature:await Jt(o,r.signing,"run")})}async function yp(t,e,r={}){let o=await ui(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await Ohe(o,i))throw new Error("The input changed after this execution was authorized.");if(P(e.actor)===P(e.executor)&&n.readers.some(c=>P(c)===P(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?P(c.actor)===P(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&P(c.executor)===P(e.executor)&&c.operations.includes(e.operation)&&nl(c,r.now)&&n0(c)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===ie.function||e.operation===ie.refresh:e.operation===ie.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||!r.destinationPending&&c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==ie.command&&e.operation!==ie.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function $g(t,e,r,o={}){let n=o.destination;await yp(t,e,{now:o.now,...typeof n=="function"?{destinationPending:!0}:{destination:n}});let i=await xo(t.sealed,r.encryption,e.executor.id,await dc(t.policy,t.materialRevision));return typeof n=="function"&&await yp(t,e,{now:o.now,destination:n(i)}),i}var SN=5,eK=1,Nhe=m.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Dhe=m.object({format:m.literal(3),id:x,origin:vp,ownerId:x,name:ne,executor:bt,operatorId:x,driver:m.literal("attached"),capabilities:m.array(Sg).min(1).max(6),functionVersion:m.number().int().positive().optional(),httpVersion:m.number().int().positive().optional(),resultVersion:m.literal(1).optional(),isolation:m.enum(["process","container"]),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),functionImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:Nhe.optional(),revision:m.number().int().positive()}).strict(),EN=m.object({manifest:Dhe,signature:zt}).strict();async function IN(t){let e=EN.parse(t),{manifest:r}=e;if(await ua(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(ie.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");return await Zr(r,e.signature,r.executor.signing,"environment"),e}async function tK(t,e){let{manifest:r}=await IN(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await oe(r)||P(e.executor)!==P(r.executor)||!r.capabilities.includes(e.operation)||e.operation===ie.function&&r.functionVersion!==SN)throw new Error("This environment does not authorize the requested execution.")}var l0=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),kN=m.object({ok:m.boolean(),result:ur.nullable(),error:m.object({code:m.string().max(100),message:m.string().max(1e3)}).nullable()}).strict(),rK={id:x,intentDigest:Dt,executorId:x,state:m.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:be},nK=m.object({...rK,sealed:Qn,signature:zt}).strict(),oK=m.object({...rK,format:m.literal(2),accessDigest:Dt,proofDigest:Dt,approval:Eg,content:$r,previousDigest:Dt.optional(),previous:nK.optional(),signature:zt}).strict(),d0=m.union([nK,oK]),zhe=m.object({result:kN,proof:zt}).strict(),iK=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function sK(t,e,r,o,n,i){await Ig(n);let s={format:2,id:t.id,intentDigest:await oe(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await oe(n),...i?{previousDigest:await oe(i)}:{}},a=await Jt({...s,resultDigest:await oe(r)},o.signing,"execution-result"),c=Ye(P({result:kN.parse(r),proof:a}));if(c.byteLength>14e5)throw new xN;let u=await YB(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await oe(a)},d=oK.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await Jt(l,o.signing,"receipt")});return await $N(d,t),d}var xN=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function $N(t,e){let r=d0.parse(t);if("content"in r){await Zr(iK(r),r.signature,e.executor.signing,"receipt");let i=await Ig(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await oe(e)||r.executorId!==e.executor.id||r.accessDigest!==await oe(i)||i.authorityId!==e.actor.id||!s.authorities.some(a=>P(a)===P(e.actor))||s.id!==e.id||s.origin!==e.origin||s.ownerId!==e.ownerId||s.contentType!==ge.executionResult||s.grants.length||e.resultApproval&&P(e.resultApproval)!==P(i))throw new Error("The result does not belong to the requested execution.");if(!e.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await oe(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await $N(r.previous,e),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await ui(r.content),!o0(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(e.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:o,...n}=r;if(await Zr(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await oe(e)||r.executorId!==e.executor.id||r.sealed.aad!==aa(Ye(await u0(e,"result")))||P(r.sealed.recipients.map(i=>i.header.kid).sort())!==P(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function aK(t,e,r,o){if(await $N(t,e),"content"in t){if(!t.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await xo(t.content.sealed,o.encryption,r,await dc(t.content.policy,t.content.materialRevision)),a=zhe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await oe(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=iK(t);if(await Zr({...u,resultDigest:await oe(a.result)},a.proof,e.executor.signing,"execution-result"),t.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await xo(t.sealed,o.encryption,r,await u0(e,"result")),i=kN.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var jhe=m.enum(["http","command","function","connect","refresh","revoke"]),yn=m.object({id:x,ownerId:x,actorId:x,environmentId:x,kind:jhe,state:l0,intent:c0,requestSignature:zt,receipt:d0.nullable(),error:m.string().nullable(),createdAt:be,startedAt:be.nullable(),finishedAt:be.nullable()}).strict(),p0=m.object({name:ne,approval:Eg}).strict(),eqe=m.object({kind:m.literal("function"),functionId:x,definition:eo,arguments:pt.default({}),outputs:m.record(m.string(),p0).default({})}).strict(),sl=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:ac,save:m.record(m.string(),p0).default({})}).strict(),m.object({kind:m.literal("command"),...cc.shape}).strict(),m.object({kind:m.enum(["connect","refresh","revoke"]),input:ur}).strict()]);var wp=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},pc=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,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=m.object({error:m.object({code:m.string(),message:m.string()})}).parse(await n.json())}catch{throw new wp("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new wp(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await this.response(e,r),i=n.status===204?null:await n.json();return o?o.parse(i):i}async session(){return this.json("/api/session",{},JS)}};import{chmod as Mhe,lstat as Uhe,mkdir as Lhe,open as AN,readFile as uK,rename as Fhe,rm as Vhe}from"node:fs/promises";import{dirname as qhe,join as TN,resolve as Hhe}from"node:path";import{homedir as Bhe}from"node:os";import{randomUUID as Khe}from"node:crypto";var PN=m.object({origin:m.url(),principalId:m.uuid(),token:m.string().min(20),keys:_g.nullable(),binding:bt.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),lK=m.object({current:m.uuid(),identities:m.array(PN).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function la(){return TN(process.env.XDG_CONFIG_HOME||TN(Bhe(),".config"),"foundation","identity.json")}function bp(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function RN(){try{let t=la(),e=await Uhe(t);if(!e.isFile()||e.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&e.mode&63&&await Mhe(t,384),lK.parse(JSON.parse(await uK(t,"utf8")))}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function dK(){let t=await RN();return(t?.identities??[]).map(e=>({...e,current:e.principalId===t.current}))}async function pK(t){let e=await RN();if(!e?.identities.some(r=>r.principalId===t))throw new Error("No saved identity has principal "+t+". Run foundation identity list.");await fc(la(),JSON.stringify({...e,current:t},null,2)+`
|
|
130
130
|
`,!0)}async function fK(t,e){let r=process.env.FOUNDATION_TOKEN,o=e||(r?void 0:process.env.FOUNDATION_PRINCIPAL_ID),n=await RN(),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=bp(t||process.env.FOUNDATION_ORIGIN||i?.origin);if(r){if(t&&process.env.FOUNDATION_ORIGIN&&s!==bp(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,u=process.env.FOUNDATION_KEY_BINDING;if(!a)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return PN.parse({origin:s,principalId:a,token:r,keys:c?JSON.parse(Buffer.from(c,"base64url").toString("utf8")):null,binding:u?JSON.parse(Buffer.from(u,"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!==bp(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 CN(t){let e=la(),r;try{r=lK.parse(JSON.parse(await uK(e,"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=PN.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await fc(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
131
131
|
`,!!r)}async function cK(t){if(process.platform==="win32")return;let e=await AN(t,"r");try{await e.sync()}finally{await e.close()}}async function fc(t,e,r){let o=Hhe(t),n=qhe(o);if(await Lhe(n,{recursive:!0,mode:448}),!r){let s=await AN(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await cK(n);return}let i=TN(n,".foundation-"+Khe());try{let s=await AN(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await Fhe(i,o),await cK(n)}finally{await Vhe(i,{force:!0})}}import{spawn as Zhe}from"node:child_process";import{chmod as Whe,mkdtemp as Jhe,rm as Ghe,writeFile as Xhe}from"node:fs/promises";import{tmpdir as Yhe}from"node:os";import{join as hK}from"node:path";import{StringDecoder as Qhe}from"node:string_decoder";function mK(t={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...t}}function ege(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var f0=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new Qhe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?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)}};async function gK(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await Jhe(hK(Yhe(),"foundation-"));await Whe(r,448);try{let o=mK(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=hK(r,i);await Xhe(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=Zhe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=ege(n),u=new f0(c,h=>process.stdout.write(h)),l=new f0(c,h=>process.stderr.write(h));a.stdout.on("data",h=>u.write(h)),a.stderr.on("data",h=>l.write(h));let d=h=>{if(a.pid)try{process.platform==="win32"?a.kill(h):process.kill(-a.pid,h)}catch{}},f=()=>d("SIGINT"),p=()=>d("SIGTERM");process.on("SIGINT",f),process.on("SIGTERM",p),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(h,g)=>{process.off("SIGINT",f),process.off("SIGTERM",p),u.end(),l.end(),i(h??(g==="SIGINT"?130:g==="SIGTERM"?143:1))})})}finally{await Ghe(r,{recursive:!0,force:!0})}}import{dirname as NPe,join as D4}from"node:path";function Vt(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",revocable:t.config.revoke?.tokenOnly===!0,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,revocable:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"ovh":{let r=t.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,revocable:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function li(t,e){return[...new Set([...t.required??[],...e??t.default])]}function mc(t){return Vt(t).requiresApp}function yK(t){return t.kind==="approval"?"unavailable":!Vt(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth"?"available":t.config.browserTokenExchange??"unknown"}var tge=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),vK=pt.refine(t=>Object.keys(t).every(e=>!tge.has(e)),"Keep method-specific facts separate from common facts."),hc=m.object({accountId:m.string().max(2e3).nullable(),accountName:m.string().max(2e3),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),authorization:vK,details:vK}).strict();function ON(t){if(t.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let e="requestedScopes"in t?t.requestedScopes:void 0;return hc.parse({accountId:t.oauth?.account??"",accountName:t.oauth?.accountName??"",accountVerified:t.oauth?.accountVerified??!1,scopes:e??t.oauth?.scopes??[],scopesStatus:e?"requested":t.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function _p(t){if(t.method.kind!=="token"&&t.method.kind!=="approval"||!t.fields)throw new Error("Use input credential material.");return"facts"in t&&t.facts?hc.parse(t.facts):hc.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function NN(t){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let e="ovh"in t?t.ovh:void 0;if(!e){let r="requestedScopes"in t?t.requestedScopes:void 0;return hc.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return hc.parse({accountId:e.user?e.account+"/"+e.user:e.account,accountName:e.account+(e.user?" / "+e.user:""),accountVerified:!0,scopes:e.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:e},details:{ovh:e}})}function DN(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return hc.parse({accountId:t.aws.identity?pp(t.aws.identity.arn):null,accountName:t.aws.identity?t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1):"",accountVerified:!!t.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:gB(t.aws)},details:{aws:yB(t.aws)}})}var rge={oauth:ON,token:_p,aws:DN,ovh:NN,approval:_p};function Ag(t){return rge[t.method.kind](t)}var oZ=$t(LK(),1);var ma=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},$ge=class extends ma{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},Age=class extends ma{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},Tge=class extends ma{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},Pge=class extends ma{char;constructor(t,e,r){super(t,e,`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"}},Rge=class extends ma{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},Cge=class extends ma{operator;constructor(t,e,r){super(t,e,`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"}},Oge=class extends ma{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},E0=class extends ma{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},HN=class extends E0{constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},Nge=class extends E0{offendingChar;constructor(t,e,r,o){super(t,e,`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"}},Dge=class extends E0{prefix;constructor(t,e,r,o){super(t,e,"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"}},FK=class extends E0{constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},zge=class extends ma{char;constructor(t,e,r){super(t,e,"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"}},jge=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},Mge=class extends jge{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},Uge=["","+",".","/",";","?","&","#"],WK={"":{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}},Lge=new TextEncoder,VK="0123456789ABCDEF",qK=t=>vc(Gr(48,57),Gr(65,70),Gr(97,102))(t.charCodeAt(0)),Cg=(t,e)=>t[e]==="%"&&e+2<t.length&&qK(t[e+1])&&qK(t[e+2]);function BN(t,e){let r=t[e];return r==null?0:vc(JK,GK,cl("_"))(r)?1:Cg(t,e)?3:0}function Fge(t,e){if(Cg(t,e))return 3;let{char:r,size:o}=Og(t,e);return qge(r)?o:0}function Og(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var JN=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Cg(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Og(e,o);r+=vc(XK,s=>t&&Vge(s))(n)?n:YK(n),o+=i}return r};function Ep(t){let e="";for(let r=0;r<t.length;){if(Cg(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Og(t,r);e+=XK(o)?o:YK(o),r+=n}return e}function Pg(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Cg(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Og(t,n);r+=i,n+=s}return r}var JK=t=>vc(Gr(65,90),Gr(97,122))(t.charCodeAt(0)),GK=t=>Gr(48,57)(t.charCodeAt(0)),XK=t=>vc(JK,GK,e=>"-._~".includes(e))(t),Vge=t=>":/?#[]@!$&'()*+,;=".includes(t),qge=t=>Hge(t.codePointAt(0)),Hge=t=>t!=null&&vc(cl(33),Gr(35,36),cl(38),Gr(40,59),cl(61),Gr(63,91),cl(93),cl(95),Gr(97,122),cl(126),Bge,Kge)(t);function Bge(t){if(t<65536)return vc(Gr(160,55295),Gr(63744,64975),Gr(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var Kge=t=>vc(Gr(57344,63743),Gr(983040,1048573),Gr(1048576,1114109))(t),YK=t=>Array.from(Lge.encode(t)).map(e=>`%${VK[e>>4]}${VK[e&15]}`).join(""),Gr=(t,e)=>r=>t<=r&&r<=e,cl=t=>e=>t===e,vc=(...t)=>e=>t.some(r=>r(e));function QK(t,e,r){return t.map(o=>o.kind==="literal"?o.text:Zge(o.vars,o.operator,e,r)).join("")}function Zge(t,e,r,o){let n=WK[e],i=t.flatMap(s=>Wge(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function Wge(t,e,r,o){if(e==null)return[];if(rye(e)){let n=Yge(e,r.allowReserved);return n.length<1?[]:HK(t,"list",o)?Gge(t,n,r):[]}if(tye(e)){let n=Qge(e,r.allowReserved);return n.length<1?[]:HK(t,"associative",o)?Xge(t,n,r):[]}return Jge(t,e,r)}function Jge(t,e,r){let o=String(e),n=t.prefix==null?o:Pg(o,t.prefix),i=JN(r.allowReserved)(n);return r.named?[Rg(Ep(t.name),i,r)]:[i]}function Gge(t,e,r){let o=Ep(t.name);if(t.explode)return r.named?e.map(i=>Rg(o,i,r)):[...e];let n=e.join(",");return r.named?[Rg(o,n,r)]:[n]}function Xge(t,e,r){if(t.explode)return e.map(([n,i])=>Rg(n,i,r));let o=e.flat(1).join(",");return r.named?[Rg(Ep(t.name),o,r)]:[o]}var Rg=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,Yge=(t,e)=>t.filter(r=>r!=null).map(String).map(JN(e)),Qge=(t,e)=>Object.entries(t).map(([r,o])=>[r,eye(o)]).filter(([,r])=>r!=null).map(r=>r.map(JN(e)));function eye(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var tye=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),rye=t=>Array.isArray(t);function HK(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new Mge(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function nye(t,e,r){return KN(t,e,r,0,0,{})}function KN(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=Pye(i);return QK(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?KN(t,e,r,o+1,n+s.text.length,i):null;for(let a of oye(t,e,o,n)){let c=e.slice(n,a);for(let u of sye(s.vars,s.operator,c)){let l=GN(i,u);if(l==null)continue;let d=KN(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*oye(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*iye(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*iye(t,e){for(let r=t;r>=e;r--)yield r}function*sye(t,e,r){if(r===""){yield*aye(t,e);return}let o=WK[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?gye(t,o,n):cye(t,o,n)}var aye=(t,e)=>(e===""||e==="+")&&t.length===1?[yc(t[0],"")]:[{}],cye=(t,e,r)=>ZN(t,e,XN(r,e.sep),0,0);function*ZN(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of uye(i,e,r,n))for(let a of ZN(t,e,r,o+1,s.index)){let c=GN(s.bindings,a);c!=null&&(yield c)}yield*ZN(t,e,r,o+1,n)}function*uye(t,e,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 lye(t,e,s))yield{bindings:a,index:o+i}}}function*lye(t,e,r){let o=eZ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*dye(t,e,r)),yield*o}function*dye(t,e,r){let o=tZ(r,e.allowReserved);if(o==null)return;let n=pye(r,e);n!=null&&(yield yc(t,n)),yield yc(t,o)}var pye=(t,e)=>fye(t.join(e.sep),e);function fye(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=mye(t,i,e.sep),a=fa(t.slice(o,n),e.allowReserved),c=fa(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function mye(t,e,r){for(let o=e;o<t.length;o++)if(hye(t,o,r))return o;return t.length}var hye=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*eZ(t,e,r){let o=fa(r,e.allowReserved);if(o==null)return;let n=yc(t,o);if(t.prefix!=null){yield n;return}let i=XN(r,",");if(i.length<2){yield n;return}let s=tZ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?Iye(i,e.allowReserved):null;a!=null&&(yield yc(t,a)),yield yc(t,s),yield n}var gye=(t,e,r)=>WN(t,e,XN(r,e.sep).map(Eye),0,0);function*WN(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of yye(i,e,r,n,t))for(let a of WN(t,e,r,o+1,s.index)){let c=GN(s.bindings,a);c!=null&&(yield c)}yield*WN(t,e,r,o+1,n)}function*yye(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*wye(t,e,r,o,n);return}yield*vye(t,e,r,o)}}function*vye(t,e,r,o){let n=r[o];if(n.name===Ep(t.name))for(let i of eZ(t,e,n.value))yield{bindings:i,index:o+1}}function*wye(t,e,r,o,n){yield*bye(t,e,r,o),yield*xye(t,e,r,o,n)}function*bye(t,e,r,o){let n=[..._ye(Ep(t.name),e,r,o)];n.length>0&&(yield{bindings:yc(t,n),index:o+n.length})}function*_ye(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=fa(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*xye(t,e,r,o,n){let i=[...Sye(e,r,o,new Set(n.map(s=>Ep(s.name))))];i.length>0&&(yield{bindings:yc(t,Object.fromEntries(i)),index:o+i.length})}function*Sye(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=fa(i.name,t.allowReserved),a=fa(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function Eye(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function Iye(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=fa(t[o],e),i=fa(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function tZ(t,e){let r=[];for(let o of t){let n=fa(o,e);if(n==null)return null;r.push(n)}return r}function fa(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var yc=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function GN(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=kye(i,n);if(s==null)return null;r[o]=s}return r}var kye=(t,e)=>S0(t)||S0(e)?$ye(t,e):Aye(t.value,e.value)?t:null;function $ye(t,e){let r=BK(t.value),o=BK(e.value);if(r==null||o==null)return null;let n=S0(t),i=S0(e);if(!n&&!i)return null;if(n&&!i)return Pg(o,t.prefix)===r?e:null;if(!n&&i)return Pg(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Pg(o,s)===r?e:null:Pg(r,a)===o?t:null}var S0=t=>t.prefix!=null,BK=t=>typeof t=="string"?t:null;function Aye(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):KK(t)?KK(e)&&Tye(Object.entries(t),Object.entries(e)):t===e}var Tye=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),KK=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Pye=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),XN=(t,e)=>e===""?[t]:t.split(e),Rye=["=",",","!","@","|"];function Cye(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new Rge(e,r));let n=t[0];if(zye(n))return o(new Cge(e,r+1,n));if(!ZK(n)&&BN(t,0)<1)return o(new Oge(e,r+1,n));let i=ZK(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:Oye(t,e,r+1,s)}}function Oye(t,e,r,o){if(o>=t.length)throw new HN(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new FK(e,r+i):new HN(e,r+i);let s=i,a=Nye(t,i);if(a===s)throw new HN(e,r+i);let c=t.slice(s,a);i=a;let u=Dye(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new zge(e,r+i,t[i]):new Nge(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new FK(e,r+i-1)}return n}function Nye(t,e){let r=e,o=!0;for(;r<t.length;){let n=BN(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||BN(t,r+1)<1)break;r++,o=!0}return r}function Dye(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&jye(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new Dge(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function ZK(t){return Uge.includes(t)&&t!==""}function zye(t){return Rye.includes(t)}function jye(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function Mye(t,e){let{report:r}=e,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<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new $ge(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new Tge(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(Cye(f,t,i))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new Age(t,i)),n(s),i++;continue}let a=Fge(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Og(t,i);r(new Pge(t,i,c)),n(c),i+=u}return o}var rZ=class nZ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=qye(r),this.#e=Uye(Mye(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new nZ(e,r)}get tokens(){return this.#e}expand=e=>QK(this.#e,e,this.#t);match=e=>nye(this.#e,e,this.#t);toString=()=>this.uriTemplate},Uye=t=>Object.freeze(t.map(Lye)),Lye=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(Fye))}),Fye=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),Vye=()=>{},qye=({strict:t,report:e})=>(e??=Vye,t??=!0,e=t?Hye(e):e,{strict:t,report:e}),Hye=t=>e=>{throw t(e),e};var ha=class extends Error{constructor(r,o){super(o);this.code=r}code};function Bye(t,e){return!t.when||e[t.when.field]===void 0||t.when.values.includes(e[t.when.field])}function I0(t,e,r={}){let o=(i,s)=>{throw new ha(i,s)},n={...r,...e};for(let i of t)n[i.name]===void 0&&i.defaultValue!==void 0&&(n[i.name]=i.defaultValue);for(let i of t){if(!Bye(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,oZ.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(e).some(i=>!t.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function ts(t,e,r={}){let o=I0(t,e,r),n={};for(let i of t){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(t.some(u=>u.name===a)||a in n&&n[a]!==c)throw new ha("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function k0(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new ha("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new ha("encrypted_input_required","Supply private material directly with your encryption keys.")}return I0(t.map(r=>({...r,required:!1,defaultValue:void 0})),e)}function zn(t,e){return k0(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function Ip(t,e,r){k0(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new ha("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}function iZ(t,e=Ag(t)){return e.accountVerified?e.accountId:null}function sZ(t,e=Ag(t)){let o=(t.method.kind==="oauth"||t.method.kind==="ovh"||t.method.kind==="token"&&!!(t.method.config.identity||t.method.config.resolver||t.method.config.bindFields))&&t.method.kind!=="aws"?zn(t.method.config.fields,t.fields??{}):{};return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,..."implicitApp"in t&&t.implicitApp?{implicitApp:{clientId:t.implicitApp.clientId,generation:t.implicitApp.generation,fields:t.implicitApp.fields}}:{},account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...Object.keys(o).length?{fields:o}:{},...e.authorization,...t.state?{state:t.state}:{}}}var wc=m.record(m.string().max(100),m.string().max(16384)),vn=m.object({format:m.literal(1),methodId:m.string().min(1),generation:x,clientId:m.string().max(1e3),clientSecret:m.string().max(16384).optional(),fields:wc}).strict(),YN=m.object({accessToken:m.string().min(1).max(16384),refreshToken:m.string().min(1).max(16384).optional(),expiresAt:m.number().nullable(),refreshExpiresAt:m.number().optional(),scopes:m.array(m.string()),requestedScopes:m.array(m.string()).optional(),account:m.string(),accountName:m.string(),accountVerified:m.boolean().optional(),scopesStatus:m.enum(["unknown","requested","reported"]).optional(),extra:wc,facts:pt}).strict(),Ng={format:m.literal(2),methodId:m.string().min(1),method:sc,generation:x,appId:x.nullable(),appGeneration:x.nullable(),state:m.literal("reconnect").optional()},ga=m.never().optional(),Tr=m.union([m.object({...Ng,method:FS,oauth:YN.optional(),requestedScopes:m.array(m.string()).optional(),implicitApp:vn.optional(),fields:wc.optional(),aws:ga}).strict(),m.object({...Ng,method:VS,fields:wc,facts:hc.optional(),oauth:ga,aws:ga}).strict(),m.object({...Ng,method:BS,fields:wc,oauth:ga,aws:ga}).strict(),m.object({...Ng,method:HS,fields:wc,ovh:hg.optional(),requestedScopes:m.array(m.string()).optional(),oauth:ga,aws:ga}).strict(),m.object({...Ng,method:qS,aws:OS,oauth:ga,fields:ga}).strict()]).superRefine((t,e)=>{if("implicitApp"in t&&t.implicitApp&&(t.method.kind!=="oauth"||t.method.config.application!=="implicit"||t.implicitApp.methodId!==t.methodId)&&e.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),t.method.kind==="oauth"&&t.fields)try{k0(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}mc(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the application required by this connection."}),!mc(t.method)&&t.appId!==null&&e.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!("requestedScopes"in t&&t.requestedScopes)&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),pHe=m.object({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),generation:x,fields:wc.optional()}).strict(),Kye=m.object({methodId:m.string().min(1).max(200),methodKind:lN,http:LS.optional(),generation:x,authorizationDigest:Dt,appId:x.nullable(),accountId:m.string().max(2e3).nullable(),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),outputs:m.array(m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:m.enum(["ready","reconnect"]),revocable:m.literal(!0).optional(),fields:wc.optional(),aws:NS.optional(),ovh:hg.optional()}).strict();async function kp(t,e=Ag(t)){let{outputs:r,revocable:o}=Vt(t.method),n=t.method.kind!=="aws"&&t.fields?zn(t.method.config.fields,t.fields):{},i=await oe(sZ(t,e));return Kye.parse({methodId:t.methodId,methodKind:t.method.kind,...t.method.http?{http:t.method.http}:{},generation:t.generation,authorizationDigest:i,appId:t.appId,accountId:iZ(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...o?{revocable:o}:{},...Object.keys(n).length?{fields:n}:{},...e.details})}var Zye=m.array(m.object({name:m.string(),label:m.string(),value:m.string()}).strict()),aZ=m.object({methodName:ne,account:m.string().max(2e3),settings:Zye.optional()}).strict();function $0(t){let e=Vt(t.method).fields,r=t.method.kind!=="aws"&&t.fields?zn(e,t.fields):{},o=e.filter(n=>r[n.name]).map(n=>({name:n.name,label:n.label,value:n.choices?.find(i=>i.value===r[n.name])?.label??r[n.name]}));return{methodName:t.method.name,account:"",...o.length?{settings:o}:{}}}var QN=m.discriminatedUnion("action",[m.object({action:m.literal("refresh"),id:x}).strict(),m.object({action:m.literal("revoke"),id:x}).strict()]);var eD=ca.extend({name:ne}),_He=ca.extend({previousSignature:zt.optional()}).strict(),cZ=m.object({name:ne,content:$r,labels:aZ.optional(),version:m.number().int().positive().optional()}).strict(),Dg=m.object({content:$r,version:m.number().int().positive()}).strict(),uZ=m.object({id:x,reason:m.enum(["grantExpired","recipients"]),remove:m.array(x).max(1e3).default([])}).strict(),xHe=m.record(x,m.object({version:m.number().int().positive(),content:$r}).strict()),lZ=m.object({id:x,name:ne,version:m.number().int().positive(),content:$r,policy:kr}).strict(),dZ=m.object({registration:EN,stoppedAt:m.iso.datetime().nullable(),heartbeatAt:m.iso.datetime().nullable()}).strict(),pZ=m.object({lease:x,request:kg,sources:m.array($r).max(100)}).strict().nullable(),Wye=m.object({lease:x}).strict(),SHe=Wye.extend({receipt:d0}).strict(),zg=m.object({id:x,resource_id:x,executor_id:x,expected_revision:m.number().int().positive(),state:m.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:m.string().regex(/^\d+$/),result:$r.nullable()}),EHe=m.object({id:x,resourceId:x,expectedRevision:m.number().int().positive()}).strict(),Jye=m.object({fence:m.string().regex(/^\d+$/)}).strict(),IHe=Jye.extend({content:$r}).strict(),kHe=m.object({id:x,executionId:x,index:m.number().int().nonnegative(),stateDigest:Dt,expiresAt:be}).strict(),tD=m.object({id:x,executionId:x,context:m.string(),sealed:Qn.nullable(),expiresAt:be,receivedAt:be.nullable()}).strict(),fZ=(t,e)=>"oauth-callback:"+t+":"+e;var Gye=m.object({binding:bt,verifiedAt:be}).strict(),rD=m.object({origin:m.url(),ownerId:x,signerId:x,revision:m.number().int().positive(),keys:m.array(Gye).max(1e3)}).strict(),Xye=m.object({version:m.number().int().positive(),signature:zt}).strict(),nD=m.object({keyring:Xye.nullable()}).strict(),CHe=m.object({version:m.number().int().positive().nullable(),signature:zt}).strict();function mZ(t,e){return Jt(rD.parse(t),e,"keyring")}function hZ(t){return rD.parse(JSON.parse(gn(GS(t.split(".")[1]??""))))}async function gZ(t,e){let r=rD.parse(await xg(t,e.signing,"keyring"));if(r.signerId!==e.id)throw new Error("Another identity signed this keyring.");return r}var $p=$t(vZ(),1);var Pr=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function N(t,e,r,o){throw new Pr(t,e,r,o)}var Yye=$p.default.IPv6.parseCIDR("2000::/3"),Qye=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function P0(t){if(!$p.default.isValid(t)||t.includes("%"))return!1;let e=$p.default.parse(t);return Qye.has(e.range())&&(!(e instanceof $p.default.IPv6)||e.match(Yye))}function jn(t,e){let r;try{r=new URL(t)}catch{N(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&N(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||$p.default.isValid(o)&&!P0(o))&&N(400,"private_destination","Choose a public HTTPS destination."),r}function di(t){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.body))}catch{N(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&N(502,"invalid_response","The service returned an invalid response."),e}var T0=class{constructor(e){this.origin=e}origin;async send(e){let r=jn(e.url,this.origin),o=e.maxBytes??1048576;e.body&&(typeof e.body=="string"?new TextEncoder().encode(e.body).length:e.body.length)>o&&N(413,"body_limit","The request body is too large.");let n;try{n=await fetch(r,{method:e.method??"GET",headers:e.headers,body:typeof e.body=="string"?e.body:e.body?new Uint8Array(e.body):void 0,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]])})}catch{e.signal?.aborted&&N(409,"cancelled","The operation was cancelled."),N(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&&N(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}}};function R0(t){return[...t.connectionId?[{id:t.connectionId}]:[],...t.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))]}function oD(t,e,r){t.method.http||N(400,"invalid_http_connection","This connection does not provide HTTP authentication.");let o=t.method.http.urlField,n=o&&t.fields?.[o];o&&!n&&N(409,"reconnect_required","Reconnect with a destination URL.");let i=jn(e.url??n??"",r);return n&&i.origin!==jn(n,r).origin&&N(400,"invalid_destination","Use this connection only at its configured destination host."),i.href}function wZ(t,e,r,o){let n=new URL(t),i={...e},s=[];Object.keys(e).some(l=>["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase()))&&N(400,"invalid_authentication","Use HTTP headers that do not override routing or transport settings.");let a=(l,d=!0)=>{Object.hasOwn(o,l)||N(400,"invalid_authentication","Choose an available authentication output.");let f=o[l];return d&&s.push(f),f},c=(l,d)=>{(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(l)||["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase())||/[\r\n\0]/.test(d))&&N(400,"invalid_authentication","Use a valid authentication header."),Object.keys(i).some(f=>f.toLowerCase()===l.toLowerCase())&&N(400,"invalid_authentication","Let the selected connection supply its authentication header."),i[l]=d,s.push(d)},u=r.authentication;if(u.kind==="bearer")c("Authorization","Bearer "+a(u.token));else if(u.kind==="basic"){let l=a(u.username),d=a(u.password);l.includes(":")&&N(400,"invalid_authentication","A Basic authentication username cannot contain a colon.");let f=new TextEncoder().encode(l+":"+d),p=btoa(Array.from(f,h=>String.fromCharCode(h)).join(""));c("Authorization","Basic "+p),s.push(p)}else if(u.kind==="header"||u.kind==="query"){let l=typeof u.name=="string"?u.name:a(u.name.output,!1),d=a(u.value);u.kind==="header"?c(l,d):((!l||/[\r\n\0]/.test(l)||n.searchParams.has(l))&&N(400,"invalid_authentication","Let the selected connection supply its authentication query parameter."),n.searchParams.set(l,d))}return s.push(n.href),{url:n.href,headers:i,sensitive:s}}var to=class extends Error{constructor(r,o){super(o);this.code=r}code},sD=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},iD=(t,...e)=>!!t&&typeof t=="object"&&("code"in t&&e.includes(String(t.code))||"status"in t&&e.includes(Number(t.status))),C0=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;verifiedKeys;async trusted(e){if(!await this.verifies(e))throw new to("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async verifies(e){if(e.principalId===this.binding.principalId)return P(this.binding)===P(e);let r=(await this.keyring()).get(e.principalId)?.binding??await this.trust.binding(e.principalId);return!!r&&P(r)===P(e)}async verifiedIdentity(e){return this.verifies((await this.inspectIdentity(e)).binding)}keyring(){return this.verifiedKeys??=this.loadKeyring().catch(e=>{throw this.verifiedKeys=void 0,e})}async loadKeyring(){let e;try{e=(await this.readKeyring()).keyring?.keys??[]}catch(i){if(iD(i,401,403))return new Map;throw i}let r=new Set(e.map(i=>i.binding.principalId)),o=new Date().toISOString(),n=(await this.trust.bindings()).filter(i=>i.principalId!==this.binding.principalId&&!r.has(i.principalId));if(n.length)try{e=(await this.changeKeyring(i=>[...i,...n.filter(s=>!i.some(a=>a.binding.principalId===s.principalId)).map(s=>({binding:s,verifiedAt:o}))])).keys}catch(i){if(i instanceof to)throw i}return new Map(e.map(i=>[i.binding.principalId,i]))}async readKeyring(){let e="/api/principals/"+this.binding.principalId+"/keyring",{keyring:r}=await this.api.json(e,{},nD),o=await this.trust.keyring(),n=()=>new to("keyring_conflict","The list of verified public keys does not match what this device saw before.");if(!r){if(o)throw n();return{version:null,revision:0,keyring:null}}let i=hZ(r.signature);if(i.signerId!==this.binding.id)return{version:r.version,revision:i.revision,keyring:null};let s=await gZ(r.signature,this.binding).catch(()=>{throw n()}),a=await oe(s);if(s.ownerId!==this.binding.principalId||s.origin!==this.origin||o&&(s.revision<o.revision||s.revision===o.revision&&a!==o.digest))throw n();return(!o||s.revision>o.revision)&&await this.trust.rememberKeyring({revision:s.revision,digest:a}),{version:r.version,revision:s.revision,keyring:s}}async changeKeyring(e){for(let r=1;;r++){let o=await this.readKeyring(),n={origin:this.origin,ownerId:this.binding.principalId,signerId:this.binding.id,revision:o.revision+1,keys:e(o.keyring?.keys??[])};try{await this.api.json("/api/principals/"+this.binding.principalId+"/keyring",{method:"PUT",body:{version:o.version,signature:await mZ(n,this.keys.signing)}},nD)}catch(i){if(r<3&&iD(i,"changed"))continue;throw i}return await this.trust.rememberKeyring({revision:n.revision,digest:await oe(n)}),n}}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+x.parse(e)+"/binding",{},ca);return await QS(r),{...r,fingerprint:await tl(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new to("fingerprint_mismatch","The identity fingerprint does not match.");if(e===this.binding.principalId||P((await this.keyring()).get(e)?.binding??null)===P(o.binding))return o;let n=new Date().toISOString();try{let i=await this.changeKeyring(s=>[...s.filter(a=>a.binding.principalId!==e),{binding:o.binding,verifiedAt:n}]);this.verifiedKeys=Promise.resolve(new Map(i.keys.map(s=>[s.binding.principalId,s])))}catch(i){if(!iD(i,401,403))throw i;await this.trust.rememberBinding(o.binding)}return o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+x.parse(e)+"/registration",{},dZ);if(await IN(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+x.parse(e)+"/bound-recipients",{},lr(eD));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:i,...s}of r)await QS(s),await this.trusted(s.binding);let o=await this.api.json("/api/principals/"+x.parse(e)+"/bound-agents",{},lr(eD)),n=[];for(let{name:i,...s}of o.items){await QS(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof to&&a.code==="identity_untrusted"))throw a}}return[...r.map(i=>i.binding),...n]}async read(e){let r=await this.api.json("/api/custody/"+x.parse(e),{},Dg);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await ui(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=_N(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&kr.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&P(o.policy)!==P(i.policy)||o.materialRevision===i.materialRevision&&await oe(o)!==i.digest)throw new to("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!o0(i.policy,o))throw new to("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return il((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},lr(lZ))).items:e,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version||P(i.content)!==P(n.content))throw new to("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);o[n.id]={version:n.version,content:await ol(await il(i.content,this.binding,this.keys.encryption),n.policy,i.content.materialRevision+1,this.binding,this.keys,i.content.metadata,i.content)}}return o}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>P(c)===P(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&nl(c)):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...lc(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return kr.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&P(o)===P({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await ol(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},Ut);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await ol(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},m.union([Ut,Ee]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},lr(uZ))).items}async reprotect(e,r="grantExpired",o=[]){let n=await this.read(e),{policy:i}=n.content,s=Date.now(),a=new Set(o),c=r==="recipients"?await this.recipients(i.ownerId):[],u=b=>!a.has(b.principalId)&&!c.some(_=>_.principalId===b.principalId&&_.id!==b.id),l=i.grants.filter(b=>nl(b,s)&&u(b.executor)&&(!("actor"in b)||u(b.actor))),d=i.readers.filter(u),f=i.authorities.filter(u),p=c.filter(b=>!d.some(_=>_.id===b.id)),h={...i,revision:i.revision+1,grants:l,producers:[],readers:[...d,...p],authorities:[...f,...p.filter(b=>!f.some(_=>_.id===b.id))],...i.observers?{observers:i.observers.filter(b=>!a.has(b))}:{}},g=i.contentType!==ge.executionResult&&i.producers.some(b=>Date.parse(b.expiresAt)>s);if(P({...h,revision:i.revision})===P(i)||g)return null;let y=await il(n.content,this.binding,this.keys.encryption);if(i.contentType===ge.executionResult){let b=await ol(y,h,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content);return await this.api.json("/api/custody/"+e,{method:"PUT",body:{name:"Execution result",content:b,version:n.version}},Dg),await this.trust.rememberContent(b),e}let w=await this.api.json("/api/resources/"+i.id,{},Ut);return this.save(w.name,y,h,{metadata:n.content.metadata,previous:n})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id,o.reason,o.remove)&&e.push(o.id)}catch(n){r.push({id:o.id,code:n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:"failure"})}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ge.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},lr(Ut));s=d.items.find(f=>f.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ge.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await a0(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=sl.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(l?.connectionId&&s.manifest.httpVersion!==eK)throw new to("http_runtime_required","Update this execution environment to use HTTP connections.");if(i.kind==="http"){let y=n.save??{},w=Object.fromEntries(await Promise.all(Object.entries(y).map(async([b,_])=>[b,await this.output(e,_,a,s,c)])));i.save=w}let d=u.kind==="command"?u.inputs.map(y=>y.source.id):l?R0(l).map(y=>y.id):[],f=await this.sourceContents([...d,...n.sourceIds??[]]);for(let y=0;y<f.length;y++){let w=f[y],b=w.policy.contentType===ge.clientCredential,_=b&&i.kind!=="revoke"?ie.refresh:ie[i.kind],I=b||!l?.url?void 0:new URL(l.url).origin;if(w.policy.grants.some(re=>"actor"in re&&P(re.actor)===P(this.binding)&&P(re.executor)===P(s.manifest.executor)&&re.operations.includes(_)&&n0(re)>=Date.parse(c)&&(!I||!re.origins.length||re.origins.includes(I))&&(b||re.callerProgram))||!w.policy.authorities.some(re=>P(re)===P(this.binding)))continue;let C=await this.read(w.policy.id),B=await this.api.json("/api/resources/"+w.policy.id,{},Ut),Q={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([_,...w.policy.contentType===ge.tokenSet?[ie.refresh]:[]])],origins:I?[I]:[],functionDigests:[],callerProgram:!b,expiresAt:c},we=re=>P({...re,expiresAt:null}),xe=C.content.policy.grants.filter(re=>we(re)===we(Q)),Xe=kr.parse({...C.content.policy,revision:C.content.policy.revision+1,grants:[...C.content.policy.grants.filter(re=>nl(re)&&we(re)!==we(Q)),{...Q,expiresAt:new Date(Math.max(Date.parse(c),...xe.map(re=>n0(re)))).toISOString()}]});await this.save(B.name,await il(C.content,this.binding,this.keys.encryption),Xe,{previous:C,metadata:C.content.metadata}),f[y]=(await this.read(w.policy.id)).content}let p=await this.policy(e,ge.executionResult,[],{id:a});p.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let h={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await oe(s.manifest),operation:ie[i.kind],operationDigest:await oe(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(f.map(async y=>({id:y.policy.id,materialRevision:y.materialRevision,policyDigest:await oe(y.policy),...y.policy.contentType===ge.tokenSet&&typeof y.metadata.authorizationDigest=="string"?{authorizationDigest:y.metadata.authorizationDigest}:{}}))),resultRecipients:p.readers,...s.manifest.resultVersion?{resultApproval:await a0(p,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await tK(s,h);let g=y=>y.policy.contentType===ge.clientCredential;for(let y of f)await yp(y,g(y)&&h.operation!==ie.connect&&h.operation!==ie.revoke?{...h,operation:ie.refresh}:h,g(y)?{}:{destination:l?.url,destinationPending:!!(l?.connectionId&&!l.url)});return QB(h,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:e},yn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new sD(e.intent.id)}}async resume(e){let r=await this.trust.run(x.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(P(r.intent.actor)!==P(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let o=await this.api.json("/api/runtime/runs/"+e,{},yn);if(P(o.intent)!==P(r.intent)||o.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return o}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="not_found")throw o}return this.submitPrepared(r)}async result(e){if(e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(e.intent.actor);let r=await xg(e.requestSignature,e.intent.actor.signing,"run");if(P(r.intent)!==P(e.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(e.intent.executor),!(e.receipt&&"content"in e.receipt?e.receipt.content.policy.readers:e.intent.resultRecipients).some(n=>P(n)===P(this.binding)))throw new to("not_recipient","This identity is not a reader of the execution result.");return e.receipt&&"content"in e.receipt&&await this.observe(e.receipt.content,e.id),e.receipt?aK(e.receipt,e.intent,this.binding.id,this.keys):null}async shareLegacyResult(e){if(!e.receipt||"content"in e.receipt)return e;if(P(e.intent.actor)!==P(this.binding)||P(e.intent.executor)!==P(this.binding))throw new to("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(e);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let o=await this.policy(e.ownerId,ge.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await sK(e.intent,e.receipt.state,r,this.keys,await a0(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},yn)}};import{lstat as eve,mkdir as bZ,readFile as tve,readdir as _Z,rm as rve}from"node:fs/promises";import{join as Ap}from"node:path";var O0=m.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),jg=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;indexing;context(e){return P({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:O0.parse(e)})}async read(e){let r=this.context(e),o=Ap(this.directory,e+".json");try{let n=await eve(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=m.string().max(32e6).parse(JSON.parse(await tve(o,"utf8"))),s=await ug(i,await _o(this.privateKeys.encryption,"ECDH-ES+A256KW"),{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(s.protectedHeader.kid!==this.binding.id||s.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let a=JSON.parse(gn(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await Zr({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async writeEntry(e,r){let o=this.context(e),n={context:o,value:r},i=await Jt(n,this.privateKeys.signing,"journal"),s=Ye(P({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new dp(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await _o(this.binding.encryption,"ECDH-ES+A256KW"));await bZ(this.directory,{recursive:!0,mode:448}),await fc(Ap(this.directory,e+".json"),P(a),!0)}delivery(e){return/^(run|process|invocation|refresh)_/.test(e)}delivered(e){return!!e&&typeof e=="object"&&"delivered"in e&&e.delivered===!0}async markPending(e){await bZ(Ap(this.directory,"pending"),{recursive:!0,mode:448}),await fc(Ap(this.directory,"pending",O0.parse(e)),"",!0)}index(){return this.indexing??=(async()=>{let e="checkpoint_pending_index";if(!await this.read(e)){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(e,{version:1})}})()}async write(e,r){await this.index();let o=this.delivered(r);this.delivery(e)&&!o&&await this.markPending(e),await this.writeEntry(e,r),this.delivery(e)&&o&&await rve(Ap(this.directory,"pending",e),{force:!0})}async pending(e){await this.index();let r;try{r=await _Z(Ap(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(e)).map(o=>O0.parse(o.name))}async keys(e){let r;try{r=await _Z(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(e)&&o.name.endsWith(".json")).map(o=>O0.parse(o.name.slice(0,-5)))}};var N0=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async bindings(){return(await Promise.all((await this.journal.keys("identity_")).map(r=>this.journal.read(r)))).filter(r=>r!==null)}async rememberBinding(e){await ua(e),await this.journal.write("identity_"+e.principalId,e)}keyring(){return this.journal.read("checkpoint_keyring")}async rememberKeyring(e){await this.journal.write("checkpoint_keyring",e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await oe(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&P(r)!==P(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var D0=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.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 Pr(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},pZ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.boolean()}))}dispatch(e,r){return this.api.json("/api/runtime/runs/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},yn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},m.object({id:x}))}connections(){let e=this.api;return{prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},zg),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},zg),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},$r),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},zg),state:r=>e.json("/api/connections/"+r+"/operation",{},zg.nullable())}}};import{randomUUID as APe}from"node:crypto";var Ta=$t(poe(),1);import{randomUUID as _Te}from"node:crypto";function foe(t){let e=CS.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&N(502,"invalid_response","The AWS account could not be verified."),e.data}function moe(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&pp(t.arn)===pp(e.arn)}function v4(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&N(409,"reconnect_required","Reconnect with current AWS credentials.")}var rA=class{async obtain(e,r,o){let n=ia.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.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)}:{}};v4(s?.expiration);let a=new Ta.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();v4(d.expiration),c=new Ta.STSClient({region:n.region,credentials:d});let f=r?.sourceIdentity?foe(await c.send(new Ta.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&f&&!moe(f,r.sourceIdentity)&&N(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,h=f;if(n.role){l=!0;let w=(await c.send(new Ta.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+_Te().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!w?.AccessKeyId||!w.SecretAccessKey||!w.SessionToken||!w.Expiration)&&N(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:w.AccessKeyId,secretAccessKey:w.SecretAccessKey,sessionToken:w.SessionToken,expiration:w.Expiration},v4(p.expiration),r?.identity&&(c.destroy(),c=new Ta.STSClient({region:n.region,credentials:p}),h=foe(await c.send(new Ta.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&h&&!moe(h,r.identity)&&N(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:OS.parse({...n,sourceIdentity:f,identity:h}),credentials:{AWS_ACCESS_KEY_ID:p.accessKeyId,AWS_SECRET_ACCESS_KEY:p.secretAccessKey,AWS_SESSION_TOKEN:p.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof Pr)throw d;o?.aborted&&N(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&N(409,"reconnect_required","Reconnect with current AWS credentials."),l&&N(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),N(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var nA=class{constructor(e){this.aws=e}aws;facts=DN;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var w4;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(w4="oauth4webapi/v3.8.8");function lA(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Vs="ERR_INVALID_ARG_VALUE",Pa="ERR_INVALID_ARG_TYPE";function sr(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var yoe=Symbol(),xTe=Symbol(),STe=Symbol(),A4=Symbol();var oA=Symbol();var ETe=new TextEncoder,ITe=new TextDecoder;function b4(t){return typeof t=="string"?ETe.encode(t):ITe.decode(t)}var _4;Uint8Array.prototype.toBase64?_4=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):_4=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var x4;Uint8Array.fromBase64?x4=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw sr("The input to be decoded is not correctly encoded.",Vs,e)}}:x4=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw sr("The input to be decoded is not correctly encoded.",Vs,e)}};function S4(t){return typeof t=="string"?x4(t):_4(t)}var Qf=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=nPe,Error.captureStackTrace?.(this,this.constructor)}},Vv=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function ke(t,e,r){return new Vv(t,{code:e,cause:r})}function iA(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function voe(t){lA(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(w4&&!e.has("user-agent")&&e.set("user-agent",w4),e.has("authorization"))throw sr('"options.headers" must not include the "authorization" header name',Vs);return e}function kTe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw sr('"options.signal" must return or be an instance of AbortSignal',Pa);return e}}function sA(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw sr(`${r} must be a number`,Pa,n);if(t>0)return;if(e){if(t!==0)throw sr(`${r} must be a non-negative number`,Vs,n);return}throw sr(`${r} must be a positive number`,Vs,n)}catch(i){throw o?ke(i.message,o,n):i}}function nn(t,e,r,o){try{if(typeof t!="string")throw sr(`${e} must be a string`,Pa,o);if(t.length===0)throw sr(`${e} must not be empty`,Vs,o)}catch(n){throw r?ke(n.message,r,o):n}}function woe(t){ATe(t,"application/json")}function $Te(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return ke(r,iPe,t)}function ATe(t,e){if(VTe(t)!==e)throw $Te(t,e)}async function boe(t){return nn(t,"codeVerifier"),S4(await crypto.subtle.digest("SHA-256",b4(t)))}function _oe(t){let e=t?.[xTe];return typeof e=="number"&&Number.isFinite(e)?e:0}function xoe(t){let e=t?.[STe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Soe(){return Math.floor(Date.now()/1e3)}function tm(t){if(typeof t!="object"||t===null)throw sr('"as" must be an object',Pa);nn(t.issuer,'"as.issuer"')}function rm(t){if(typeof t!="object"||t===null)throw sr('"client" must be an object',Pa);nn(t.client_id,'"client.client_id"')}function hoe(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Eoe(t){return nn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function Ioe(t){return nn(t,'"clientSecret"'),(e,r,o,n)=>{let i=hoe(r.client_id),s=hoe(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function koe(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var TTe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function PTe(t,e){if(e&&t.protocol!=="https:")throw ke("only requests to HTTPS are allowed",aPe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw ke("only HTTP and HTTPS requests are allowed",cPe,t)}function goe(t,e,r,o){let n;if(typeof t!="string"||!(n=TTe(t)))throw ke(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?uPe:lPe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return PTe(n,o),n}function $oe(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?goe(t.mtls_endpoint_aliases[e],e,r,o):goe(t[e],e,r,o)}var E4=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=rPe,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)}},qv=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=oPe,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)}},I4=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=tPe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},aA="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",RTe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",CTe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',OTe="("+aA+")\\s*=\\s*"+CTe,NTe="("+aA+")\\s*=\\s*("+aA+")",DTe=new RegExp("^[,\\s]*("+aA+")"),zTe=new RegExp("^[,\\s]*"+OTe+"[,\\s]*(.*)"),jTe=new RegExp("^[,\\s]*"+NTe+"[,\\s]*(.*)"),MTe=new RegExp("^("+RTe+")(?:$|[,\\s])(.*)");function UTe(t){if(!lA(t,Response))throw sr('"response" must be an instance of Response',Pa);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(DTe),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 f,p;if(n=o.match(zTe)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(jTe)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(MTe)){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 LTe(t){if(t.status>399&&t.status<500){Hoe(t),woe(t);try{let e=await t.clone().json();if(iA(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Aoe(t,e,r){if(t.status!==e){HTe(t);let o;throw(o=await LTe(t))?(await t.body?.cancel(),new E4("server responded with an error in the response body",{cause:o,response:t})):ke(`"response" is not a conform ${r} response (unexpected HTTP status code)`,sPe,t)}}function FTe(t){if(!P4.has(t))throw sr('"options.DPoP" is not a valid DPoPHandle',Vs)}function VTe(t){return t.headers.get("content-type")?.split(";")[0]}async function Toe(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[A4]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:kTe(o,s?.signal)})}async function T4(t,e,r,o,n,i){let s=$oe(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[yoe]!==!0);n.set("grant_type",o);let a=voe(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(FTe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await Toe(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Poe(t,e,r,o,n){tm(t),rm(e),nn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),T4(t,e,r,"refresh_token",i,n)}var Roe=new WeakMap,qTe=new WeakMap;function Coe(t){if(!t.id_token)return;let e=Roe.get(t);if(!e)throw sr('"ref" was already garbage collected or did not resolve from the proper sources',Vs);return e}async function dA(t,e,r,o,n,i){if(tm(t),rm(e),!lA(r,Response))throw sr('"response" must be an instance of Response',Pa);await Aoe(r,200,"Token Endpoint"),Hoe(r);let s=await hPe(r);if(nn(s.access_token,'"response" body "access_token" property',mt,{body:s}),nn(s.token_type,'"response" body "token_type" property',mt,{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;sA(a,!0,'"response" body "expires_in" property',mt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&nn(s.refresh_token,'"response" body "refresh_token" property',mt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw ke('"response" body "scope" property must be a string',mt,{body:s});if(s.id_token!==void 0){nn(s.id_token,'"response" body "id_token" property',mt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(sA(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await GTe(t,e,s.id_token,a,n);YTe(e,c),XTe(c),qTe.set(r,u),Roe.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 Qf("unsupported `token_type` value",{cause:{body:s}});return s}function HTe(t){let e;if(e=UTe(t))throw new I4("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function Ooe(t,e,r,o){return dA(t,e,r,void 0,o?.[oA],o?.recognizedTokenTypes)}function BTe(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw ke('unexpected JWT "aud" (audience) claim value',em,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw ke('unexpected JWT "aud" (audience) claim value',em,{expected:t,claims:e.claims,claim:"aud"});return e}function KTe(t,e){let r=t[gPe]?.(e)??t.issuer;if(e.claims.iss!==r)throw ke('unexpected JWT "iss" (issuer) claim value',em,{expected:r,claims:e.claims,claim:"iss"});return e}var P4=new WeakSet;function ZTe(t){return P4.add(t),t}var R4=Symbol();async function Noe(t,e,r,o,n,i,s){if(tm(t),rm(e),!P4.has(o))throw sr('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Vs);nn(n,'"redirectUri"');let a=ql(o,"code");if(!a)throw ke('no authorization code in "callbackParameters"',mt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==R4&&(nn(i,'"codeVerifier"'),c.set("code_verifier",i)),T4(t,e,r,"authorization_code",c,s)}var Doe={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 WTe(t,e){for(let r of t)if(e.claims[r]===void 0)throw ke(`JWT "${r}" (${Doe[r]}) claim missing`,mt,{claims:e.claims});return e}function JTe(t,e){if(typeof e.claims[t]!="string")throw ke(`unexpected JWT "${t}" (${Doe[t]}) claim type`,mt,{claims:e.claims});return e}function GTe(t,e,r,o,n){return dPe(r,pPe.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),_oe(e),xoe(e),n).then(WTe.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(KTe.bind(void 0,t)).then(BTe.bind(void 0,e.client_id)).then(JTe.bind(void 0,"sub"))}function zoe(t,e){if(e===uA)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?uA:(sA(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function XTe(t){t.auth_time!==void 0&&sA(t.auth_time,!0,'ID Token "auth_time" (authentication time)',mt,{claims:t})}function joe(t,e,r){if(r===uA)return;let o=Soe()+_oe(t),n=xoe(t);if(e.auth_time+r<o-n)throw ke("too much time has elapsed since the last End-User authentication",$4,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Moe(t,e){let r=e===cA?void 0:e;if(t.nonce!==r)throw ke('unexpected ID Token "nonce" claim value',em,{expected:r,claims:t,claim:"nonce"})}function YTe(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw ke('ID Token "aud" (audience) claim includes additional untrusted audiences',em,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw ke('unexpected ID Token "azp" (authorized party) claim value',em,{expected:t.client_id,claims:e,claim:"azp"})}}var cA=Symbol(),uA=Symbol();async function Uoe(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?QTe(t,e,r,o.expectedNonce,o.maxAge,o[oA],o.recognizedTokenTypes):ePe(t,e,r,o?.maxAge,o?.[oA],o?.recognizedTokenTypes)}async function QTe(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=cA;break;case cA:break;default:nn(o,'"expectedNonce" argument'),a.push("nonce")}n=zoe(e,n),n!==uA&&a.push("auth_time");let c=await dA(t,e,r,a,i,s);nn(c.id_token,'"response" body "id_token" property',mt,{body:c});let u=Coe(c);return joe(e,u,n),Moe(u,o),c}async function ePe(t,e,r,o,n,i){let s=await dA(t,e,r,void 0,n,i),a=Coe(s);return a&&(joe(e,a,zoe(e,o)),Moe(a,cA)),s}var tPe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",rPe="OAUTH_RESPONSE_BODY_ERROR",nPe="OAUTH_UNSUPPORTED_OPERATION",oPe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var k4="OAUTH_PARSE_ERROR",mt="OAUTH_INVALID_RESPONSE";var iPe="OAUTH_RESPONSE_IS_NOT_JSON",sPe="OAUTH_RESPONSE_IS_NOT_CONFORM",aPe="OAUTH_HTTP_REQUEST_FORBIDDEN",cPe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",$4="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",em="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var uPe="OAUTH_MISSING_SERVER_METADATA",lPe="OAUTH_INVALID_SERVER_METADATA";async function Loe(t,e,r,o,n){return tm(t),rm(e),T4(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Foe(t,e,r,o){return dA(t,e,r,void 0,o?.[oA],o?.recognizedTokenTypes)}async function Voe(t,e,r,o,n){tm(t),rm(e),nn(o,'"token"');let i=$oe(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[yoe]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=voe(n?.headers);return a.delete("accept"),Toe(t,e,r,i,s,a,n)}async function qoe(t){if(!lA(t,Response))throw sr('"response" must be an instance of Response',Pa);await Aoe(t,200,"Revocation Endpoint")}function Hoe(t){if(t.bodyUsed)throw sr('"response" body has been used already',Vs)}async function dPe(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new Qf("JWE decryption is not configured",{cause:t});if(a!==3)throw ke("Invalid JWT",mt,t);let c;try{c=JSON.parse(b4(S4(i)))}catch(d){throw ke("failed to parse JWT Header body as base64url encoded JSON",k4,d)}if(!iA(c))throw ke("JWT Header must be a top level object",mt,t);if(e(c),c.crit!==void 0)throw new Qf('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(b4(S4(s)))}catch(d){throw ke("failed to parse JWT Payload body as base64url encoded JSON",k4,d)}if(!iA(u))throw ke("JWT Payload must be a top level object",mt,t);let l=Soe()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw ke('unexpected JWT "exp" (expiration time) claim type',mt,{claims:u});if(u.exp<=l-o)throw ke('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',$4,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw ke('unexpected JWT "iat" (issued at) claim type',mt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw ke('unexpected JWT "iss" (issuer) claim type',mt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw ke('unexpected JWT "nbf" (not before) claim type',mt,{claims:u});if(u.nbf>l+o)throw ke('unexpected JWT "nbf" (not before) claim value',$4,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw ke('unexpected JWT "aud" (audience) claim type',mt,{claims:u});return{header:c,claims:u,jwt:t}}function pPe(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw ke('unexpected JWT "alg" header parameter',mt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw ke('unexpected JWT "alg" header parameter',mt,{header:o,expected:e,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 ke('unexpected JWT "alg" header parameter',mt,{header:o,expected:r,reason:"default value"});return}throw ke('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function ql(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw ke(`"${e}" parameter must be provided only once`,mt);return r}var fPe=Symbol(),mPe=Symbol();function Boe(t,e,r,o){if(tm(t),rm(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw sr('"parameters" must be an instance of URLSearchParams, or URL',Pa);if(ql(r,"response"))throw ke('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',mt,{parameters:r});let n=ql(r,"iss"),i=ql(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw ke('response parameter "iss" (issuer) missing',mt,{parameters:r});if(n&&n!==t.issuer)throw ke('unexpected "iss" (issuer) response parameter value',mt,{expected:t.issuer,parameters:r});switch(o){case void 0:case mPe:if(i!==void 0)throw ke('unexpected "state" response parameter encountered',mt,{expected:void 0,parameters:r});break;case fPe:break;default:if(nn(o,'"expectedState" argument'),i!==o)throw ke(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',mt,{expected:o,parameters:r})}if(ql(r,"error"))throw new qv("authorization response from the server is an error",{cause:r});let a=ql(r,"id_token"),c=ql(r,"token");if(a!==void 0||c!==void 0)throw new Qf("implicit and hybrid flows are not supported");return ZTe(new URLSearchParams(r))}async function hPe(t,e=woe){let r;try{r=await t.json()}catch(o){throw e(t),ke('failed to parse "response" body as JSON',k4,o)}if(!iA(r))throw ke('"response" body must be a top level object',mt,{body:r});return r}var gPe=Symbol();function vPe(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function Ra(t,e){for(let r of vPe(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function du(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function pA(t,e){return typeof e=="string"?du(Ra(t,e)):e.map(r=>typeof r=="string"?r:du(Ra(t,r.pointer))).join("")}function C4(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Koe=Object.assign(Object.create(null),{dpop:()=>N(502,"invalid_response","The service returned an unsupported token.")}),wPe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Koe,{"user access token":()=>{}})},bPe={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,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"))&&N(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},_Pe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+C4(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},xPe={tokenParameters(t){let e=t.get("redirect_uri");e!==null&&(t.set("redirect_url",e),t.delete("redirect_uri"))}};function qs(t,e){let r=e?new URL(e):void 0;return{recognizedTokenTypes:Koe,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(o){o.token_type===void 0&&(o.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(o){o.refresh_token===null&&delete o.refresh_token}}:{},...t.adapter==="ebay"?wPe:t.adapter==="openrouter"?bPe:t.adapter==="vultr"?xPe:{},...t.revoke?.style==="github"?_Pe:{}}}function Ca(t,e){try{return jn(new rZ(t).expand(e)).href}catch{N(400,"invalid_service_url","Check the service URL and its required fields.")}}var Zoe=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],fA=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&N(502,"invalid_response","The service returned an invalid expiry."),e};var Hl=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...ts(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof ha&&N(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&N(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(Ca(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:qs(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await boe(n),c.code_challenge_method="S256"),qs(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(Ca(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:Ca(e.tokenUrl,this.appValues(e,r))};return e.issuer&&jn(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?koe():(e.clientSecret||N(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?Ioe(e.clientSecret):Eoe(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[A4]:async(o,{body:n,headers:i,method:s,signal:a})=>{let c=new URLSearchParams(n);e&&qs(e).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(e){return di({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&Ra(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&N(409,"reconnect_required","Reconnect this service to renew access."),r===429&&N(503,"service_rate_limit","The service is busy. Try again later."),N(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&N(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,qs(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=fA(u.expires_in));try{let d=await(n?Ooe:e.grantType==="client_credentials"?Foe:Uoe)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:qs(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof Pr)throw l;N(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[qs(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&N(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+fA(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&N(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?Zoe(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+fA(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&N(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=qs(e);if(l.exchange){let f=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>Ca(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,f.status,di(f))}else{let{server:f,client:p}=this.configuration(e,r),h;try{let g=Boe(f,p,o.parameters,o.state);h=await Noe(f,p,this.authentication(r,e.clientAuth),g,l.redirectUri?.(r,i)??i,e.pkce?n:R4,{...this.options(e),additionalParameters:e.tokenParams})}catch(g){throw(g instanceof Vv||g instanceof qv)&&N(400,"invalid_state","Start the connection again."),g}u=await this.tokenResponse(e,r,h)}let d=this.token(e,u,s,a);return await c?.(d,u),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&N(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=qs(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Loe(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e)),d=await this.tokenResponse(e,r,l),f={...this.token(e,d,o,n,!!n),requestedScopes:o};return await i?.(f,d),f}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||N(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&N(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await Poe(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return i}async revoke(e,r,o){if(!e.revoke?.tokenOnly)throw new Error("Revoke only with an endpoint that invalidates this token alone.");let n=Ca(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await Voe({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await qoe(d)}catch{N(502,"revoke_failed","The service did not revoke the token.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+C4(r.clientId,r.clientSecret??"")),(await this.transport.send(qs(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&N(502,"revoke_failed","The service did not revoke the token.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,du(Ra(n,s))]))}};function O4(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function N4(t){return t||N(409,"app_required","Choose an OAuth application."),t}function SPe(t){return{token:YN.parse(t.token),response:pt.parse(t.response)}}var mA=class{constructor(e){this.transport=e}transport;facts=ON;oauth(e){return new Hl({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(e){return!e.oauth||e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=e.material,o=O4(r),n=N4(e.app),i=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>e.receive({token:c,response:u}),a=o.grantType==="client_credentials"?await this.oauth(e.signal).clientCredentials(o,n,i??li(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return Tr.parse({...e.material,oauth:a})}async recover(e,r,o){let i=SPe(o).token;return Tr.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(O4(e),N4(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(O4(e),N4(r),e.oauth)}};function EPe(t){if(t.method.kind!=="token"&&t.method.kind!=="approval")throw new Error("Use an input credential provider.");return t.method.config}var Hv=class{facts=_p;needsRenewal(){return!1}async outputs(e){let r=EPe(e),o=ts(r.fields,e.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,i])=>[n,pA(o,i)]))}};function hA(t){if(t.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return t.method.config}var gA=class{facts=NN;values(e,r){let o=hA(e),n=o.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&N(409,"app_required","Choose an OVHcloud API application with its key and secret.");let i=n?r.fields:e.fields;return ts(o.fields,i)}credentials(e,r){if(hA(e).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:e.fields.consumerKey};let o=this.values(e,r);return{applicationKey:o.applicationKey,applicationSecret:o.applicationSecret,consumerKey:o.consumerKey}}needsRenewal(){return!1}async outputs(e,r){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let o="ovh"in e?e.ovh:void 0;o&&o.expiresAt!==null&&o.expiresAt<=Date.now()&&N(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=hA(e).authorization==="consumer_key"?{...this.values(e,r),...this.credentials(e,r)}:this.values(e,r);return Object.fromEntries(Object.entries(hA(e).outputs).map(([i,s])=>[i,du(Ra(n,s))]))}};import{readFile as IPe}from"node:fs/promises";var kPe=m.object({accessToken:m.string().min(1).max(16384).regex(/^\S+$/),expiresAt:m.number().int().positive()}).strict();async function $Pe(t,e){if(t==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,i=n?await IPe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!i||i.length>16384)&&N(409,"authentication_required","Provide the current OIDC token to this executor."),i.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([e,AbortSignal.timeout(3e3)])});r.ok||N(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let o=(await r.text()).trim();return(!o||o.length>16384)&&N(502,"invalid_response","The instance did not return a valid identity token."),o}function Woe(t){if(t.method.kind!=="token"||t.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return t.method.config}var yA=class{constructor(e,r=$Pe){this.transport=e;this.identityToken=r}transport;identityToken;facts=_p;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(e,r){let o=ts(Woe(e).fields,e.fields),n=o.authentication;["api_key","oidc","instance"].includes(n)||N(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))&&N(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(o.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&N(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&&N(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=di(a);(c.role_id!==void 0&&c.role_id!==o.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==o.userId)&&N(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=kPe.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&N(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(e,r,o){let n=Woe(e);o.throwIfAborted();let i=await oe(e),s=this.sessions.get(i);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(i);a||(a=this.obtain(e,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,pA(s,c)]))}};function Joe(t,e){let r={oauth:new mA(t),token:new Hv,aws:new nA(e),approval:new Hv,ovh:new gA},o=new yA(t);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?o:r[n.kind]}function nm(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Goe(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!AB(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=Ye(du(Ra(JSON.parse(nm(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=nm(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}var vA=class{constructor(e,r,o,n,i,s=new rA){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=Joe(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers(e)}metadata(e){return kp(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||N(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=typeof o=="function"?a=>o(Tr.parse(JSON.parse(nm(a)))):o,i=Tr.safeParse(JSON.parse(nm(await $g(e,r,this.keys,{destination:n}))));i.success||N(409,"reconnect_required","Reconnect this service with the current connection format.");let s=i.data;return(await this.metadata(s)).authorizationDigest!==e.metadata.authorizationDigest&&N(409,"connection_changed","Approve the current service account and permissions before using this connection."),s.state==="reconnect"&&r.operation!==ie.revoke&&N(409,"reconnect_required","Reconnect this service before using it."),s}async app(e,r,o,n){let i=this.source(e,ge.clientCredential,n),s=vn.parse(JSON.parse(nm(await $g(i,o,this.keys))));return s.methodId!==r&&N(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(Vt(e.method).application==="none")return null;if(!mc(e.method))return"implicitApp"in e&&e.implicitApp?e.implicitApp:vn.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===ie.revoke?ie.revoke:ie.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&N(409,"app_changed","Reconnect this service with the current application."),Vt(e.method).requiresApp&&e.method.kind!=="aws"&&Object.entries(zn(e.method.config.fields,e.fields??{})).some(([s,a])=>i.fields[s]!==a)&&N(409,"app_changed","Reconnect this service with the current application settings."),i}async validate(e,r,o){let n=QN.parse(e);r.operation!==ie[n.action]&&N(400,"wrong_operation","Use the approved connection operation.");let i=await this.material(this.source(n.id,ge.tokenSet,o),r);(n.action==="refresh"||Vt(i.method).revocable)&&await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=QN.parse(e);this.active.has(i.id)&&N(409,"connection_busy","Another operation is updating this connection."),this.active.add(i.id);try{n.throwIfAborted();let s=this.source(i.id,ge.tokenSet,o),a=await this.material(s,r);if(i.action==="refresh"){let l=await this.refresh(s,a,r,o,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(l)}}let c=this.provider(a.method),u=Vt(a.method).revocable&&!!c.revoke;return u&&await c.revoke(a,await this.connectionApp(a,r,o),n),{kind:"disconnected",id:s.policy.id,revoked:u}}finally{this.active.delete(i.id)}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&N(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async httpDestination(e,r,o){let n=await this.material(e,r,i=>oD(i,o,r.origin));return oD(n,o,r.origin)}async http(e,r,o,n,i){let s=await this.httpDestination(e,r,i),a=await this.material(e,r,s),c=await this.outputs(e,r,o,n,s);return wZ(s,i.headers,a.method.http,c)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&N(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await XB(e.previous,Ye(P(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||N(409,"reconnect_required","Reconnect this service to renew access.");try{await yp(e,{...o,operation:ie.refresh},{destination:s})}catch{N(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=APe(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let f=await a.renew({material:r,app:c,signal:i,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,f)}catch(f){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),f instanceof Pr&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(f.code))throw f;N(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.pending("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,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{e.push(r.slice(8))}return e}};import{lookup as TPe}from"node:dns/promises";import{request as PPe}from"node:https";import{brotliDecompressSync as RPe,gunzipSync as CPe,inflateSync as OPe}from"node:zlib";var om=class{constructor(e){this.origin=e}origin;async send(e){let r=jn(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&N(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(e.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))&&N(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await TPe(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!P0(u.address)))&&N(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(p,h,g)=>{h.all?g(null,[a]):g(null,a.address,a.family)}},f=PPe(r,d,p=>{let h=[],g=0;p.on("data",y=>{g+=y.length,g>n?p.destroy(new Pr(413,"body_limit","The response body is too large.")):h.push(y)}),p.on("error",l),p.on("end",()=>{try{let y=Buffer.concat(h),w=p.headers["content-encoding"];if(w&&w!=="identity"){let _=w==="gzip"?CPe:w==="deflate"?OPe:w==="br"?RPe:null;if(!_)throw new Pr(502,"invalid_response","The service returned an unsupported response.");y=_(y,{maxOutputLength:n})}let b={};for(let[_,I]of Object.entries(p.headers))I!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(_)&&(b[_]=Array.isArray(I)?I.join(", "):I);u({status:p.statusCode??502,headers:b,body:new Uint8Array(y)})}catch(y){l(y)}})});f.on("error",l),f.end(e.body)})}catch(s){if(s instanceof Pr)throw s;e.signal?.aborted&&N(409,"cancelled","The operation was cancelled."),N(502,"service_unavailable","The service could not be reached. Try again.")}}};function En(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=D4(NPe(la()),"custody",r.id),i=new jg(D4(n,"client"),o,r,e),s=new C0(t,o,r,e,new N0(i)),a=new D0(t),c=new om(o),u=new vA(r,e,a.connections(),new jg(D4(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function Xoe(t,e){let{custody:r,keys:o,binding:n,connections:i}=En(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await oe(n),operation:ie.command,functionDigest:null,operationDigest:await oe(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await oe(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===ge.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Goe(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ge.value)return $g(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return Ye(d[u.output])})}import{spawn as DPe}from"node:child_process";import{fileURLToPath as zPe}from"node:url";function Yoe(t,e){return new Promise((r,o)=>{let n=DPe(process.execPath,[zPe(new URL("./agent.mjs",import.meta.url)),t],{stdio:"inherit",env:{...process.env,...e?{FOUNDATION_AGENT_OPTIONS:JSON.stringify(e)}:{}}}),i=()=>n.kill("SIGINT"),s=()=>n.kill("SIGTERM");process.on("SIGINT",i),process.on("SIGTERM",s),n.once("close",()=>{process.off("SIGINT",i),process.off("SIGTERM",s)}),n.once("error",o),n.once("close",(a,c)=>r(a??(c?1:0)))})}async function wA(t,e,r,o){let n=r?.policy??await t.policy(e,ge.tokenSet,[]);if(!o)return n;let i=await Promise.all([...new Set(o)].map(async s=>{let{binding:a}=await t.inspectIdentity(s);return await t.trusted(a),a}));return n=kr.parse({...n,revision:n.revision+(r?1:0),grants:[...n.grants.filter(s=>!("actor"in s)),...i.map(s=>({actor:s,executor:s,operations:[...lc(ge.tokenSet)],origins:[],functionDigests:[],callerProgram:!0,expiresAt:new Date(Date.now()+30*864e5).toISOString()}))]}),n}function bA(t){if(Vt(t.method).application==="none")return null;let e=t.app??vn.parse({format:1,methodId:t.methodId,generation:crypto.randomUUID(),clientId:"",fields:{}});if(Vt(t.method).requiresApp&&(!t.appId||e.methodId!==t.methodId))throw new Error("Choose an application for this connection method.");if(t.method.kind==="oauth"&&t.method.config.clientAuth!=="none"&&!e.clientSecret||t.method.kind==="ovh"&&(!e.clientId||!e.clientSecret))throw new Error("Enter the application client ID and secret.");return e}function Qoe(t,e){let r={format:2,methodId:t.methodId,method:t.method,generation:crypto.randomUUID(),appId:t.appId,appGeneration:t.appId?t.app.generation:null};if(t.method.kind==="aws")return Tr.parse({...r,aws:ia.parse(t.aws)});if(t.method.kind==="oauth")return Tr.parse({...r,requestedScopes:t.scopes,fields:zn(t.method.config.fields,t.app.fields)});let o=t.method.config.fields,n=Object.fromEntries(o.filter(s=>e?.fields?.[s.name]!==void 0).map(s=>[s.name,e.fields[s.name]])),i=Object.fromEntries(Object.entries(t.fields).filter(([s,a])=>a!==""||o.find(c=>c.name===s)?.secret===!1||n[s]===void 0));return Tr.parse({...r,fields:I0(o,i,n)})}var _A=m.object({consumerKey:m.string().min(1).max(16384),validationUrl:m.url()});async function eie(t,e,r,o,n){if(t.method.kind==="oauth"){if(t.method.config.registrationUrl&&!t.app.clientId){if(t.method.config.application!=="implicit"||t.method.config.clientAuth!=="none")throw new Error("Use dynamic registration only with an implicit public OAuth client.");let l=await e.send({url:jn(t.method.config.registrationUrl).href,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:"Foundation",redirect_uris:[n],token_endpoint_auth_method:"none",grant_types:["authorization_code"],response_types:["code"]})});if(l.status>=400)throw new Error("The service could not register this connection.");let d=m.object({client_id:m.string().min(1).max(1e3),token_endpoint_auth_method:m.literal("none").optional()}).parse(di(l));t.app.clientId=d.client_id}return{url:await new Hl(e).authorize(t.method.config,t.app,r,o,n,t.scopes)}}if(t.method.kind!=="ovh"||t.method.config.authorization!=="consumer_key")throw new Error("Choose a browser authorization method.");let i=new URL(n);i.searchParams.set("state",r);let s=Ca(t.method.config.apiBaseUrl,ts(t.method.config.fields,t.app.fields)).replace(/\/$/,"")+"/auth/credential",a=await e.send({url:s,method:"POST",headers:{"content-type":"application/json","X-Ovh-Application":t.app.clientId},body:JSON.stringify({redirection:i.href,accessRules:wB(li(t.method.config.scopes,t.scopes))})});if(a.status>=400)throw new Error("Check the OVHcloud application key and account region.");let c=_A.parse(di(a)),u=jn(c.validationUrl);if(!["ovh.com","ovhcloud.com"].some(l=>u.hostname===l||u.hostname.endsWith("."+l)))throw new Error("OVHcloud returned an unexpected authorization address.");return{url:c.validationUrl,ovh:c}}async function tie(t,e,r,o,n,i,s){let a=new URLSearchParams(r);if(a.getAll("state").length!==1||a.get("state")!==o)throw new Error("The authorization response does not match this connection.");if(a.has("error"))throw new Error("The service authorization was cancelled.");let c={format:2,methodId:t.methodId,method:t.method,generation:crypto.randomUUID(),appId:t.appId,appGeneration:t.appId?t.app.generation:null,fields:zn(Vt(t.method).fields,t.app.fields),requestedScopes:t.scopes};if(t.method.kind==="ovh")return Tr.parse({...c,fields:{...c.fields,consumerKey:_A.parse(s).consumerKey}});if(t.method.kind!=="oauth")throw new Error("Choose a browser authorization method.");let u=await new Hl(e).exchange(t.method.config,t.app,{parameters:a,state:o},n,i,t.scopes);return Tr.parse({...c,oauth:u,...t.method.config.registrationUrl&&!t.appId?{implicitApp:t.app}:{}})}var xA=m.object({id:m.string().min(1).max(1e3),expiresAt:m.number().int().positive()}).strict();async function rie(t,e,r={}){let o=await t.send({url:"https://api.runpod.io/graphql",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:e,variables:r})});o.status>=400&&N(502,"authorization_failed","RunPod could not authorize this connection.");let n=di(o);return n.errors&&N(502,"authorization_failed","RunPod could not authorize this connection."),m.record(m.string(),m.unknown()).parse(n.data)}async function nie(t){let e=await rie(t,`mutation createFlashAuthRequest {
|
|
132
132
|
createFlashAuthRequest { id status expiresAt }
|