@tomato414941/foundation 22.1.0 → 22.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.mjs +1 -1
- package/dist/cli.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -125,10 +125,10 @@ ${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 Ape(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 Kr(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,Tpe(t,e,r,o)}}function Tpe(t,e,r,o){e.definite=!1;let n=ae(e,r),i=ae(e,Ape),s=te(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var Ppe=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Rpe(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&&!Ppe.has(a.check))throw new ze('check with a custom "when" condition');switch(a.check){case"greater_than":Cpe(t,e,a,i);break;case"less_than":Ope(t,e,a,i);break;case"multiple_of":Npe(t,e,a,i);break;case"number_format":BV(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=KV(t,e,a,i);break;case"custom":i=Lpe(t,e,s,i);break;case"bigint_format":Dpe(t,a,i);break;case"mime_type":zpe(t,e,a,i);break;case"property":Mpe(t,e,a,i);break;case"properties":jpe(t,e,a,i);break;case"overwrite":{let c=te(e);Upe(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 HV(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 Cpe(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${HV(e,r.value)}) return INVALID;`)}function Ope(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${HV(e,r.value)}) return INVALID;`)}function Npe(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 BV(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 Dpe(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 zpe(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 jpe(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}];`),Kr(t,e,n[i],a,!1)}}function Mpe(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Ot(t,e,r.schema,n)}function Upe(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 ni("z.compile: async overwrite transforms are not supported");let s=ae(e,i);t.write(`const ${n} = ${s}(${o});`)}function OR(){throw new On}function zR(t){this.issues.push(t)}function Lpe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Mu(n.fn))throw new ni("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 ni("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 Fpe=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 KV(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,qb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ae(e,Gb),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,Ub);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ae(e,Kb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ae(e,Wb);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,Eb),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,Ib);t.write(`if (!${g}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let g=ae(e,kb);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(Fpe.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=Vpe(t,e,r,o,a);break;case"number":c=qpe(t,r,o);break;case"boolean":c=Hpe(t,o);break;case"bigint":c=Bpe(t,r,o);break;case"symbol":c=Kpe(t,o);break;case"undefined":c=Zpe(t,o);break;case"null":c=Wpe(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=Jpe(t,o);break;case"nan":c=Gpe(t,o);break;case"date":c=Xpe(t,o);break;case"object":c=Ype(t,e,r,o,a);break;case"optional":c=Qpe(t,e,r,o,a);break;case"nullable":c=rfe(t,e,r,o,a);break;case"array":c=nfe(t,e,r,o,a);break;case"literal":c=ofe(t,e,r,o);break;case"enum":c=ife(t,e,r,o);break;case"readonly":{let u=FV(t,e,r,o),l=te(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":FV(t,e,r,o),c="true";break;case"default":case"prefault":c=sfe(t,e,r,o);break;case"nonoptional":c=afe(t,e,r,o);break;case"tuple":c=cfe(t,e,r,o);break;case"union":c=ufe(t,e,r,o);break;case"intersection":c=pfe(t,e,r,o);break;case"record":c=ffe(t,e,r,o);break;case"map":c=hfe(t,e,r,o);break;case"set":c=gfe(t,e,r,o);break;case"file":c=yfe(t,o);break;case"template_literal":c=vfe(t,e,r,o);break;case"lazy":c=wfe(t,e,r,o);break;case"pipe":c=bfe(t,e,r,o);break;case"custom":c=_fe(t,e,r,o);break;case"transform":c=Efe(t,e,r,o);break;case"catch":c=Sfe(t,e,r,o);break;default:throw new ze(`schema type ${s}`)}return c===null?null:Rpe(t,e,r,c)}function Vpe(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:KV(t,e,i,o,n)}function qpe(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&&BV(t,{format:o.format},r),r}function Hpe(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function Bpe(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 Kpe(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function Zpe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Wpe(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function Jpe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Gpe(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function Xpe(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function Ype(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),A=te(e);if(t.write(`const ${A} = ${o}[${I}];`),_._zod.optin!==void 0){let k=te(e);t.write(`let ${k} = (() => {`),t.indented(U=>{let Z=Kr(U,e,_,A);U.write(`return ${Z};`)}),t.write("})();"),_._zod.optout==="optional"?(t.write(`if (${k} === INVALID) {`),t.indented(U=>{U.write(`if (${I} in ${o}) return INVALID;`),U.write(`${k} = undefined;`)}),t.write("}")):t.write(`if (${k} === INVALID) return INVALID;`),p.set(b,k)}else{tfe(_)&&t.write(`if (!(${I} in ${o})) return INVALID;`);let k=Kr(t,e,_,A,n);k!==null&&p.set(b,k)}}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=>LV(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];`),Kr(_,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};`):LV(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 A=Kr(_,e,h,I);_.write(`${y}[k] = ${A};`)}}),t.write("}")}return y}function Qpe(t,e,r,o,n=!0){let i=r._zod.def;if(efe(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 efe(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function tfe(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 LV(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 rfe(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 nfe(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=Kr(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function ofe(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 ife(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 FV(t,e,r,o){let n=r._zod.def;return Ot(t,e,n.innerType,o)}function sfe(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 afe(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 cfe(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=VV(i,"optin"),c=VV(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=Kr(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=Kr(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=Kr(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=Kr(f,e,s,d);f.write(`${u}[${l}] = ${p};`)}),t.write("}")}return u}function VV(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 ufe(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return lfe(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 lfe(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=>dfe(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 dfe(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 pfe(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=Kr(t,e,n.left,o),s=Kr(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 ffe(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}[${mfe(e,y)}];`);let I=Kr(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=K_(n.keyType);h.definite===!1&&(e.definite=!1);let g=ae(e,h),y=ae(e,Qs),w=te(e);return qV(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=Kr(b,e,n.valueType,_);b.write(`${s}[${w}] = ${I};`)}),s}return qV(t,e,o,a,p=>{p.write(`const ${c} = ${o}[${a}];`);let h=Kr(p,e,n.valueType,c);p.write(`${s}[${a}] = ${h};`)},"return INVALID;"),s}function qV(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 mfe(t,e){return typeof e=="string"?ln(e):ae(t,e)}function hfe(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 gfe(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 yfe(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function vfe(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 wfe(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 bfe(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 ni("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 _fe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Mu(n.fn))throw new ni("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 xfe(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 Sfe(t,e,r,o){let n=r._zod.def;if(!n.catchValue[eb])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=Kr(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,xfe);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 Efe(t,e,r,o){let n=r._zod.def;if(n.transform){if(Mu(n.transform))throw new ni("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 Z_(t){return t.checks&&(t.checks=[...t.checks]),t}function W_(t,e){return new t(Z_({type:"string",...z(e)}))}function jR(t,e){return new t(Z_({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 J_(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 G_(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...z(e)})}function X_(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 Y_(t,e){return new t(Z_({type:"number",checks:[],...z(e)}))}function UR(t,e){return new t(Z_({type:"number",coerce:!0,checks:[],...z(e)}))}function Q_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...z(e)})}function ex(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...z(e)})}function tx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...z(e)})}function rx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...z(e)})}function nx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...z(e)})}function ox(t,e){return new t({type:"boolean",...z(e)})}function LR(t,e){return new t({type:"boolean",coerce:!0,...z(e)})}function ix(t,e){return new t({type:"bigint",...z(e)})}function FR(t,e){return new t({type:"bigint",coerce:!0,...z(e)})}function sx(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...z(e)})}function ax(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...z(e)})}function cx(t,e){return new t({type:"symbol",...z(e)})}function ux(t,e){return new t({type:"undefined",...z(e)})}function lx(t,e){return new t({type:"null",...z(e)})}function dx(t){return new t({type:"any"})}function px(t){return new t({type:"unknown"})}function fx(t,e){return new t({type:"never",...z(e)})}function mx(t,e){return new t({type:"void",...z(e)})}function hx(t,e){return new t({type:"date",...z(e)})}function VR(t,e){return new t({type:"date",coerce:!0,...z(e)})}function gx(t,e){return new t({type:"nan",...z(e)})}function Gi(t,e){return new mb({check:"less_than",...z(e),value:t,inclusive:!1})}function Xn(t,e){return new mb({check:"less_than",...z(e),value:t,inclusive:!0})}function Xi(t,e){return new hb({check:"greater_than",...z(e),value:t,inclusive:!1})}function Yn(t,e){return new hb({check:"greater_than",...z(e),value:t,inclusive:!0})}function yx(t){return Xi(0,t)}function vx(t){return Gi(0,t)}function wx(t){return Xn(0,t)}function bx(t){return Yn(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 _x(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 oi(t){return new gR({check:"overwrite",tx:t})}function Fd(t){return oi(e=>e.normalize(t))}function Vd(){return oi(t=>t.trim())}function qd(){return oi(t=>t.toLowerCase())}function Hd(){return oi(t=>t.toUpperCase())}function Bd(){return oi(t=>QT(t))}function qR(t,e,r){return new t({type:"array",element:e,...z(r)})}function Ife(t,e,r){return new t({type:"union",options:e,...z(r)})}function kfe(t,e,r){return new t({type:"union",options:e,inclusive:!1,...z(r)})}function $fe(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...z(o)})}function Afe(t,e,r){return new t({type:"intersection",left:e,right:r})}function Tfe(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 Pfe(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...z(o)})}function Rfe(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...z(o)})}function Cfe(t,e,r){return new t({type:"set",valueType:e,...z(r)})}function Ofe(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 Nfe(t,e,r){return new t({type:"enum",entries:e,...z(r)})}function Dfe(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...z(r)})}function xx(t,e){return new t({type:"file",...z(e)})}function zfe(t,e){return new t({type:"transform",transform:e})}function jfe(t,e){return new t({type:"optional",innerType:e})}function Mfe(t,e){return new t({type:"nullable",innerType:e})}function Ufe(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():pd(r)}})}function Lfe(t,e,r){return new t({type:"nonoptional",innerType:e,...z(r)})}function Ffe(t,e){return new t({type:"success",innerType:e})}function Vfe(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:sP(r)})}function qfe(t,e,r){return new t({type:"pipe",in:e,out:r})}function Hfe(t,e){return new t({type:"readonly",innerType:e})}function Bfe(t,e,r){return new t({type:"template_literal",parts:e,...z(r)})}function Kfe(t,e){return new t({type:"lazy",getter:e})}function Zfe(t,e){return new t({type:"promise",innerType:e})}function Sx(t,e,r){let o=z(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function Ex(t,e,r){return new t({type:"custom",check:"custom",fn:e,...z(r)})}function Ix(t,e){let r=ZV(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 ZV(t,e){let r=new at({check:"custom",...z(e)});return r._zod.check=t,r}function kx(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 $x(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 Ax(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 WV(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}/${WV(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+WV(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 XV(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;XV(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 YV=new Set(["type","properties","required","additionalProperties"]),JV=["oneOf","anyOf"];function GV(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(!YV.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]??GV(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=GV(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 Wfe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of YV)if(n in t)return;let r=e.filter(n=>JV.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=HR(e);else{let n=r[0],i=JV.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())XV(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)??[])Wfe(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)},QV=(t,e)=>{Zd(t,"minimum",e),Wd(t,"maximum",e)},nq=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},oq=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},iq=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},sq=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},eq=(t,e)=>Zd(t,"minimum",e.minimum),tq=(t,e)=>Wd(t,"maximum",e.maximum),rq=t=>(e,r)=>{sq(e,r.format);let[o,n]=t[r.format];Zd(e,"minimum",o),Wd(e,"maximum",n)},Jfe={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)=>nq(t,e.value),number_format:rq(Wm),bigint_format:rq(Jm),min_length:eq,max_length:tq,length_equals:(t,e)=>QV(t,e.length),min_size:eq,max_size:tq,size_equals:(t,e)=>QV(t,e.size),string_format:(t,e)=>{sq(t,e.format),e.pattern&&oq(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)=>iq(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)Jfe[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&&nq(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&iq(e,n.mime);for(let i of n.patterns??[])oq(e,i);return e}var Gfe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Xfe=new Map([[Fb,CP],[uh,OP]]),aq=t=>Xfe.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=Gfe[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(aq);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)},Px=(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 Yfe(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,aq(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(()=>Yfe(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 cq(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=cq(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=cq(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},Rx=(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},Tx={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:Px,intersection:wC,tuple:bC,record:_C,nullable:xC,nonoptional:SC,default:IC,prefault:kC,catch:$C,pipe:AC,readonly:TC,promise:PC,optional:Rx,lazy:RC};function Vu(t,e){if("_idmap"in t){let o=t,n=Za({...e,processors:Tx}),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:Tx});return it(t,r),Wa(r,t),Ja(r,t)}var Cx=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:Tx,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 uq={};var rp={};St(rp,{ZodAny:()=>GC,ZodArray:()=>eO,ZodBase64:()=>Xx,ZodBase64URL:()=>Yx,ZodBigInt:()=>ep,ZodBigIntFormat:()=>tS,ZodBoolean:()=>Qd,ZodCIDRv4:()=>Jx,ZodCIDRv6:()=>Gx,ZodCUID:()=>Vx,ZodCUID2:()=>qx,ZodCatch:()=>wO,ZodCodec:()=>eg,ZodCreditCard:()=>BC,ZodCustom:()=>tg,ZodCustomStringFormat:()=>Hu,ZodDate:()=>Jh,ZodDefault:()=>fO,ZodDiscriminatedUnion:()=>rO,ZodE164:()=>Qx,ZodEmail:()=>Mx,ZodEmoji:()=>Lx,ZodEnum:()=>Gd,ZodExactOptional:()=>oS,ZodFile:()=>uO,ZodFunction:()=>TO,ZodGUID:()=>Ux,ZodIBAN:()=>KC,ZodIPv4:()=>Zx,ZodIPv6:()=>Wx,ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,ZodInstanceOf:()=>CO,ZodIntersection:()=>nO,ZodJWT:()=>eS,ZodKSUID:()=>Kx,ZodLazy:()=>kO,ZodLiteral:()=>cO,ZodMAC:()=>HC,ZodMap:()=>sO,ZodNaN:()=>_O,ZodNanoID:()=>Fx,ZodNever:()=>YC,ZodNonOptional:()=>iS,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:()=>Hx,ZodURL:()=>Zh,ZodUUID:()=>Qi,ZodUndefined:()=>WC,ZodUnion:()=>Xh,ZodUnknown:()=>XC,ZodVoid:()=>QC,ZodXID:()=>Bx,ZodXor:()=>tO,_ZodString:()=>jx,_default:()=>mO,_function:()=>yH,any:()=>Yq,array:()=>Oe,base64:()=>Cq,base64url:()=>Oq,bigint:()=>Zq,boolean:()=>Wt,catch:()=>bO,check:()=>vH,cidrv4:()=>Pq,cidrv6:()=>Rq,codec:()=>fH,creditCard:()=>Dq,cuid:()=>xq,cuid2:()=>Sq,currencyCode:()=>Fq,custom:()=>sS,date:()=>eH,describe:()=>wH,discriminatedUnion:()=>Yh,e164:()=>Nq,email:()=>pq,emoji:()=>bq,enum:()=>Er,exactOptional:()=>dO,file:()=>uH,float32:()=>qq,float64:()=>Hq,function:()=>yH,guid:()=>fq,hash:()=>Vq,hex:()=>Lq,hostname:()=>Uq,httpUrl:()=>wq,iban:()=>zq,instanceof:()=>_H,int:()=>Dx,int32:()=>Bq,int64:()=>Wq,intersection:()=>tp,invertCodec:()=>mH,ipv4:()=>$q,ipv6:()=>Tq,json:()=>SH,jwt:()=>jq,keyof:()=>tH,ksuid:()=>kq,lazy:()=>$O,literal:()=>X,looseObject:()=>Sr,looseRecord:()=>iH,mac:()=>Aq,map:()=>sH,meta:()=>bH,nan:()=>pH,nanoid:()=>_q,nativeEnum:()=>cH,never:()=>rS,nonoptional:()=>yO,null:()=>Wh,nullable:()=>Kh,nullish:()=>lH,number:()=>Je,object:()=>H,optional:()=>ct,partialRecord:()=>oH,pipe:()=>zx,prefault:()=>gO,preprocess:()=>rg,promise:()=>gH,readonly:()=>EO,record:()=>lt,refine:()=>PO,set:()=>aH,strictObject:()=>rH,string:()=>$,stringFormat:()=>Mq,stringbool:()=>xH,success:()=>dH,superRefine:()=>RO,symbol:()=>Gq,templateLiteral:()=>hH,transform:()=>nS,tuple:()=>iO,uint32:()=>Kq,uint64:()=>Jq,ulid:()=>Eq,undefined:()=>Xq,union:()=>st,unknown:()=>ht,url:()=>vq,uuid:()=>mq,uuidv4:()=>hq,uuidv6:()=>gq,uuidv7:()=>yq,void:()=>Qq,xid:()=>Iq,xor:()=>nH});var Ox={};St(Ox,{endsWith:()=>Md,gt:()=>Xi,gte:()=>Yn,includes:()=>zd,length:()=>Fu,lowercase:()=>Nd,lt:()=>Gi,lte:()=>Xn,maxLength:()=>Lu,maxSize:()=>Ba,mime:()=>Ld,minLength:()=>ea,minSize:()=>Yi,multipleOf:()=>Ha,negative:()=>vx,nonnegative:()=>bx,nonpositive:()=>wx,normalize:()=>Fd,overwrite:()=>oi,positive:()=>yx,properties:()=>Ud,property:()=>_x,regex:()=>Od,size:()=>Uu,slugify:()=>Bd,startsWith:()=>jd,toLowerCase:()=>qd,toUpperCase:()=>Hd,trim:()=>Vd,uppercase:()=>Dd});var lq=new WeakSet([Object.prototype,Error.prototype]);function Nx(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 dq=(t,e)=>{pP.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);lq.has(r)||(lq.add(r),Nx(r,"format",o=>n=>eh(o,n)),Nx(r,"flatten",o=>n=>Qm(o,n)),Nx(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,ud,2)}),Nx(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}}))},eme=S("ZodError",dq),Dn=S("ZodError",dq,void 0,{Parent:Error});var CC=md(Dn),OC=hd(Dn),NC=gd(Dn),DC=vd(Dn),zC=rb(Dn),jC=nb(Dn),MC=ob(Dn),UC=ib(Dn),LC=sb(Dn),FC=ab(Dn),VC=cb(Dn),qC=ub(Dn);function rme(){cr.localeError||Ft(L_())}function qu(){cr.memoizer||Ft({memoizer:yh()})}var Se=S("ZodType",(t,e)=>(rme(),de.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(T.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(oi(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 zx(this,nS(t))},default(t){return mO(this,t)},prefault(t){return gO(this,t)},catch(t){return bO(this,t)},pipe(t){return zx(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 T.hide(this,"~standard",{...bb(this),jsonSchema:{input:Kd(this,"input"),output:Kd(this,"output")}})},set"~standard"(t){T.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){T.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}}),jx=S("_ZodString",(t,e)=>{qa.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WR(t,r,o,n)},T.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),jx.init(t,e)},{email(t){return this.check(wh(Mx,t))},url(t){return this.check(Cd(Zh,t))},jwt(t){return this.check(Uh(eS,t))},emoji(t){return this.check(Ih(Lx,t))},guid(t){return this.check(bh(Ux,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(Fx,t))},cuid(t){return this.check($h(Vx,t))},cuid2(t){return this.check(Ah(qx,t))},ulid(t){return this.check(Th(Hx,t))},base64(t){return this.check(zh(Xx,t))},base64url(t){return this.check(jh(Yx,t))},xid(t){return this.check(Ph(Bx,t))},ksuid(t){return this.check(Rh(Kx,t))},ipv4(t){return this.check(Ch(Zx,t))},ipv6(t){return this.check(Oh(Wx,t))},cidrv4(t){return this.check(Nh(Jx,t))},cidrv6(t){return this.check(Dh(Gx,t))},e164(t){return this.check(Mh(Qx,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 $(t){return W_(Xd,t)}var ut=S("ZodStringFormat",(t,e)=>{Qe.init(t,e),jx.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)}),Mx=S("ZodEmail",(t,e)=>{Sb.init(t,e),ut.init(t,e)});function pq(t){return wh(Mx,t)}var Ux=S("ZodGUID",(t,e)=>{_b.init(t,e),ut.init(t,e)});function fq(t){return bh(Ux,t)}var Qi=S("ZodUUID",(t,e)=>{xb.init(t,e),ut.init(t,e)});function mq(t){return _h(Qi,t)}function hq(t){return xh(Qi,t)}function gq(t){return Sh(Qi,t)}function yq(t){return Eh(Qi,t)}var Zh=S("ZodURL",(t,e)=>{$b.init(t,e),ut.init(t,e)});function vq(t){return Cd(Zh,t)}function wq(t){return Cd(Zh,{protocol:th,hostname:DP,...T.normalizeParams(t)})}var Lx=S("ZodEmoji",(t,e)=>{Ab.init(t,e),ut.init(t,e)});function bq(t){return Ih(Lx,t)}var Fx=S("ZodNanoID",(t,e)=>{Tb.init(t,e),ut.init(t,e)});function _q(t){return kh(Fx,t)}var Vx=S("ZodCUID",(t,e)=>{Pb.init(t,e),ut.init(t,e)});function xq(t){return $h(Vx,t)}var qx=S("ZodCUID2",(t,e)=>{Rb.init(t,e),ut.init(t,e)});function Sq(t){return Ah(qx,t)}var Hx=S("ZodULID",(t,e)=>{Cb.init(t,e),ut.init(t,e)});function Eq(t){return Th(Hx,t)}var Bx=S("ZodXID",(t,e)=>{Ob.init(t,e),ut.init(t,e)});function Iq(t){return Ph(Bx,t)}var Kx=S("ZodKSUID",(t,e)=>{Nb.init(t,e),ut.init(t,e)});function kq(t){return Rh(Kx,t)}var Zx=S("ZodIPv4",(t,e)=>{Db.init(t,e),ut.init(t,e)});function $q(t){return Ch(Zx,t)}var HC=S("ZodMAC",(t,e)=>{jb.init(t,e),ut.init(t,e)});function Aq(t){return J_(HC,t)}var Wx=S("ZodIPv6",(t,e)=>{zb.init(t,e),ut.init(t,e)});function Tq(t){return Oh(Wx,t)}var Jx=S("ZodCIDRv4",(t,e)=>{Mb.init(t,e),ut.init(t,e)});function Pq(t){return Nh(Jx,t)}var Gx=S("ZodCIDRv6",(t,e)=>{Lb.init(t,e),ut.init(t,e)});function Rq(t){return Dh(Gx,t)}var Xx=S("ZodBase64",(t,e)=>{Vb.init(t,e),ut.init(t,e)});function Cq(t){return zh(Xx,t)}var Yx=S("ZodBase64URL",(t,e)=>{Hb.init(t,e),ut.init(t,e)});function Oq(t){return jh(Yx,t)}var Qx=S("ZodE164",(t,e)=>{Bb.init(t,e),ut.init(t,e)});function Nq(t){return Mh(Qx,t)}var BC=S("ZodCreditCard",(t,e)=>{Zb.init(t,e),ut.init(t,e)});function Dq(t){return G_(BC,t)}var KC=S("ZodIBAN",(t,e)=>{Jb.init(t,e),ut.init(t,e)});function zq(t){return X_(KC,t)}var eS=S("ZodJWT",(t,e)=>{Xb.init(t,e),ut.init(t,e)});function jq(t){return Uh(eS,t)}var Hu=S("ZodCustomStringFormat",(t,e)=>{Yb.init(t,e),ut.init(t,e)});function Mq(t,e,r={}){return Ka(Hu,t,e,r)}function Uq(t){return Ka(Hu,"hostname",NP,t)}function Lq(t){return Ka(Hu,"hex",JP,t)}function Fq(t){return Ka(Hu,"currency_code",jP,t)}function Vq(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Gn[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},T.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(Yn(t,e))},min(t,e){return this.check(Yn(t,e))},lt(t,e){return this.check(Gi(t,e))},lte(t,e){return this.check(Xn(t,e))},max(t,e){return this.check(Xn(t,e))},int(t){return this.check(Dx(t))},safe(t){return this.check(Dx(t))},positive(t){return this.check(Xi(0,t))},nonnegative(t){return this.check(Yn(0,t))},negative(t){return this.check(Gi(0,t))},nonpositive(t){return this.check(Xn(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 Y_(Yd,t)}var Bu=S("ZodNumberFormat",(t,e)=>{Qb.init(t,e),Yd.init(t,e)});function Dx(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)}function Kq(t){return nx(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 ox(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)},T.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(Yn(t,e))},min(t,e){return this.check(Yn(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(Xn(t,e))},max(t,e){return this.check(Xn(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(Xn(BigInt(0),t))},nonnegative(t){return this.check(Yn(BigInt(0),t))},multipleOf(t,e){return this.check(Ha(t,e))}}));function Zq(t){return ix(ep,t)}var tS=S("ZodBigIntFormat",(t,e)=>{e_.init(t,e),ep.init(t,e)});function Wq(t){return sx(tS,t)}function Jq(t){return ax(tS,t)}var ZC=S("ZodSymbol",(t,e)=>{t_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YR(t,r,o,n)});function Gq(t){return cx(ZC,t)}var WC=S("ZodUndefined",(t,e)=>{r_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eC(t,r,o,n)});function Xq(t){return ux(WC,t)}var JC=S("ZodNull",(t,e)=>{n_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QR(t,r,o,n)});function Wh(t){return lx(JC,t)}var GC=S("ZodAny",(t,e)=>{o_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nC(t,r,o,n)});function Yq(){return dx(GC)}var XC=S("ZodUnknown",(t,e)=>{i_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oC(t,r,o,n)});function ht(){return px(XC)}var YC=S("ZodNever",(t,e)=>{s_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rC(t,r,o,n)});function rS(t){return fx(YC,t)}var QC=S("ZodVoid",(t,e)=>{a_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tC(t,r,o,n)});function Qq(t){return mx(QC,t)}var Jh=S("ZodDate",(t,e)=>{c_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iC(t,r,o,n),t.min=(r,o)=>t.check(Yn(r,o)),t.max=(r,o)=>t.check(Xn(r,o))},T.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 eH(t){return hx(Jh,t)}var eO=S("ZodArray",(t,e)=>{qu(),u_.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 tH(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),T.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Er(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(T.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(T.mergeDefs(this._zod.def,{catchall:ht()}))},loose(){return this.clone(T.mergeDefs(this._zod.def,{catchall:ht()}))},strict(){return this.clone(T.mergeDefs(this._zod.def,{catchall:rS()}))},strip(){return this.clone(T.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return T.extend(this,t)},safeExtend(t){return T.safeExtend(this,t)},merge(t){return T.merge(this,t)},pick(t){return T.pick(this,t)},omit(t){return T.omit(this,t)},partial(...t){return T.partial(Ku,this,t[0])},exactPartial(...t){return T.partial(oS,this,t[0],"exactPartial")},required(...t){return T.required(iS,this,t[0])}});function H(t,e){let r={type:"object",shape:t??{},...T.normalizeParams(e)};return new Gh(r)}function rH(t,e){return new Gh({type:"object",shape:t,catchall:rS(),...T.normalizeParams(e)})}function Sr(t,e){return new Gh({type:"object",shape:t,catchall:ht(),...T.normalizeParams(e)})}var Xh=S("ZodUnion",(t,e)=>{Id.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.options=e.options});function st(t,e){return new Xh({type:"union",options:t,...T.normalizeParams(e)})}var tO=S("ZodXor",(t,e)=>{Xh.init(t,e),d_.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.options=e.options});function nH(t,e){return new tO({type:"union",options:t,inclusive:!1,...T.normalizeParams(e)})}var rO=S("ZodDiscriminatedUnion",(t,e)=>{Xh.init(t,e),p_.init(t,e)});function Yh(t,e,r){return new rO({type:"union",options:e,discriminator:t,...T.normalizeParams(r)})}var nO=S("ZodIntersection",(t,e)=>{f_.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,...T.normalizeParams(n)})}var Jd=S("ZodRecord",(t,e)=>{qu(),m_.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:$(),valueType:t,...T.normalizeParams(e)}):new Jd({type:"record",keyType:t,valueType:e,...T.normalizeParams(r)})}function oH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,...T.normalizeParams(r),partial:!0})}function iH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,mode:"loose",...T.normalizeParams(r)})}var sO=S("ZodMap",(t,e)=>{qu(),h_.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 sH(t,e,r){return new sO({type:"map",keyType:t,valueType:e,...T.normalizeParams(r)})}var aO=S("ZodSet",(t,e)=>{qu(),g_.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 aH(t,e){return new aO({type:"set",valueType:t,...T.normalizeParams(e)})}var Gd=S("ZodEnum",(t,e)=>{y_.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:[],...T.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:[],...T.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,...T.normalizeParams(e)})}function cH(t,e){return new Gd({type:"enum",entries:t,...T.normalizeParams(e)})}var cO=S("ZodLiteral",(t,e)=>{v_.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 X(t,e){return new cO({type:"literal",values:Array.isArray(t)?t:[t],...T.normalizeParams(e)})}var uO=S("ZodFile",(t,e)=>{w_.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 uH(t){return xx(uO,t)}var lO=S("ZodTransform",(t,e)=>{qu(),b_.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(T.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(T.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 nS(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)=>Rx(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ct(t){return new Ku({type:"optional",innerType:t})}var oS=S("ZodExactOptional",(t,e)=>{__.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Rx(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function dO(t){return new oS({type:"optional",innerType:t})}var pO=S("ZodNullable",(t,e)=>{x_.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 lH(t){return ct(Kh(t))}var fO=S("ZodDefault",(t,e)=>{S_.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():T.shallowClone(e)}})}var hO=S("ZodPrefault",(t,e)=>{E_.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():T.shallowClone(e)}})}var iS=S("ZodNonOptional",(t,e)=>{I_.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 iS({type:"nonoptional",innerType:t,...T.normalizeParams(e)})}var vO=S("ZodSuccess",(t,e)=>{k_.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 dH(t){return new vO({type:"success",innerType:t})}var wO=S("ZodCatch",(t,e)=>{$_.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:T.constantCatch(e)})}var _O=S("ZodNaN",(t,e)=>{A_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cC(t,r,o,n)});function pH(t){return gx(_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 zx(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 fH(t,e,r){return new eg({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function mH(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)=>{T_.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)=>{P_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uC(t,r,o,n)});function hH(t,e){return new IO({type:"template_literal",parts:t,...T.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)=>{C_.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 gH(t){return new AO({type:"promise",innerType:t})}var TO=S("ZodFunction",(t,e)=>{R_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fC(t,r,o,n)});function yH(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)=>{O_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pC(t,r,o,n)});function vH(t){let e=new at({check:"custom"});return e._zod.check=t,e}function sS(t,e){return Sx(tg,t??(()=>!0),e)}function PO(t,e={}){return Ex(tg,t,e)}function RO(t,e){return Ix(t,e)}var wH=kx,bH=$x,CO=S("ZodInstanceOf",(t,e)=>{tg.init(t,e)},{properties(t,e){return this.check(Ud(t,e))}});function _H(t,e={}){let r=new CO({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...T.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 xH=(...t)=>Ax({Codec:eg,Boolean:Qd,String:Xd},...t);function SH(t){let e=$O(()=>st([$(t),Je(),Wt(),Wh(),Oe(e),lt($(),e)]));return e}function rg(t,e){return new xO({type:"pipe",in:nS(t),out:e})}var nme={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 ome(t){Ft({customError:t})}function ime(){return Ft().customError}var OO;OO||(OO={});var Zu={};St(Zu,{ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,date:()=>ame,datetime:()=>sme,duration:()=>ume,time:()=>cme});function sme(t){return Lh(Ga,t)}function ame(t){return Fh(Xa,t)}function cme(t){return Vh(Ya,t)}function ume(t){return qh(Qa,t)}var q={...rp,...Ox,iso:Zu},lme=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 dme(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 EH(t,e){return t.map((r,o)=>o<e?r:r.optional())}function pme(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function fme(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:pme(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 mme(t,e){return q.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 hme=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),gme=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])=>hme.has(e)?ng(r):!gme.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(ng))}function IH(t){return t===1?"element":"elements"}function yme(t,e){return q.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 ${IH(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 ${IH(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function kH(t,e){if(t!==!1)return t===void 0||t===!0?q.any():mn(t,e)}var vme=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function $H(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return q.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 q.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=fme(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 q.null();if(n.length===0)return q.never();if(n.length===1)return q.literal(n[0]);if(n.every(s=>typeof s=="string"))return q.enum(n);let i=n.map(s=>q.literal(s));return i.length<2?i[0]:q.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return q.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return $H(s,e)});return n.length===0?q.never():n.length===1?n[0]:q.union(n)}if(!r)return q.any();let o;switch(r){case"string":{let n=q.string();if(t.format){let i=t.format;i==="email"?n=n.check(q.email()):i==="uri"||i==="uri-reference"?n=n.check(q.url()):i==="uuid"||i==="guid"?n=n.check(q.uuid()):i==="date-time"?n=n.check(q.iso.datetime({offset:!0})):i==="date"?n=n.check(q.iso.date()):i==="time"?n=n.check(q.regex(vme)):i==="duration"?n=n.check(q.iso.duration()):i==="hostname"?n=n.check(q.hostname()):i==="ipv4"?n=n.check(q.ipv4()):i==="ipv6"?n=n.check(q.ipv6()):i==="mac"?n=n.check(q.mac()):i==="cidr"?n=n.check(q.cidrv4()):i==="cidr-v6"?n=n.check(q.cidrv6()):i==="base64"?n=n.check(q.base64()):i==="base64url"?n=n.check(q.base64url()):i==="e164"?n=n.check(q.e164()):i==="credit_card"?n=n.check(q.creditCard()):i==="iban"?n=n.check(q.iban()):i==="jwt"?n=n.check(q.jwt()):i==="emoji"?n=n.check(q.emoji()):i==="nanoid"?n=n.check(q.nanoid()):i==="cuid"?n=n.check(q.cuid()):i==="cuid2"?n=n.check(q.cuid2()):i==="ulid"?n=n.check(q.ulid()):i==="xid"?n=n.check(q.xid()):i==="ksuid"&&(n=n.check(q.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"?q.number().int():q.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=q.boolean();break}case"null":{o=q.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=q.string().regex(new RegExp(g));p.push(q.looseRecord(w,y))}let h=[];if(Object.keys(n).length>0&&h.push(q.object(n).passthrough()),h.push(...p),h.length===0)o=q.object({}).passthrough();else if(h.length===1)o=h[0];else{let g=q.intersection(h[0],h[1]);for(let y=2;y<h.length;y++)g=q.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(A=>A.test(I))||_.push(I);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=q.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=mme(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=EH(a,s),u=Array.isArray(i)?void 0:kH(i,e),l=q.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(q.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(q.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=EH(a,s),u=kH(t.additionalItems,e),l=q.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(q.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(q.maxLength(t.maxItems)))}else if(i!==void 0){let s=mn(i,e),a=q.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=q.array(q.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=yme(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?q.any():q.never();let r=$H(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=q.union(a);r=o?q.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>mn(u,e)),c=q.xor(a);r=o?q.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:q.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=q.intersection(a,mn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=q.nullable(r)),t.readOnly===!0&&(r=q.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))lme.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 AH(t,e){if(typeof t=="boolean")return t?q.any():q.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=dme(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 TH=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===TH)return new $d({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,TH);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 PH(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 wme(t,e){if(!e?.length)return t;let r=t._zod.def;return We(t,yo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function RH(t){return wme(t.out,t.checks)}function bme(t){return t.in._zod.traits.has("$ZodTransform")?RH(t):t.in}function CH(t){return og(t,{pipe:e=>bme(e._zod.def),default:(e,r)=>r?ct(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function OH(t){return og(t,{pipe:e=>RH(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var DO={};St(DO,{bigint:()=>Eme,boolean:()=>Sme,date:()=>Ime,number:()=>xme,string:()=>_me});function _me(t){return jR(Xd,t)}function xme(t){return UR(Yd,t)}function Sme(t){return LR(Qd,t)}function Eme(t){return FR(ep,t)}function Ime(t){return VR(Jh,t)}var ig={name:"@tomato414941/foundation",version:"22.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 $me(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 NH=m.string().trim().max(8192).refine(t=>$me(t)!==null,"Use an OpenSSH public key from a .pub file."),aS=m.object({authorizedKeys:m.array(NH).max(32)}).strict(),A2e=aS.extend({revision:m.number().int().positive().optional()}),zO=aS.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:NH.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),T2e=zO.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])});var np=new TextEncoder,op=new TextDecoder,DH=new TextDecoder("utf-8",{fatal:!0}),cS=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>=cS)throw new RangeError(`value must be >= 0 and <= ${cS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function MO(t){let e=Math.floor(t/cS),r=t%cS,o=new Uint8Array(8);return jO(o,e,0),jO(o,r,4),o}function uS(t){let e=new Uint8Array(4);return jO(e,t),e}var Ame=/[^\x00-\x7f]/;function Ir(t){if(typeof t=="string"&&t.length>=128){if(Ame.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 zH(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 jH(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 lS(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)}},L=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 dS=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 Tme="The input to be decoded is not correctly encoded.";function Ju(t){try{return jH(typeof t=="string"?t:op.decode(t),!0)}catch(e){throw new TypeError(Tme,{cause:e})}}function Nt(t){return zH(typeof t=="string"?np.encode(t):t,!0)}function Qn(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 zn(t,e,r){try{return Ju(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function pS(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(DH.decode(Ju(t)))}catch{throw new e(r)}if(!Yt(o))throw new e(r);return o}var fS={__proto__:null,b64:!0},mS={__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 hS(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 gS(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 Pme=t=>t[Symbol.toStringTag],Rme=(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 si(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 MH(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(Rme(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 MH(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${Pme(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=Cme[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,Cme={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function vS(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 UH(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)=>UH("Key must be ",t,...e);function MH(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(UH(`Key for the ${t} algorithm must be `,e,...o))}var yS=(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 yS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw yS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw yS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw yS(e.length,"algorithm.length");VO(t,r)}function wS(t){return{__proto__:null,...t}}function HO(t){let e=wS(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 bS(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 ai(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 _S(t,e){let r=t.byteLength<<3;if(r!==e)throw new L(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var Ome=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function LH(t,e){if(e.length<<3!==t.ivBits)throw new L("Invalid Initialization Vector length")}async function FH(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 VH(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Nme(t,e,r,o,n){let[i,s,a]=await FH(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 VH(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Dme(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 zme(t,e,r,o,n,i){let[s,a,c]=await FH(t,e,"decrypt"),u=hn(i,o,r,MO(i.length*8)),l=await VH(a,u,c);try{if(await Dme(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new ec}async function xS(t,e,r,o,n){if(!nc(r)&&!(r instanceof Uint8Array))throw new TypeError(ra(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?LH(t,o):o=Ome(t),r instanceof Uint8Array&&_S(r,t.cekBits),t.cbc)return Nme(t,e,r,o,n);let i=await ai(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 SS(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 L("JWE Initialization Vector missing");if(!n)throw new L("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new L("Invalid Authentication Tag length");if(LH(t,o),e instanceof Uint8Array&&_S(e,t.cekBits),t.cbc)return zme(t,e,r,o,n,i);let s=await ai(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 jme=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Mme=[[],["deriveBits"]],kS=[[],[]];function ES(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:jme,ops:["wrapKey","unwrapKey"]}}function IS(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:Mme,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:kS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function BO(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:kS,ops:["deriveBits","deriveBits"]}}var na=cg({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:kS,ops:["encrypt","decrypt"]},"RSA-OAEP":ES(1),"RSA-OAEP-256":ES(256),"RSA-OAEP-384":ES(384),"RSA-OAEP-512":ES(512),"ECDH-ES":IS("direct-key-agreement"),"ECDH-ES+A128KW":IS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":IS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":IS("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()}),Ume=["encrypt","decrypt"];function up(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:kS,ops:Ume,cekBits:t,ivBits:e?128:96,cbc:e}}var Lme=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 qH(t,e){throw new dt(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function ci(t){return(typeof t=="string"?na[t]:void 0)??qH("alg","Algorithm")}function ui(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function Yu(t){return(typeof t=="string"?Lme[t]:void 0)??qH("enc","Encryption Algorithm")}function HH(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 Fme(t,e,r){let o=await ai(e,ci(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 Vme(t,e,r){let o=await ai(e,ci(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 KH(t,e,r){qO(e,ci(t).subtle,r),sp(t,e)}async function ZH(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new L("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new L("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 ai(o,ci(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KO(t){return hn(uS(t.length),t)}async function qme(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 lS("sha256",hn(uS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function WH(t,e,r,o,n=new Uint8Array,i=new Uint8Array){HH(t),HH(e,"deriveBits");let s=hn(KO(Ir(r)),KO(n),KO(i),uS(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 qme(a,o,s)}function JH(t){vS(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 $S(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new L(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return zn(r,e,L)}}function GH(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 L('JOSE Header "apu" and "apv" values must be distinct')}}function Hme(t){if(t===void 0)throw new L("JWE Encrypted Key missing")}function BH(t){if(t!==void 0)throw new L("Encountered unexpected JWE Encrypted Key")}function Bme(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 XH(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return BH(o),r;let c=a==="direct-key-agreement";switch(c?BH(o):Hme(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 L('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');JH(r);let l=await ap(t,u),d=$S(n,"apu"),f=$S(n,"apv");GH(d,f);let p=await WH(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 vS(r),KH(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new L('JOSE Header "p2c" (PBES2 Count) missing or invalid');Bme(i);let u=i??1e4;if(n.p2c>u)throw new L('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new L('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=zn(n.p2s,"p2s",L);r=await ZH(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new L('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new L('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=zn(n.iv,"iv",L),l=zn(n.tag,"tag",L);if(u.byteLength!==12)throw new L("Invalid Initialization Vector length");if(l.byteLength!==16)throw new L("Invalid Authentication Tag length");return SS(Yu(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Vme(s.slice(-6),r,o)}async function AS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=ui(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await si(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&&_S(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{JH(u);let{apu:p,apv:h}=i;p!==void 0&&Qn(p,'"apu"'),h!==void 0&&Qn(h,'"apv"');let g=p??$S(o,"apu"),y=h??$S(o,"apv");GH(g,y);let w;i.epk!==void 0?w=await si(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:A,crv:k,kty:U}=await b.exportKey("jwk",_),Z=a==="direct-key-agreement",be=await WH(u,w,Z?e.alg:s,Z?e.cekBits:parseInt(s.slice(-5,-2),10),g,y),xe={x:I,crv:k,kty:U};if(U==="EC"&&(xe.y=A),f={epk:xe},p!==void 0&&(f.apu=Nt(p)),h!==void 0&&(f.apv=Nt(h)),Z)return[be,void 0,f];u=be;break}case"RSA-OAEP":{vS(u),KH(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 ZH(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 xS(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 Fme(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 TS(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 L('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function YH(t){if(typeof globalThis[t]>"u")throw new dt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function QH(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 L("Decompressed plaintext exceeded the configured limit")}return hn(...n)}async function eB(t){return YH("CompressionStream"),QH(new CompressionStream("deflate-raw"),t)}async function tB(t,e){return YH("DecompressionStream"),QH(new DecompressionStream("deflate-raw"),t,e)}function rB(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 L("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new L("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new L("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new L("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new L("JWE AAD incorrect type");if(s!==void 0&&!Yt(s))throw new L("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 nB(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 oB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new L("JWE Encrypted Key incorrect type");if(r!==void 0&&!Yt(r))throw new L("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new L("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,L,"JWE Protected Header is invalid")),[s,zn(r,"ciphertext",L),o!==void 0?zn(o,"iv",L):void 0,n!==void 0?zn(n,"tag",L):void 0,pS((e??"")+(i!==void 0?`.${i}`:""),"aad",L)]}function PS(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 L("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(L,mS,g,n,f),TS(f,n);let{alg:_,enc:I}=f;if(typeof _!="string"||!_)throw new L("missing JWE Algorithm (alg) in JWE Header");let A=na[_];if(b===""&&(!A||!ui(A)))throw new L("JWE Encrypted Key incorrect type");let k=A?.mode==="integrated-encryption";if(!k&&(typeof I!="string"||!I))throw new L("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 U;if(k){if(I!==void 0)throw new L('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new L("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new L("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');U=Yu(I)}let Z;if(b!==void 0)try{Z=zn(b,"encrypted_key",L)}catch(Ce){if(!A||!ui(A))throw Ce;Z=new Uint8Array}let be=!1;typeof r=="function"&&(r=await r(n,t),be=!0);let xe=A??ci(_);ui(xe)&&Z===void 0&&(Z=new Uint8Array);let Xe=await si(xe.mode==="direct-encryption"?U:xe,r,"decrypt"),re;if(xe.mode==="integrated-encryption")re=await xe.decrypt(Xe,Z,i,c,n,f);else{let Ce=U,G;try{G=await XH(xe,Ce,Xe,Z,f,y),ui(xe)&&G instanceof Uint8Array&&G.byteLength<<3!==Ce.cekBits&&(G=Xu(Ce))}catch(Ct){if(Ct instanceof TypeError||Ct instanceof L||Ct instanceof dt)throw Ct;G=Xu(Ce)}re=await SS(Ce,G,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 tB(re,Ce).catch(G=>{throw G instanceof L?G:new L("Failed to decompress plaintext",{cause:G})})}return{plaintext:re,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:zn(d,"aad",L)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...be&&{key:Xe}}}async function iB(t,e,r){if(t instanceof Uint8Array&&(t=op.decode(t)),typeof t!="string")throw new L("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 L("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 iB(t,PS(r),e)}async function JO(t,e,r){if(!Yt(t))throw new L("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new L("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Yt))throw new L("JWE Recipients missing or incorrect type");if(!n.length)throw new L("JWE Recipients has no members");let i,s,a;try{i=PS(r),s=rB(t),a=ZO(s)}catch{throw new ec}let c=n.map(u=>nB(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&&!ui(d))throw new L(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return oB(l),await WO(l,i,e,a)}catch{}throw new ec}function RS(t,e,r){if(!tc(t,e,r))throw new L("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 L("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&&Qn(s,"JWE Additional Authenticated Data"),a!==void 0&&Qn(a,"JWE Content Encryption Key"),c!==void 0&&Qn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Gu(L,o)[0],t[1]=o),n!==void 0&&(n=Gu(L,n)[0],t[2]=n),!r&&i!==void 0&&(i=Gu(L,i)[0],t[3]=i),u!==void 0&&!Yt(u))throw new TypeError("JWE Key Management Parameters must be an object");RS(o,n,i);let d={...o,...n,...i};hS(L,o),rc(L,mS,l,o,d),TS(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new L('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=na[f];if(h?.mode==="integrated-encryption"){if(p!==void 0)throw new L('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 L('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??ci(o.alg),b,_,I;w.mode==="integrated-encryption"?I=await si(w,r,"encrypt"):[I,b,_]=await AS(w,n,r,o,d,p),_&&(h?y=y?{...y,..._}:_:g=g?{...g,..._}:_,RS(g,y,u));let A=g?Nt(JSON.stringify(g)):"",k=l?.byteLength?Nt(l):void 0,U=Ir(k?`${A}.${k}`:A),Z=s;o.zip==="DEF"&&(Z=await eB(Z).catch(Ce=>{throw new L("Failed to compress plaintext",{cause:Ce})}));let be,xe,Xe;w.mode==="integrated-encryption"?[b,be]=await w.encrypt(I,Z,U,g,o,p):{ciphertext:be,tag:xe,iv:Xe}=await xS(n,Z,I,f,U);let re={ciphertext:Nt(be)};return Xe&&(re.iv=Nt(Xe)),xe&&(re.tag=Nt(xe)),b?.byteLength&&(re.encrypted_key=Nt(b)),k&&(re.aad=k),g&&(re.protected=A),u&&(re.unprotected=u),y&&(re.header=y),re}async function sB(t,e,r){return XO(t,GO(t,r),e)}function aB(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 L("at least one recipient must be added");Qn(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:A,enc:k},,U]=I;if(e&&U&&!ui(U))throw new L(`"${A}" alg may only have a single recipient`);if(!r)r=k;else if(r!==k)throw new L('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,h]of i)h[2]??=ci(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],[,A,k]=await AS(b,w,_,y,u,g[7]),U={encrypted_key:Nt(A)};if(I||k){let Z={...I,...k};k&&RS(g[1],Z,g[3]),U.header=Z}p.recipients.push(U)}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 cB(){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:cB(),Ed25519:cB(),"ML-DSA-44":tN(44),"ML-DSA-65":tN(65),"ML-DSA-87":tN(87)});function CS(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 uB(t){return[t&&ag("algorithms",t.algorithms),t?.crit]}function Kme(t){return t===void 0?{}:ip(t,At,"JWS Protected Header is invalid")}function Zme(t){try{return Ir(t)}catch{throw new At("JWS Compact Serialization payload must use only ASCII characters")}}async function Wme(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Kme(i);if(!tc(c,s))throw new At("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=gS(c,rc(At,fS,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=CS(d),g=hn(i!==void 0?Ir(i):new Uint8Array,Ir("."),typeof f=="string"?e[2]??=pS(f,"payload",At):f),y=zn(t.signature,"signature",At),w=await si(h,r,"verify"),b=await ai(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 dS;let I={payload:typeof f=="string"?zn(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 lB(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 Wme({payload:n,protected:o,signature:i},e,r,Zme)}async function nN(t,e,r){let[o]=await lB(t,uB(r),e);return o}var dp=class{#e;constructor(e){Qn(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 aB(await sB([...this.#e],e,r))}};async function Jme(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};hS(At,n);let u=gS(n,rc(At,fS,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=CS(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 ai(await si(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 dB(t,e,r,o,n){let[i]=await Jme([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var pg=class{#e;#t;constructor(e){Qn(e,"payload"),this.#e=e}setProtectedHeader(e){return bo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return dB(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=wS(t),typeof r.kty!="string")throw new TypeError(ra(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(FO(t))r=wS(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 lS(e,n))}async function _o(t,e,r){if(!Yt(t))throw new TypeError("JWK must be an object");let o=HO(t),n=bS(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 Gme(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=bS(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:Gme(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var hB=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),gB=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),pB=m.string().min(1).max(128),fB=m.string().min(1).max(16384),Xme=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:pB,secretAccessKey:fB}).strict(),m.object({kind:m.literal("session"),accessKeyId:pB,secretAccessKey:fB,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()]),Yme=m.object({arn:gB,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),ia=m.object({authentication:Xme,region:hB,role:Yme.optional()}).strict(),OS=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(),NS=ia.extend({sourceIdentity:OS.optional(),identity:OS.optional()}).strict();function pp(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function mB(t){return{...t,arn:pp(t.arn)}}function yB(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:mB(t.sourceIdentity)}:{},...t.identity?{identity:mB(t.identity)}:{}}}var DS=m.object({authentication:m.enum(["access_key","session","environment"]),region:hB,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:gB.optional(),expiresAt:m.number().int().positive().optional()}).strict();function vB(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 wB=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(wB),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function bB(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 wB.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),ge=m.iso.datetime(),ur=m.json(),pt=m.record(m.string(),ur),xB=m.enum(["ja","en"]),SB=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var EB=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(),Qme=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:x}).strict(),vg=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 Qme.safeParse(aN(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),eo=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(),dVe=m.object({id:x,name:ne,publicKey:kr}),ic=m.object({id:x,name:ne,owner:m.object({id:x,name:ne}).nullable(),createdAt:ge,permissions:m.array(SB),createKinds:m.array(EB),publicKey:kr.nullable()}),IB=m.object({id:x,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:ge,lastUsedAt:ge.nullable(),expiresAt:ge.nullable(),canOpen:m.boolean()}),cN=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ehe=m.object({subjectId:x,relation:cN,objectId:x}).strict(),kB=m.enum(["principal",...EB.options]),pVe=ehe.extend({objectType:kB,subjectName:ne,objectName:ne,createdAt:ge}),fVe=m.object({error:m.object({code:m.string(),message:m.string(),details:ur.optional()})}),mVe=m.object({ok:m.literal(!0)}),the=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(the).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."})}),uN=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),rhe=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)])),lN=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),jS=m.union([m.string(),m.array(m.string()).min(1)]),nhe=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:jS.default("/id"),name:jS.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:lN.default({default:[],separator:" "}),fields:m.array(US).default([]),outputs:uN.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."}),ohe=m.object({fields:m.array(US).min(1),outputs:rhe,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:jS,name:jS}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),dN=m.enum(["oauth","token","aws","ovh","approval"]),ihe=m.object({hint:m.string().optional()}).strict(),she=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:Qu,fields:m.array(US).min(1),scopes:lN.default({default:[],separator:`
|
|
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 XV(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;XV(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 YV=new Set(["type","properties","required","additionalProperties"]),JV=["oneOf","anyOf"];function GV(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(!YV.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]??GV(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=GV(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 Wfe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of YV)if(n in t)return;let r=e.filter(n=>JV.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=HR(e);else{let n=r[0],i=JV.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())XV(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)??[])Wfe(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)},QV=(t,e)=>{Zd(t,"minimum",e),Wd(t,"maximum",e)},nq=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},oq=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},iq=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},sq=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},eq=(t,e)=>Zd(t,"minimum",e.minimum),tq=(t,e)=>Wd(t,"maximum",e.maximum),rq=t=>(e,r)=>{sq(e,r.format);let[o,n]=t[r.format];Zd(e,"minimum",o),Wd(e,"maximum",n)},Jfe={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)=>nq(t,e.value),number_format:rq(Wm),bigint_format:rq(Jm),min_length:eq,max_length:tq,length_equals:(t,e)=>QV(t,e.length),min_size:eq,max_size:tq,size_equals:(t,e)=>QV(t,e.size),string_format:(t,e)=>{sq(t,e.format),e.pattern&&oq(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)=>iq(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)Jfe[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&&nq(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&iq(e,n.mime);for(let i of n.patterns??[])oq(e,i);return e}var Gfe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Xfe=new Map([[Fb,CP],[uh,OP]]),aq=t=>Xfe.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=Gfe[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(aq);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)},Px=(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 Yfe(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,aq(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(()=>Yfe(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 cq(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=cq(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=cq(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},Rx=(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},Tx={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:Px,intersection:wC,tuple:bC,record:_C,nullable:xC,nonoptional:SC,default:IC,prefault:kC,catch:$C,pipe:AC,readonly:TC,promise:PC,optional:Rx,lazy:RC};function Vu(t,e){if("_idmap"in t){let o=t,n=Za({...e,processors:Tx}),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:Tx});return it(t,r),Wa(r,t),Ja(r,t)}var Cx=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:Tx,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 uq={};var rp={};St(rp,{ZodAny:()=>GC,ZodArray:()=>eO,ZodBase64:()=>Xx,ZodBase64URL:()=>Yx,ZodBigInt:()=>ep,ZodBigIntFormat:()=>tS,ZodBoolean:()=>Qd,ZodCIDRv4:()=>Jx,ZodCIDRv6:()=>Gx,ZodCUID:()=>Vx,ZodCUID2:()=>qx,ZodCatch:()=>wO,ZodCodec:()=>eg,ZodCreditCard:()=>BC,ZodCustom:()=>tg,ZodCustomStringFormat:()=>Hu,ZodDate:()=>Jh,ZodDefault:()=>fO,ZodDiscriminatedUnion:()=>rO,ZodE164:()=>Qx,ZodEmail:()=>Mx,ZodEmoji:()=>Lx,ZodEnum:()=>Gd,ZodExactOptional:()=>oS,ZodFile:()=>uO,ZodFunction:()=>TO,ZodGUID:()=>Ux,ZodIBAN:()=>KC,ZodIPv4:()=>Zx,ZodIPv6:()=>Wx,ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,ZodInstanceOf:()=>CO,ZodIntersection:()=>nO,ZodJWT:()=>eS,ZodKSUID:()=>Kx,ZodLazy:()=>kO,ZodLiteral:()=>cO,ZodMAC:()=>HC,ZodMap:()=>sO,ZodNaN:()=>_O,ZodNanoID:()=>Fx,ZodNever:()=>YC,ZodNonOptional:()=>iS,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:()=>Hx,ZodURL:()=>Zh,ZodUUID:()=>Qi,ZodUndefined:()=>WC,ZodUnion:()=>Xh,ZodUnknown:()=>XC,ZodVoid:()=>QC,ZodXID:()=>Bx,ZodXor:()=>tO,_ZodString:()=>jx,_default:()=>mO,_function:()=>yH,any:()=>Yq,array:()=>Oe,base64:()=>Cq,base64url:()=>Oq,bigint:()=>Zq,boolean:()=>Wt,catch:()=>bO,check:()=>vH,cidrv4:()=>Pq,cidrv6:()=>Rq,codec:()=>fH,creditCard:()=>Dq,cuid:()=>xq,cuid2:()=>Sq,currencyCode:()=>Fq,custom:()=>sS,date:()=>eH,describe:()=>wH,discriminatedUnion:()=>Yh,e164:()=>Nq,email:()=>pq,emoji:()=>bq,enum:()=>Er,exactOptional:()=>dO,file:()=>uH,float32:()=>qq,float64:()=>Hq,function:()=>yH,guid:()=>fq,hash:()=>Vq,hex:()=>Lq,hostname:()=>Uq,httpUrl:()=>wq,iban:()=>zq,instanceof:()=>_H,int:()=>Dx,int32:()=>Bq,int64:()=>Wq,intersection:()=>tp,invertCodec:()=>mH,ipv4:()=>$q,ipv6:()=>Tq,json:()=>SH,jwt:()=>jq,keyof:()=>tH,ksuid:()=>kq,lazy:()=>$O,literal:()=>X,looseObject:()=>Sr,looseRecord:()=>iH,mac:()=>Aq,map:()=>sH,meta:()=>bH,nan:()=>pH,nanoid:()=>_q,nativeEnum:()=>cH,never:()=>rS,nonoptional:()=>yO,null:()=>Wh,nullable:()=>Kh,nullish:()=>lH,number:()=>Je,object:()=>H,optional:()=>ct,partialRecord:()=>oH,pipe:()=>zx,prefault:()=>gO,preprocess:()=>rg,promise:()=>gH,readonly:()=>EO,record:()=>lt,refine:()=>PO,set:()=>aH,strictObject:()=>rH,string:()=>$,stringFormat:()=>Mq,stringbool:()=>xH,success:()=>dH,superRefine:()=>RO,symbol:()=>Gq,templateLiteral:()=>hH,transform:()=>nS,tuple:()=>iO,uint32:()=>Kq,uint64:()=>Jq,ulid:()=>Eq,undefined:()=>Xq,union:()=>st,unknown:()=>ht,url:()=>vq,uuid:()=>mq,uuidv4:()=>hq,uuidv6:()=>gq,uuidv7:()=>yq,void:()=>Qq,xid:()=>Iq,xor:()=>nH});var Ox={};St(Ox,{endsWith:()=>Md,gt:()=>Xi,gte:()=>Yn,includes:()=>zd,length:()=>Fu,lowercase:()=>Nd,lt:()=>Gi,lte:()=>Xn,maxLength:()=>Lu,maxSize:()=>Ba,mime:()=>Ld,minLength:()=>ea,minSize:()=>Yi,multipleOf:()=>Ha,negative:()=>vx,nonnegative:()=>bx,nonpositive:()=>wx,normalize:()=>Fd,overwrite:()=>oi,positive:()=>yx,properties:()=>Ud,property:()=>_x,regex:()=>Od,size:()=>Uu,slugify:()=>Bd,startsWith:()=>jd,toLowerCase:()=>qd,toUpperCase:()=>Hd,trim:()=>Vd,uppercase:()=>Dd});var lq=new WeakSet([Object.prototype,Error.prototype]);function Nx(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 dq=(t,e)=>{pP.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);lq.has(r)||(lq.add(r),Nx(r,"format",o=>n=>eh(o,n)),Nx(r,"flatten",o=>n=>Qm(o,n)),Nx(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,ud,2)}),Nx(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}}))},eme=S("ZodError",dq),Dn=S("ZodError",dq,void 0,{Parent:Error});var CC=md(Dn),OC=hd(Dn),NC=gd(Dn),DC=vd(Dn),zC=rb(Dn),jC=nb(Dn),MC=ob(Dn),UC=ib(Dn),LC=sb(Dn),FC=ab(Dn),VC=cb(Dn),qC=ub(Dn);function rme(){cr.localeError||Ft(L_())}function qu(){cr.memoizer||Ft({memoizer:yh()})}var Se=S("ZodType",(t,e)=>(rme(),de.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(T.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(oi(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 zx(this,nS(t))},default(t){return mO(this,t)},prefault(t){return gO(this,t)},catch(t){return bO(this,t)},pipe(t){return zx(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 T.hide(this,"~standard",{...bb(this),jsonSchema:{input:Kd(this,"input"),output:Kd(this,"output")}})},set"~standard"(t){T.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){T.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}}),jx=S("_ZodString",(t,e)=>{qa.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WR(t,r,o,n)},T.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),jx.init(t,e)},{email(t){return this.check(wh(Mx,t))},url(t){return this.check(Cd(Zh,t))},jwt(t){return this.check(Uh(eS,t))},emoji(t){return this.check(Ih(Lx,t))},guid(t){return this.check(bh(Ux,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(Fx,t))},cuid(t){return this.check($h(Vx,t))},cuid2(t){return this.check(Ah(qx,t))},ulid(t){return this.check(Th(Hx,t))},base64(t){return this.check(zh(Xx,t))},base64url(t){return this.check(jh(Yx,t))},xid(t){return this.check(Ph(Bx,t))},ksuid(t){return this.check(Rh(Kx,t))},ipv4(t){return this.check(Ch(Zx,t))},ipv6(t){return this.check(Oh(Wx,t))},cidrv4(t){return this.check(Nh(Jx,t))},cidrv6(t){return this.check(Dh(Gx,t))},e164(t){return this.check(Mh(Qx,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 $(t){return W_(Xd,t)}var ut=S("ZodStringFormat",(t,e)=>{Qe.init(t,e),jx.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)}),Mx=S("ZodEmail",(t,e)=>{Sb.init(t,e),ut.init(t,e)});function pq(t){return wh(Mx,t)}var Ux=S("ZodGUID",(t,e)=>{_b.init(t,e),ut.init(t,e)});function fq(t){return bh(Ux,t)}var Qi=S("ZodUUID",(t,e)=>{xb.init(t,e),ut.init(t,e)});function mq(t){return _h(Qi,t)}function hq(t){return xh(Qi,t)}function gq(t){return Sh(Qi,t)}function yq(t){return Eh(Qi,t)}var Zh=S("ZodURL",(t,e)=>{$b.init(t,e),ut.init(t,e)});function vq(t){return Cd(Zh,t)}function wq(t){return Cd(Zh,{protocol:th,hostname:DP,...T.normalizeParams(t)})}var Lx=S("ZodEmoji",(t,e)=>{Ab.init(t,e),ut.init(t,e)});function bq(t){return Ih(Lx,t)}var Fx=S("ZodNanoID",(t,e)=>{Tb.init(t,e),ut.init(t,e)});function _q(t){return kh(Fx,t)}var Vx=S("ZodCUID",(t,e)=>{Pb.init(t,e),ut.init(t,e)});function xq(t){return $h(Vx,t)}var qx=S("ZodCUID2",(t,e)=>{Rb.init(t,e),ut.init(t,e)});function Sq(t){return Ah(qx,t)}var Hx=S("ZodULID",(t,e)=>{Cb.init(t,e),ut.init(t,e)});function Eq(t){return Th(Hx,t)}var Bx=S("ZodXID",(t,e)=>{Ob.init(t,e),ut.init(t,e)});function Iq(t){return Ph(Bx,t)}var Kx=S("ZodKSUID",(t,e)=>{Nb.init(t,e),ut.init(t,e)});function kq(t){return Rh(Kx,t)}var Zx=S("ZodIPv4",(t,e)=>{Db.init(t,e),ut.init(t,e)});function $q(t){return Ch(Zx,t)}var HC=S("ZodMAC",(t,e)=>{jb.init(t,e),ut.init(t,e)});function Aq(t){return J_(HC,t)}var Wx=S("ZodIPv6",(t,e)=>{zb.init(t,e),ut.init(t,e)});function Tq(t){return Oh(Wx,t)}var Jx=S("ZodCIDRv4",(t,e)=>{Mb.init(t,e),ut.init(t,e)});function Pq(t){return Nh(Jx,t)}var Gx=S("ZodCIDRv6",(t,e)=>{Lb.init(t,e),ut.init(t,e)});function Rq(t){return Dh(Gx,t)}var Xx=S("ZodBase64",(t,e)=>{Vb.init(t,e),ut.init(t,e)});function Cq(t){return zh(Xx,t)}var Yx=S("ZodBase64URL",(t,e)=>{Hb.init(t,e),ut.init(t,e)});function Oq(t){return jh(Yx,t)}var Qx=S("ZodE164",(t,e)=>{Bb.init(t,e),ut.init(t,e)});function Nq(t){return Mh(Qx,t)}var BC=S("ZodCreditCard",(t,e)=>{Zb.init(t,e),ut.init(t,e)});function Dq(t){return G_(BC,t)}var KC=S("ZodIBAN",(t,e)=>{Jb.init(t,e),ut.init(t,e)});function zq(t){return X_(KC,t)}var eS=S("ZodJWT",(t,e)=>{Xb.init(t,e),ut.init(t,e)});function jq(t){return Uh(eS,t)}var Hu=S("ZodCustomStringFormat",(t,e)=>{Yb.init(t,e),ut.init(t,e)});function Mq(t,e,r={}){return Ka(Hu,t,e,r)}function Uq(t){return Ka(Hu,"hostname",NP,t)}function Lq(t){return Ka(Hu,"hex",JP,t)}function Fq(t){return Ka(Hu,"currency_code",jP,t)}function Vq(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Gn[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},T.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(Yn(t,e))},min(t,e){return this.check(Yn(t,e))},lt(t,e){return this.check(Gi(t,e))},lte(t,e){return this.check(Xn(t,e))},max(t,e){return this.check(Xn(t,e))},int(t){return this.check(Dx(t))},safe(t){return this.check(Dx(t))},positive(t){return this.check(Xi(0,t))},nonnegative(t){return this.check(Yn(0,t))},negative(t){return this.check(Gi(0,t))},nonpositive(t){return this.check(Xn(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 Y_(Yd,t)}var Bu=S("ZodNumberFormat",(t,e)=>{Qb.init(t,e),Yd.init(t,e)});function Dx(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)}function Kq(t){return nx(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 ox(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)},T.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(Yn(t,e))},min(t,e){return this.check(Yn(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(Xn(t,e))},max(t,e){return this.check(Xn(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(Xn(BigInt(0),t))},nonnegative(t){return this.check(Yn(BigInt(0),t))},multipleOf(t,e){return this.check(Ha(t,e))}}));function Zq(t){return ix(ep,t)}var tS=S("ZodBigIntFormat",(t,e)=>{e_.init(t,e),ep.init(t,e)});function Wq(t){return sx(tS,t)}function Jq(t){return ax(tS,t)}var ZC=S("ZodSymbol",(t,e)=>{t_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YR(t,r,o,n)});function Gq(t){return cx(ZC,t)}var WC=S("ZodUndefined",(t,e)=>{r_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eC(t,r,o,n)});function Xq(t){return ux(WC,t)}var JC=S("ZodNull",(t,e)=>{n_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QR(t,r,o,n)});function Wh(t){return lx(JC,t)}var GC=S("ZodAny",(t,e)=>{o_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nC(t,r,o,n)});function Yq(){return dx(GC)}var XC=S("ZodUnknown",(t,e)=>{i_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oC(t,r,o,n)});function ht(){return px(XC)}var YC=S("ZodNever",(t,e)=>{s_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rC(t,r,o,n)});function rS(t){return fx(YC,t)}var QC=S("ZodVoid",(t,e)=>{a_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tC(t,r,o,n)});function Qq(t){return mx(QC,t)}var Jh=S("ZodDate",(t,e)=>{c_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iC(t,r,o,n),t.min=(r,o)=>t.check(Yn(r,o)),t.max=(r,o)=>t.check(Xn(r,o))},T.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 eH(t){return hx(Jh,t)}var eO=S("ZodArray",(t,e)=>{qu(),u_.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 tH(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),T.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Er(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(T.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(T.mergeDefs(this._zod.def,{catchall:ht()}))},loose(){return this.clone(T.mergeDefs(this._zod.def,{catchall:ht()}))},strict(){return this.clone(T.mergeDefs(this._zod.def,{catchall:rS()}))},strip(){return this.clone(T.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return T.extend(this,t)},safeExtend(t){return T.safeExtend(this,t)},merge(t){return T.merge(this,t)},pick(t){return T.pick(this,t)},omit(t){return T.omit(this,t)},partial(...t){return T.partial(Ku,this,t[0])},exactPartial(...t){return T.partial(oS,this,t[0],"exactPartial")},required(...t){return T.required(iS,this,t[0])}});function H(t,e){let r={type:"object",shape:t??{},...T.normalizeParams(e)};return new Gh(r)}function rH(t,e){return new Gh({type:"object",shape:t,catchall:rS(),...T.normalizeParams(e)})}function Sr(t,e){return new Gh({type:"object",shape:t,catchall:ht(),...T.normalizeParams(e)})}var Xh=S("ZodUnion",(t,e)=>{Id.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.options=e.options});function st(t,e){return new Xh({type:"union",options:t,...T.normalizeParams(e)})}var tO=S("ZodXor",(t,e)=>{Xh.init(t,e),d_.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Px(t,r,o,n),t.options=e.options});function nH(t,e){return new tO({type:"union",options:t,inclusive:!1,...T.normalizeParams(e)})}var rO=S("ZodDiscriminatedUnion",(t,e)=>{Xh.init(t,e),p_.init(t,e)});function Yh(t,e,r){return new rO({type:"union",options:e,discriminator:t,...T.normalizeParams(r)})}var nO=S("ZodIntersection",(t,e)=>{f_.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,...T.normalizeParams(n)})}var Jd=S("ZodRecord",(t,e)=>{qu(),m_.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:$(),valueType:t,...T.normalizeParams(e)}):new Jd({type:"record",keyType:t,valueType:e,...T.normalizeParams(r)})}function oH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,...T.normalizeParams(r),partial:!0})}function iH(t,e,r){return new Jd({type:"record",keyType:t,valueType:e,mode:"loose",...T.normalizeParams(r)})}var sO=S("ZodMap",(t,e)=>{qu(),h_.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 sH(t,e,r){return new sO({type:"map",keyType:t,valueType:e,...T.normalizeParams(r)})}var aO=S("ZodSet",(t,e)=>{qu(),g_.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 aH(t,e){return new aO({type:"set",valueType:t,...T.normalizeParams(e)})}var Gd=S("ZodEnum",(t,e)=>{y_.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:[],...T.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:[],...T.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,...T.normalizeParams(e)})}function cH(t,e){return new Gd({type:"enum",entries:t,...T.normalizeParams(e)})}var cO=S("ZodLiteral",(t,e)=>{v_.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 X(t,e){return new cO({type:"literal",values:Array.isArray(t)?t:[t],...T.normalizeParams(e)})}var uO=S("ZodFile",(t,e)=>{w_.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 uH(t){return xx(uO,t)}var lO=S("ZodTransform",(t,e)=>{qu(),b_.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(T.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(T.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 nS(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)=>Rx(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ct(t){return new Ku({type:"optional",innerType:t})}var oS=S("ZodExactOptional",(t,e)=>{__.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Rx(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function dO(t){return new oS({type:"optional",innerType:t})}var pO=S("ZodNullable",(t,e)=>{x_.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 lH(t){return ct(Kh(t))}var fO=S("ZodDefault",(t,e)=>{S_.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():T.shallowClone(e)}})}var hO=S("ZodPrefault",(t,e)=>{E_.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():T.shallowClone(e)}})}var iS=S("ZodNonOptional",(t,e)=>{I_.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 iS({type:"nonoptional",innerType:t,...T.normalizeParams(e)})}var vO=S("ZodSuccess",(t,e)=>{k_.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 dH(t){return new vO({type:"success",innerType:t})}var wO=S("ZodCatch",(t,e)=>{$_.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:T.constantCatch(e)})}var _O=S("ZodNaN",(t,e)=>{A_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cC(t,r,o,n)});function pH(t){return gx(_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 zx(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 fH(t,e,r){return new eg({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function mH(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)=>{T_.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)=>{P_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uC(t,r,o,n)});function hH(t,e){return new IO({type:"template_literal",parts:t,...T.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)=>{C_.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 gH(t){return new AO({type:"promise",innerType:t})}var TO=S("ZodFunction",(t,e)=>{R_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fC(t,r,o,n)});function yH(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)=>{O_.init(t,e),Se.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pC(t,r,o,n)});function vH(t){let e=new at({check:"custom"});return e._zod.check=t,e}function sS(t,e){return Sx(tg,t??(()=>!0),e)}function PO(t,e={}){return Ex(tg,t,e)}function RO(t,e){return Ix(t,e)}var wH=kx,bH=$x,CO=S("ZodInstanceOf",(t,e)=>{tg.init(t,e)},{properties(t,e){return this.check(Ud(t,e))}});function _H(t,e={}){let r=new CO({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...T.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 xH=(...t)=>Ax({Codec:eg,Boolean:Qd,String:Xd},...t);function SH(t){let e=$O(()=>st([$(t),Je(),Wt(),Wh(),Oe(e),lt($(),e)]));return e}function rg(t,e){return new xO({type:"pipe",in:nS(t),out:e})}var nme={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 ome(t){Ft({customError:t})}function ime(){return Ft().customError}var OO;OO||(OO={});var Zu={};St(Zu,{ZodISODate:()=>Xa,ZodISODateTime:()=>Ga,ZodISODuration:()=>Qa,ZodISOTime:()=>Ya,date:()=>ame,datetime:()=>sme,duration:()=>ume,time:()=>cme});function sme(t){return Lh(Ga,t)}function ame(t){return Fh(Xa,t)}function cme(t){return Vh(Ya,t)}function ume(t){return qh(Qa,t)}var q={...rp,...Ox,iso:Zu},lme=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 dme(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 EH(t,e){return t.map((r,o)=>o<e?r:r.optional())}function pme(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function fme(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:pme(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 mme(t,e){return q.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 hme=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),gme=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])=>hme.has(e)?ng(r):!gme.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(ng))}function IH(t){return t===1?"element":"elements"}function yme(t,e){return q.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 ${IH(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 ${IH(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function kH(t,e){if(t!==!1)return t===void 0||t===!0?q.any():mn(t,e)}var vme=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function $H(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return q.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 q.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=fme(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 q.null();if(n.length===0)return q.never();if(n.length===1)return q.literal(n[0]);if(n.every(s=>typeof s=="string"))return q.enum(n);let i=n.map(s=>q.literal(s));return i.length<2?i[0]:q.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return q.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return $H(s,e)});return n.length===0?q.never():n.length===1?n[0]:q.union(n)}if(!r)return q.any();let o;switch(r){case"string":{let n=q.string();if(t.format){let i=t.format;i==="email"?n=n.check(q.email()):i==="uri"||i==="uri-reference"?n=n.check(q.url()):i==="uuid"||i==="guid"?n=n.check(q.uuid()):i==="date-time"?n=n.check(q.iso.datetime({offset:!0})):i==="date"?n=n.check(q.iso.date()):i==="time"?n=n.check(q.regex(vme)):i==="duration"?n=n.check(q.iso.duration()):i==="hostname"?n=n.check(q.hostname()):i==="ipv4"?n=n.check(q.ipv4()):i==="ipv6"?n=n.check(q.ipv6()):i==="mac"?n=n.check(q.mac()):i==="cidr"?n=n.check(q.cidrv4()):i==="cidr-v6"?n=n.check(q.cidrv6()):i==="base64"?n=n.check(q.base64()):i==="base64url"?n=n.check(q.base64url()):i==="e164"?n=n.check(q.e164()):i==="credit_card"?n=n.check(q.creditCard()):i==="iban"?n=n.check(q.iban()):i==="jwt"?n=n.check(q.jwt()):i==="emoji"?n=n.check(q.emoji()):i==="nanoid"?n=n.check(q.nanoid()):i==="cuid"?n=n.check(q.cuid()):i==="cuid2"?n=n.check(q.cuid2()):i==="ulid"?n=n.check(q.ulid()):i==="xid"?n=n.check(q.xid()):i==="ksuid"&&(n=n.check(q.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"?q.number().int():q.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=q.boolean();break}case"null":{o=q.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=q.string().regex(new RegExp(g));p.push(q.looseRecord(w,y))}let h=[];if(Object.keys(n).length>0&&h.push(q.object(n).passthrough()),h.push(...p),h.length===0)o=q.object({}).passthrough();else if(h.length===1)o=h[0];else{let g=q.intersection(h[0],h[1]);for(let y=2;y<h.length;y++)g=q.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(A=>A.test(I))||_.push(I);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=q.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=mme(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=EH(a,s),u=Array.isArray(i)?void 0:kH(i,e),l=q.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(q.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(q.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=EH(a,s),u=kH(t.additionalItems,e),l=q.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(q.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(q.maxLength(t.maxItems)))}else if(i!==void 0){let s=mn(i,e),a=q.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=q.array(q.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=yme(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?q.any():q.never();let r=$H(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=q.union(a);r=o?q.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>mn(u,e)),c=q.xor(a);r=o?q.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:q.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=q.intersection(a,mn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=q.nullable(r)),t.readOnly===!0&&(r=q.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))lme.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 AH(t,e){if(typeof t=="boolean")return t?q.any():q.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=dme(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 TH=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===TH)return new $d({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,TH);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 PH(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 wme(t,e){if(!e?.length)return t;let r=t._zod.def;return We(t,yo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function RH(t){return wme(t.out,t.checks)}function bme(t){return t.in._zod.traits.has("$ZodTransform")?RH(t):t.in}function CH(t){return og(t,{pipe:e=>bme(e._zod.def),default:(e,r)=>r?ct(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function OH(t){return og(t,{pipe:e=>RH(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var DO={};St(DO,{bigint:()=>Eme,boolean:()=>Sme,date:()=>Ime,number:()=>xme,string:()=>_me});function _me(t){return jR(Xd,t)}function xme(t){return UR(Yd,t)}function Sme(t){return LR(Qd,t)}function Eme(t){return FR(ep,t)}function Ime(t){return VR(Jh,t)}var ig={name:"@tomato414941/foundation",version:"22.1.1",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 $me(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 NH=m.string().trim().max(8192).refine(t=>$me(t)!==null,"Use an OpenSSH public key from a .pub file."),aS=m.object({authorizedKeys:m.array(NH).max(32)}).strict(),A2e=aS.extend({revision:m.number().int().positive().optional()}),zO=aS.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:NH.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),T2e=zO.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])});var np=new TextEncoder,op=new TextDecoder,DH=new TextDecoder("utf-8",{fatal:!0}),cS=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>=cS)throw new RangeError(`value must be >= 0 and <= ${cS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function MO(t){let e=Math.floor(t/cS),r=t%cS,o=new Uint8Array(8);return jO(o,e,0),jO(o,r,4),o}function uS(t){let e=new Uint8Array(4);return jO(e,t),e}var Ame=/[^\x00-\x7f]/;function Ir(t){if(typeof t=="string"&&t.length>=128){if(Ame.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 zH(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 jH(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 lS(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)}},L=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 dS=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 Tme="The input to be decoded is not correctly encoded.";function Ju(t){try{return jH(typeof t=="string"?t:op.decode(t),!0)}catch(e){throw new TypeError(Tme,{cause:e})}}function Nt(t){return zH(typeof t=="string"?np.encode(t):t,!0)}function Qn(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 zn(t,e,r){try{return Ju(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function pS(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(DH.decode(Ju(t)))}catch{throw new e(r)}if(!Yt(o))throw new e(r);return o}var fS={__proto__:null,b64:!0},mS={__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 hS(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 gS(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 Pme=t=>t[Symbol.toStringTag],Rme=(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 si(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 MH(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(Rme(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 MH(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${Pme(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=Cme[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,Cme={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function vS(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 UH(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)=>UH("Key must be ",t,...e);function MH(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(UH(`Key for the ${t} algorithm must be `,e,...o))}var yS=(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 yS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw yS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw yS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw yS(e.length,"algorithm.length");VO(t,r)}function wS(t){return{__proto__:null,...t}}function HO(t){let e=wS(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 bS(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 ai(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 _S(t,e){let r=t.byteLength<<3;if(r!==e)throw new L(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var Ome=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function LH(t,e){if(e.length<<3!==t.ivBits)throw new L("Invalid Initialization Vector length")}async function FH(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 VH(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Nme(t,e,r,o,n){let[i,s,a]=await FH(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 VH(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Dme(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 zme(t,e,r,o,n,i){let[s,a,c]=await FH(t,e,"decrypt"),u=hn(i,o,r,MO(i.length*8)),l=await VH(a,u,c);try{if(await Dme(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new ec}async function xS(t,e,r,o,n){if(!nc(r)&&!(r instanceof Uint8Array))throw new TypeError(ra(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?LH(t,o):o=Ome(t),r instanceof Uint8Array&&_S(r,t.cekBits),t.cbc)return Nme(t,e,r,o,n);let i=await ai(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 SS(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 L("JWE Initialization Vector missing");if(!n)throw new L("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new L("Invalid Authentication Tag length");if(LH(t,o),e instanceof Uint8Array&&_S(e,t.cekBits),t.cbc)return zme(t,e,r,o,n,i);let s=await ai(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 jme=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Mme=[[],["deriveBits"]],kS=[[],[]];function ES(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:jme,ops:["wrapKey","unwrapKey"]}}function IS(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:Mme,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:kS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function BO(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:kS,ops:["deriveBits","deriveBits"]}}var na=cg({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:kS,ops:["encrypt","decrypt"]},"RSA-OAEP":ES(1),"RSA-OAEP-256":ES(256),"RSA-OAEP-384":ES(384),"RSA-OAEP-512":ES(512),"ECDH-ES":IS("direct-key-agreement"),"ECDH-ES+A128KW":IS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":IS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":IS("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()}),Ume=["encrypt","decrypt"];function up(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:kS,ops:Ume,cekBits:t,ivBits:e?128:96,cbc:e}}var Lme=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 qH(t,e){throw new dt(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function ci(t){return(typeof t=="string"?na[t]:void 0)??qH("alg","Algorithm")}function ui(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function Yu(t){return(typeof t=="string"?Lme[t]:void 0)??qH("enc","Encryption Algorithm")}function HH(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 Fme(t,e,r){let o=await ai(e,ci(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 Vme(t,e,r){let o=await ai(e,ci(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 KH(t,e,r){qO(e,ci(t).subtle,r),sp(t,e)}async function ZH(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new L("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new L("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 ai(o,ci(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KO(t){return hn(uS(t.length),t)}async function qme(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 lS("sha256",hn(uS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function WH(t,e,r,o,n=new Uint8Array,i=new Uint8Array){HH(t),HH(e,"deriveBits");let s=hn(KO(Ir(r)),KO(n),KO(i),uS(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 qme(a,o,s)}function JH(t){vS(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 $S(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new L(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return zn(r,e,L)}}function GH(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 L('JOSE Header "apu" and "apv" values must be distinct')}}function Hme(t){if(t===void 0)throw new L("JWE Encrypted Key missing")}function BH(t){if(t!==void 0)throw new L("Encountered unexpected JWE Encrypted Key")}function Bme(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 XH(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return BH(o),r;let c=a==="direct-key-agreement";switch(c?BH(o):Hme(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 L('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');JH(r);let l=await ap(t,u),d=$S(n,"apu"),f=$S(n,"apv");GH(d,f);let p=await WH(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 vS(r),KH(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new L('JOSE Header "p2c" (PBES2 Count) missing or invalid');Bme(i);let u=i??1e4;if(n.p2c>u)throw new L('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new L('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=zn(n.p2s,"p2s",L);r=await ZH(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new L('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new L('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=zn(n.iv,"iv",L),l=zn(n.tag,"tag",L);if(u.byteLength!==12)throw new L("Invalid Initialization Vector length");if(l.byteLength!==16)throw new L("Invalid Authentication Tag length");return SS(Yu(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Vme(s.slice(-6),r,o)}async function AS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=ui(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await si(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&&_S(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{JH(u);let{apu:p,apv:h}=i;p!==void 0&&Qn(p,'"apu"'),h!==void 0&&Qn(h,'"apv"');let g=p??$S(o,"apu"),y=h??$S(o,"apv");GH(g,y);let w;i.epk!==void 0?w=await si(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:A,crv:k,kty:U}=await b.exportKey("jwk",_),Z=a==="direct-key-agreement",be=await WH(u,w,Z?e.alg:s,Z?e.cekBits:parseInt(s.slice(-5,-2),10),g,y),xe={x:I,crv:k,kty:U};if(U==="EC"&&(xe.y=A),f={epk:xe},p!==void 0&&(f.apu=Nt(p)),h!==void 0&&(f.apv=Nt(h)),Z)return[be,void 0,f];u=be;break}case"RSA-OAEP":{vS(u),KH(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 ZH(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 xS(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 Fme(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 TS(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 L('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function YH(t){if(typeof globalThis[t]>"u")throw new dt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function QH(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 L("Decompressed plaintext exceeded the configured limit")}return hn(...n)}async function eB(t){return YH("CompressionStream"),QH(new CompressionStream("deflate-raw"),t)}async function tB(t,e){return YH("DecompressionStream"),QH(new DecompressionStream("deflate-raw"),t,e)}function rB(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 L("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new L("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new L("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new L("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new L("JWE AAD incorrect type");if(s!==void 0&&!Yt(s))throw new L("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 nB(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 oB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new L("JWE Encrypted Key incorrect type");if(r!==void 0&&!Yt(r))throw new L("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new L("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,L,"JWE Protected Header is invalid")),[s,zn(r,"ciphertext",L),o!==void 0?zn(o,"iv",L):void 0,n!==void 0?zn(n,"tag",L):void 0,pS((e??"")+(i!==void 0?`.${i}`:""),"aad",L)]}function PS(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 L("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(L,mS,g,n,f),TS(f,n);let{alg:_,enc:I}=f;if(typeof _!="string"||!_)throw new L("missing JWE Algorithm (alg) in JWE Header");let A=na[_];if(b===""&&(!A||!ui(A)))throw new L("JWE Encrypted Key incorrect type");let k=A?.mode==="integrated-encryption";if(!k&&(typeof I!="string"||!I))throw new L("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 U;if(k){if(I!==void 0)throw new L('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new L("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new L("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');U=Yu(I)}let Z;if(b!==void 0)try{Z=zn(b,"encrypted_key",L)}catch(Ce){if(!A||!ui(A))throw Ce;Z=new Uint8Array}let be=!1;typeof r=="function"&&(r=await r(n,t),be=!0);let xe=A??ci(_);ui(xe)&&Z===void 0&&(Z=new Uint8Array);let Xe=await si(xe.mode==="direct-encryption"?U:xe,r,"decrypt"),re;if(xe.mode==="integrated-encryption")re=await xe.decrypt(Xe,Z,i,c,n,f);else{let Ce=U,G;try{G=await XH(xe,Ce,Xe,Z,f,y),ui(xe)&&G instanceof Uint8Array&&G.byteLength<<3!==Ce.cekBits&&(G=Xu(Ce))}catch(Ct){if(Ct instanceof TypeError||Ct instanceof L||Ct instanceof dt)throw Ct;G=Xu(Ce)}re=await SS(Ce,G,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 tB(re,Ce).catch(G=>{throw G instanceof L?G:new L("Failed to decompress plaintext",{cause:G})})}return{plaintext:re,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:zn(d,"aad",L)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...be&&{key:Xe}}}async function iB(t,e,r){if(t instanceof Uint8Array&&(t=op.decode(t)),typeof t!="string")throw new L("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 L("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 iB(t,PS(r),e)}async function JO(t,e,r){if(!Yt(t))throw new L("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new L("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Yt))throw new L("JWE Recipients missing or incorrect type");if(!n.length)throw new L("JWE Recipients has no members");let i,s,a;try{i=PS(r),s=rB(t),a=ZO(s)}catch{throw new ec}let c=n.map(u=>nB(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&&!ui(d))throw new L(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return oB(l),await WO(l,i,e,a)}catch{}throw new ec}function RS(t,e,r){if(!tc(t,e,r))throw new L("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 L("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&&Qn(s,"JWE Additional Authenticated Data"),a!==void 0&&Qn(a,"JWE Content Encryption Key"),c!==void 0&&Qn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Gu(L,o)[0],t[1]=o),n!==void 0&&(n=Gu(L,n)[0],t[2]=n),!r&&i!==void 0&&(i=Gu(L,i)[0],t[3]=i),u!==void 0&&!Yt(u))throw new TypeError("JWE Key Management Parameters must be an object");RS(o,n,i);let d={...o,...n,...i};hS(L,o),rc(L,mS,l,o,d),TS(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new L('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=na[f];if(h?.mode==="integrated-encryption"){if(p!==void 0)throw new L('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 L('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??ci(o.alg),b,_,I;w.mode==="integrated-encryption"?I=await si(w,r,"encrypt"):[I,b,_]=await AS(w,n,r,o,d,p),_&&(h?y=y?{...y,..._}:_:g=g?{...g,..._}:_,RS(g,y,u));let A=g?Nt(JSON.stringify(g)):"",k=l?.byteLength?Nt(l):void 0,U=Ir(k?`${A}.${k}`:A),Z=s;o.zip==="DEF"&&(Z=await eB(Z).catch(Ce=>{throw new L("Failed to compress plaintext",{cause:Ce})}));let be,xe,Xe;w.mode==="integrated-encryption"?[b,be]=await w.encrypt(I,Z,U,g,o,p):{ciphertext:be,tag:xe,iv:Xe}=await xS(n,Z,I,f,U);let re={ciphertext:Nt(be)};return Xe&&(re.iv=Nt(Xe)),xe&&(re.tag=Nt(xe)),b?.byteLength&&(re.encrypted_key=Nt(b)),k&&(re.aad=k),g&&(re.protected=A),u&&(re.unprotected=u),y&&(re.header=y),re}async function sB(t,e,r){return XO(t,GO(t,r),e)}function aB(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 L("at least one recipient must be added");Qn(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:A,enc:k},,U]=I;if(e&&U&&!ui(U))throw new L(`"${A}" alg may only have a single recipient`);if(!r)r=k;else if(r!==k)throw new L('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,h]of i)h[2]??=ci(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],[,A,k]=await AS(b,w,_,y,u,g[7]),U={encrypted_key:Nt(A)};if(I||k){let Z={...I,...k};k&&RS(g[1],Z,g[3]),U.header=Z}p.recipients.push(U)}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 cB(){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:cB(),Ed25519:cB(),"ML-DSA-44":tN(44),"ML-DSA-65":tN(65),"ML-DSA-87":tN(87)});function CS(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 uB(t){return[t&&ag("algorithms",t.algorithms),t?.crit]}function Kme(t){return t===void 0?{}:ip(t,At,"JWS Protected Header is invalid")}function Zme(t){try{return Ir(t)}catch{throw new At("JWS Compact Serialization payload must use only ASCII characters")}}async function Wme(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Kme(i);if(!tc(c,s))throw new At("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=gS(c,rc(At,fS,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=CS(d),g=hn(i!==void 0?Ir(i):new Uint8Array,Ir("."),typeof f=="string"?e[2]??=pS(f,"payload",At):f),y=zn(t.signature,"signature",At),w=await si(h,r,"verify"),b=await ai(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 dS;let I={payload:typeof f=="string"?zn(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 lB(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 Wme({payload:n,protected:o,signature:i},e,r,Zme)}async function nN(t,e,r){let[o]=await lB(t,uB(r),e);return o}var dp=class{#e;constructor(e){Qn(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 aB(await sB([...this.#e],e,r))}};async function Jme(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};hS(At,n);let u=gS(n,rc(At,fS,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=CS(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 ai(await si(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 dB(t,e,r,o,n){let[i]=await Jme([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var pg=class{#e;#t;constructor(e){Qn(e,"payload"),this.#e=e}setProtectedHeader(e){return bo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return dB(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=wS(t),typeof r.kty!="string")throw new TypeError(ra(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(FO(t))r=wS(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 lS(e,n))}async function _o(t,e,r){if(!Yt(t))throw new TypeError("JWK must be an object");let o=HO(t),n=bS(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 Gme(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=bS(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:Gme(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var hB=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),gB=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),pB=m.string().min(1).max(128),fB=m.string().min(1).max(16384),Xme=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:pB,secretAccessKey:fB}).strict(),m.object({kind:m.literal("session"),accessKeyId:pB,secretAccessKey:fB,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()]),Yme=m.object({arn:gB,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),ia=m.object({authentication:Xme,region:hB,role:Yme.optional()}).strict(),OS=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(),NS=ia.extend({sourceIdentity:OS.optional(),identity:OS.optional()}).strict();function pp(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function mB(t){return{...t,arn:pp(t.arn)}}function yB(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:mB(t.sourceIdentity)}:{},...t.identity?{identity:mB(t.identity)}:{}}}var DS=m.object({authentication:m.enum(["access_key","session","environment"]),region:hB,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:gB.optional(),expiresAt:m.number().int().positive().optional()}).strict();function vB(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 wB=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(wB),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function bB(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 wB.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),ge=m.iso.datetime(),ur=m.json(),pt=m.record(m.string(),ur),xB=m.enum(["ja","en"]),SB=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var EB=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(),Qme=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:x}).strict(),vg=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 Qme.safeParse(aN(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),eo=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(),dVe=m.object({id:x,name:ne,publicKey:kr}),ic=m.object({id:x,name:ne,owner:m.object({id:x,name:ne}).nullable(),createdAt:ge,permissions:m.array(SB),createKinds:m.array(EB),publicKey:kr.nullable()}),IB=m.object({id:x,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:ge,lastUsedAt:ge.nullable(),expiresAt:ge.nullable(),canOpen:m.boolean()}),cN=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ehe=m.object({subjectId:x,relation:cN,objectId:x}).strict(),kB=m.enum(["principal",...EB.options]),pVe=ehe.extend({objectType:kB,subjectName:ne,objectName:ne,createdAt:ge}),fVe=m.object({error:m.object({code:m.string(),message:m.string(),details:ur.optional()})}),mVe=m.object({ok:m.literal(!0)}),the=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(the).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."})}),uN=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),rhe=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)])),lN=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),jS=m.union([m.string(),m.array(m.string()).min(1)]),nhe=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:jS.default("/id"),name:jS.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:lN.default({default:[],separator:" "}),fields:m.array(US).default([]),outputs:uN.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."}),ohe=m.object({fields:m.array(US).min(1),outputs:rhe,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:jS,name:jS}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),dN=m.enum(["oauth","token","aws","ovh","approval"]),ihe=m.object({hint:m.string().optional()}).strict(),she=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:Qu,fields:m.array(US).min(1),scopes:lN.default({default:[],separator:`
|
|
129
129
|
`}),outputs:uN,hint:m.string().optional()}).strict(),fp=m.string().regex(/^[A-Z_][A-Z0-9_]*$/),_B=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:_B,value:fp}).strict(),m.object({kind:m.literal("query"),name:_B,value:fp}).strict()])}).strict(),wg={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({...wg,kind:m.literal("oauth"),config:nhe}).strict(),VS=m.object({...wg,kind:m.literal("token"),config:ohe}).strict(),qS=m.object({...wg,kind:m.literal("aws"),config:ihe}).strict(),HS=m.object({...wg,kind:m.literal("ovh"),config:she}).strict(),BS=m.object({...wg,kind:m.literal("approval"),config:m.object({adapter:m.literal("runpod-flash"),fields:m.array(US).default([]),scopes:lN.default({default:[],separator:" "}),outputs:uN,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()},bg=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}$/),pN=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(),ahe=pN.extend({methods:m.record(yg,m.string().min(1))}).strict(),$B=pN.extend({methods:m.record(yg,m.union([m.string().min(1),sc]))}).strict(),hVe=pN.extend({id:m.string(),builtin:m.boolean(),methods:m.record(yg,bg)}),AB=m.object({id:x,output:m.string().min(1).max(100).optional()}).strict(),TB=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),fN=m.object({name:m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:AB,format:m.enum(["text","file","json"]).default("text"),pointer:m.string().optional()}).strict(),che=m.object({pointer:m.string().max(500),parts:m.array(m.union([m.string().max(8192),AB])).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(che).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(fN).max(32).default([])}).strict(),PB=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()]),to=m.object({description:m.string().max(2e3).default(""),program:PB,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:ge.nullable().default(null)}).strict(),RB=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:ge,updatedAt:ge,version:m.number().int().positive(),permissions:m.array(SB)},uhe=m.enum(["starting","running","stopping","stopped","failed"]),lhe=m.enum(["manual","idle","timeout","quota","capacity","payment"]),dhe=m.object({state:m.enum(["pending","failed","complete"]),error:m.string().nullable()}),phe=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(),CB=m.object({size:m.enum(["small","medium","large"]).default("small"),lifetime:phe.default({idleSeconds:null,maxSeconds:null}),ssh:aS.optional()}).strict(),mN={recipients:m.array(x).default([]),executors:m.array(x).default([]),custodyRevision:m.number().int().positive().nullable().default(null)},fhe=m.object({...sa,kind:m.literal("variable"),data:m.object({...mN,bytes:m.number().int().nonnegative()})}),mhe=m.object({...sa,kind:m.literal("connection"),data:m.object({...mN,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:dN,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:DS.optional(),ovh:hg.optional()})}),hhe=m.object({...sa,kind:m.literal("service"),data:ahe}),ghe=m.object({...sa,kind:m.literal("method"),data:sc}),yhe=m.object({...sa,kind:m.literal("app"),data:m.object({...mN,methodId:m.string(),clientId:m.string(),fields:m.record(m.string(),m.string()).default({}),generation:x.optional()})}),vhe=m.object({...sa,kind:m.literal("object"),data:m.object({size:m.number().int().nonnegative(),contentType:m.string()})}),whe=m.object({...sa,kind:m.literal("environment"),data:CB.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:uhe,connected:m.boolean(),deletion:dhe.optional(),startedAt:ge.nullable(),stoppedAt:ge.nullable(),stopReason:lhe.nullable().default(null),lastActiveAt:ge,error:m.string().nullable()})}),KS=m.object({...sa,kind:m.literal("function"),data:to.omit({program:!0}).extend({program:PB.optional()})}),bhe=m.object({...sa,kind:m.literal("keyring"),data:m.object({revision:m.number().int().positive(),signature:m.string()})}),Ut=m.discriminatedUnion("kind",[fhe,mhe,hhe,ghe,yhe,vhe,whe,KS,bhe]),gVe=m.discriminatedUnion("kind",[m.object({kind:m.literal("service"),name:ne,definition:$B}).strict(),m.object({kind:m.literal("method"),name:ne,definition:sc}).strict(),m.object({kind:m.literal("environment"),name:ne.optional(),options:CB}).strict()]),yVe=m.object({version:m.number().int().positive(),name:ne.optional(),definition:m.union([$B,sc]).optional()}).strict(),li=m.object({name:m.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:pt}).strict(),ZS=li.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([])}),MS=m.object({ja:m.string(),en:m.string()}).strict(),hN=ZS.extend({title:MS,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:m.object({required:m.boolean(),reason:MS.nullable()}).strict()}),OB=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."})}),zS=m.object({id:x,name:ne}),NB=m.discriminatedUnion("kind",[m.object({kind:m.literal("line"),subject:zS,relation:cN,object:zS}),m.object({kind:m.literal("transfer"),item:zS,to:zS})]),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:ge,expiresAt:ge,url:m.url(),code:m.string().optional(),returnUrl:m.url().nullable(),refreshUrl:m.url().nullable(),canRespond:m.boolean(),canCancel:m.boolean()}),vVe=m.object({id:x,name:ne,publicKey:kr,state:m.enum(["pending","approving","approved"]),principalId:x.nullable(),createdAt:ge,expiresAt:ge}),wVe=m.object({available:m.boolean(),required:m.boolean(),active:m.boolean(),payer:ic.pick({id:!0,name:!0}).nullable()}),bVe=m.object({storageBytes:m.number().nonnegative(),storageLimit:m.number().positive(),computeSeconds:m.number().nonnegative(),computeLimit:m.number().positive(),month:m.string()}),_Ve=m.object({id:m.string(),actorId:x.nullable(),action:m.string(),targetId:x.nullable(),createdAt:ge,details:pt}),xVe=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)}),SVe=m.object({id:x}),EVe=m.object({owner:x}),_he=m.object({limit:m.coerce.number().int().min(1).max(200).default(100),after:m.string().optional()}),IVe=_he.extend({object:x.optional(),subject:x.optional(),relation:cN.optional(),objectType:kB.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var xhe=m.object({requestedAt:ge,readyAt:ge}).strict(),She=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:vg.nullable(),requestId:x.nullable(),keyReset:xhe.nullable(),server:m.object({name:ne}),features:She,principals:m.array(ic)}),TVe=m.object({email:m.email().max(254),returnTo:m.string().max(2048).optional(),locale:xB.default("ja"),principalId:x.optional()}).strict(),PVe=m.object({intent:m.enum(["register","authenticate"]),name:ne.optional(),principalId:x.optional(),credentialId:x.optional(),returnTo:m.string().max(2048).optional()}).strict(),RVe=m.object({challengeId:x,credential:m.json(),publicKey:kr.optional(),existingPublicKey:kr.optional(),wrappedKey:vg.optional()}).strict(),CVe=m.object({publicKey:kr,wrappedKey:vg}).strict();var Ehe=new TextEncoder,Ihe=new TextDecoder,_g="ECDH-ES+A256KW",gN="A256GCM",Ye=t=>Ehe.encode(t),gn=t=>Ihe.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(_g,{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:gN}).setAdditionalAuthenticatedData(Ye(r));for(let n of e)o.addRecipient(await _o(n.publicKey,_g)).setUnprotectedHeader({alg:_g,kid:n.id});return eo.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,_g);return(await JO({...t,recipients:[n]},i,{keyManagementAlgorithms:[_g],contentEncryptionAlgorithms:[gN]})).plaintext}async function khe(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 DB(t,e,r){let o=await ug(t,await khe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[gN]});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),zB=kr.extend({d:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}),xg=m.object({encryption:zB,signing:zB}).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 jB(){let[t,e]=await Promise.all([XS(),mg("ES256",{crv:"P-256",extractable:!0})]),r=await oc(e.privateKey);return xg.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 MB(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 Sg(e,r,o))!==P(t))throw new Error("The signature does not authorize this content.")}async function Sg(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 yN(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 UB=m.object({ownerId:x,name:ne,resourceId:x.optional(),version:m.number().int().positive().optional(),environmentIds:m.array(x).max(32).optional()}).strict(),LB=UB.extend({value:m.literal("").optional()}),vN=UB.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:to,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(),wN=m.object({ownerId:x,connectionId:x,environmentId:x}).strict(),FB=m.object({ownerId:x,connectionId:x,version:m.number().int().positive(),users:m.array(x).max(32),expiresAt:m.iso.datetime().optional()}).strict(),VB=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:li.shape.name,title:MS,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:hN.shape.environment,input:pt}).strict(),qB=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(),HB=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:li,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:li.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(hN),approval:m.object({requestId:x.nullable(),proposal:NB.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(),BB=m.object({id:x,index:m.number().int().nonnegative(),invocation:li,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."),ye={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},$he=m.enum([ye.value,ye.tokenSet,ye.clientCredential,ye.executionResult]),ZB=t=>t===ye.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"},Eg=m.enum([ie.http,ie.command,ie.function,ie.connect,ie.refresh,ie.revoke]);var Ahe={[ye.value]:[ie.http,ie.command,ie.function],[ye.tokenSet]:[ie.http,ie.command,ie.function,ie.refresh,ie.revoke],[ye.clientCredential]:[ie.connect,ie.refresh,ie.revoke],[ye.executionResult]:[]},lc=t=>Ahe[t],WB=t=>lc(t).filter(e=>e===ie.function||e===ie.refresh),bN=t=>t===ye.tokenSet,The=m.object({id:x,digest:Dt}).strict(),Phe=m.object({actor:bt,executor:bt,operations:m.array(Eg).min(1).max(6),functionDigests:m.array(Dt).max(100).default([]),origins:m.array(vp).max(100).default([]),callerProgram:m.boolean().default(!1),expiresAt:ge}).strict(),Rhe=m.object({function:The,executor:bt,operations:m.array(Eg).min(1).max(6),expiresAt:ge.nullable()}).strict(),Che=m.union([Phe,Rhe]);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 $r=m.object({format:m.literal(2),origin:vp,id:x,ownerId:x,contentType:$he,revision:m.number().int().positive(),authorities:m.array(bt).min(1).max(100),readers:m.array(bt).min(1).max(100),grants:m.array(Che).max(100),observers:m.array(x).max(100).optional(),producers:m.array(m.object({executor:bt,runId:x,expiresAt:ge,materialRevision:m.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),KB=m.object({ownerId:x,authorities:m.array(bt).min(1).max(100)}).strict(),JB=m.object({origin:vp,id:x,revision:m.number().int().positive(),from:KB,to:KB,policyDigest:Dt,previous:Dt.nullable(),signerId:x}).strict(),Ohe=JB.extend({signature:zt}),_N=m.array(Ohe).max(16),Ig=m.object({policy:$r,authorityId:x,signature:zt,lineage:_N.optional()}).strict(),Ar=m.object({policy:$r,authorityId:x,authorization:zt,lineage:_N.optional(),materialRevision:m.number().int().positive(),updatedAt:ge,creationRunId:x.nullable(),metadata:pt,sealed:eo,signerId:x,signature:zt}).strict(),rl=t=>({ownerId:t.ownerId,authorities:t.authorities});async function GB(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 xN(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 XB(t,e,r,o){let n=[...t?.lineage??[]];if(t&&P(rl(t.policy))!==P(rl(e))){if(await di(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=JB.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:_N.parse(n)}:{}}async function i0(t){let e=$r.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>ZB(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await i0(e),c=await XB(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===ye.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=Ar.parse({...l,signature:await Jt(l,n.signing,"resource")});return await di(d),d}async function di(t){let e=Ar.parse(t),{signature:r,...o}=e;await i0(e.policy),await GB(e.policy,e.lineage);let n=xN(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===ye.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(bN(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 YB(t,e,r,o,n=t.metadata){let i=await di(t);if(!bN(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 di(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 XB(o,n,e,r),authorityId:e.id,signature:await Jt(n,r.signing,"access-policy")};return await kg(i),i}async function kg(t){let e=Ig.parse(t);await i0(e.policy),await GB(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 QB(t,e,r,o,n,i){let s=await kg(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&P(f.executor)===P(o)&&(a.contentType===ye.executionResult||Date.parse(f.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>ZB(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 di(d),d}async function il(t,e,r){let o=await di(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 Nhe=m.object({id:x,policyDigest:Dt,materialRevision:m.number().int().positive(),authorizationDigest:Dt.optional()}).strict();async function Dhe(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||bN(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:BB.optional(),actor:bt,environmentId:x,executor:bt,environmentDigest:Dt,operation:Eg,functionDigest:Dt.nullable(),functionId:x.optional(),operationDigest:Dt,sources:m.array(Nhe).max(100),resultRecipients:m.array(bt).min(1).max(100),resultApproval:Ig.optional(),createdAt:ge,expiresAt:ge}).strict(),$g=m.object({intent:c0,signature:zt,sealed:eo}).strict();async function u0(t,e){return P({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await oe(t)})}async function eK(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 $g.parse({...o,signature:await Jt(o,r.signing,"run")})}async function yp(t,e,r={}){let o=await di(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await Dhe(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 Ag(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 EN=5,tK=1,zhe=m.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),jhe=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(Eg).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:zhe.optional(),revision:m.number().int().positive()}).strict(),IN=m.object({manifest:jhe,signature:zt}).strict();async function kN(t){let e=IN.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 rK(t,e){let{manifest:r}=await kN(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!==EN)throw new Error("This environment does not authorize the requested execution.")}var l0=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),$N=m.object({ok:m.boolean(),result:ur.nullable(),error:m.object({code:m.string().max(100),message:m.string().max(1e3)}).nullable()}).strict(),nK={id:x,intentDigest:Dt,executorId:x,state:m.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:ge},oK=m.object({...nK,sealed:eo,signature:zt}).strict(),iK=m.object({...nK,format:m.literal(2),accessDigest:Dt,proofDigest:Dt,approval:Ig,content:Ar,previousDigest:Dt.optional(),previous:oK.optional(),signature:zt}).strict(),d0=m.union([oK,iK]),Mhe=m.object({result:$N,proof:zt}).strict(),sK=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function aK(t,e,r,o,n,i){await kg(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:$N.parse(r),proof:a}));if(c.byteLength>14e5)throw new SN;let u=await QB(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await oe(a)},d=iK.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await Jt(l,o.signing,"receipt")});return await AN(d,t),d}var SN=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function AN(t,e){let r=d0.parse(t);if("content"in r){await Zr(sK(r),r.signature,e.executor.signing,"receipt");let i=await kg(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!==ye.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 AN(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 di(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 cK(t,e,r,o){if(await AN(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=Mhe.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}=sK(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=$N.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 Uhe=m.enum(["http","command","function","connect","refresh","revoke"]),yn=m.object({id:x,ownerId:x,actorId:x,environmentId:x,kind:Uhe,state:l0,intent:c0,requestSignature:zt,receipt:d0.nullable(),error:m.string().nullable(),createdAt:ge,startedAt:ge.nullable(),finishedAt:ge.nullable()}).strict(),p0=m.object({name:ne,approval:Ig}).strict(),nqe=m.object({kind:m.literal("function"),functionId:x,definition:to,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 Lhe,lstat as Fhe,mkdir as Vhe,open as TN,readFile as lK,rename as qhe,rm as Hhe}from"node:fs/promises";import{dirname as Bhe,join as PN,resolve as Khe}from"node:path";import{homedir as Zhe}from"node:os";import{randomUUID as Whe}from"node:crypto";var RN=m.object({origin:m.url(),principalId:m.uuid(),token:m.string().min(20),keys:xg.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."),dK=m.object({current:m.uuid(),identities:m.array(RN).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function la(){return PN(process.env.XDG_CONFIG_HOME||PN(Zhe(),".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 CN(){try{let t=la(),e=await Fhe(t);if(!e.isFile()||e.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&e.mode&63&&await Lhe(t,384),dK.parse(JSON.parse(await lK(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 pK(){let t=await CN();return(t?.identities??[]).map(e=>({...e,current:e.principalId===t.current}))}async function fK(t){let e=await CN();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 mK(t,e){let r=process.env.FOUNDATION_TOKEN,o=e||(r?void 0:process.env.FOUNDATION_PRINCIPAL_ID),n=await CN(),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 RN.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 ON(t){let e=la(),r;try{r=dK.parse(JSON.parse(await lK(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=RN.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
|
-
`,!!r)}async function uK(t){if(process.platform==="win32")return;let e=await TN(t,"r");try{await e.sync()}finally{await e.close()}}async function fc(t,e,r){let o=Khe(t),n=Bhe(o);if(await Vhe(n,{recursive:!0,mode:448}),!r){let s=await TN(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await uK(n);return}let i=PN(n,".foundation-"+Whe());try{let s=await TN(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await qhe(i,o),await uK(n)}finally{await Hhe(i,{force:!0})}}import{spawn as Jhe}from"node:child_process";import{chmod as Ghe,mkdtemp as Xhe,rm as Yhe,writeFile as Qhe}from"node:fs/promises";import{tmpdir as ege}from"node:os";import{join as gK}from"node:path";import{StringDecoder as tge}from"node:string_decoder";function hK(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 rge(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 tge("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 yK(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await Xhe(gK(ege(),"foundation-"));await Ghe(r,448);try{let o=hK(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=gK(r,i);await Qhe(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=Jhe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=rge(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 Yhe(r,{recursive:!0,force:!0})}}import{dirname as zPe,join as z4}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 pi(t,e){return[...new Set([...t.required??[],...e??t.default])]}function mc(t){return Vt(t).requiresApp}function vK(t){return t.kind==="approval"?"unavailable":!Vt(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth"?"available":t.config.browserTokenExchange??"unknown"}var nge=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),wK=pt.refine(t=>Object.keys(t).every(e=>!nge.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:wK,details:wK}).strict();function NN(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 DN(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 zN(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:yB(t.aws)},details:{aws:vB(t.aws)}})}var oge={oauth:NN,token:_p,aws:zN,ovh:DN,approval:_p};function Tg(t){return oge[t.method.kind](t)}var iZ=$t(FK(),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"}},Tge=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"}},Pge=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"}},Rge=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"}},Cge=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"}},Oge=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"}},Nge=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"}},Dge=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"}},BN=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"}},zge=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"}},jge=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"}},VK=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"}},Mge=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"}},Uge=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},Lge=class extends Uge{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"}},Fge=["","+",".","/",";","?","&","#"],JK={"":{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}},Vge=new TextEncoder,qK="0123456789ABCDEF",HK=t=>vc(Gr(48,57),Gr(65,70),Gr(97,102))(t.charCodeAt(0)),Og=(t,e)=>t[e]==="%"&&e+2<t.length&&HK(t[e+1])&&HK(t[e+2]);function KN(t,e){let r=t[e];return r==null?0:vc(GK,XK,cl("_"))(r)?1:Og(t,e)?3:0}function qge(t,e){if(Og(t,e))return 3;let{char:r,size:o}=Ng(t,e);return Bge(r)?o:0}function Ng(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 GN=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Og(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Ng(e,o);r+=vc(YK,s=>t&&Hge(s))(n)?n:QK(n),o+=i}return r};function Ep(t){let e="";for(let r=0;r<t.length;){if(Og(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Ng(t,r);e+=YK(o)?o:QK(o),r+=n}return e}function Rg(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Og(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Ng(t,n);r+=i,n+=s}return r}var GK=t=>vc(Gr(65,90),Gr(97,122))(t.charCodeAt(0)),XK=t=>Gr(48,57)(t.charCodeAt(0)),YK=t=>vc(GK,XK,e=>"-._~".includes(e))(t),Hge=t=>":/?#[]@!$&'()*+,;=".includes(t),Bge=t=>Kge(t.codePointAt(0)),Kge=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),Zge,Wge)(t);function Zge(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 Wge=t=>vc(Gr(57344,63743),Gr(983040,1048573),Gr(1048576,1114109))(t),QK=t=>Array.from(Vge.encode(t)).map(e=>`%${qK[e>>4]}${qK[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 eZ(t,e,r){return t.map(o=>o.kind==="literal"?o.text:Jge(o.vars,o.operator,e,r)).join("")}function Jge(t,e,r,o){let n=JK[e],i=t.flatMap(s=>Gge(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function Gge(t,e,r,o){if(e==null)return[];if(oye(e)){let n=eye(e,r.allowReserved);return n.length<1?[]:BK(t,"list",o)?Yge(t,n,r):[]}if(nye(e)){let n=tye(e,r.allowReserved);return n.length<1?[]:BK(t,"associative",o)?Qge(t,n,r):[]}return Xge(t,e,r)}function Xge(t,e,r){let o=String(e),n=t.prefix==null?o:Rg(o,t.prefix),i=GN(r.allowReserved)(n);return r.named?[Cg(Ep(t.name),i,r)]:[i]}function Yge(t,e,r){let o=Ep(t.name);if(t.explode)return r.named?e.map(i=>Cg(o,i,r)):[...e];let n=e.join(",");return r.named?[Cg(o,n,r)]:[n]}function Qge(t,e,r){if(t.explode)return e.map(([n,i])=>Cg(n,i,r));let o=e.flat(1).join(",");return r.named?[Cg(Ep(t.name),o,r)]:[o]}var Cg=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,eye=(t,e)=>t.filter(r=>r!=null).map(String).map(GN(e)),tye=(t,e)=>Object.entries(t).map(([r,o])=>[r,rye(o)]).filter(([,r])=>r!=null).map(r=>r.map(GN(e)));function rye(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 nye=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),oye=t=>Array.isArray(t);function BK(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new Lge(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function iye(t,e,r){return ZN(t,e,r,0,0,{})}function ZN(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=Cye(i);return eZ(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?ZN(t,e,r,o+1,n+s.text.length,i):null;for(let a of sye(t,e,o,n)){let c=e.slice(n,a);for(let u of cye(s.vars,s.operator,c)){let l=XN(i,u);if(l==null)continue;let d=ZN(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*sye(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*aye(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*aye(t,e){for(let r=t;r>=e;r--)yield r}function*cye(t,e,r){if(r===""){yield*uye(t,e);return}let o=JK[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?vye(t,o,n):lye(t,o,n)}var uye=(t,e)=>(e===""||e==="+")&&t.length===1?[yc(t[0],"")]:[{}],lye=(t,e,r)=>WN(t,e,YN(r,e.sep),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 dye(i,e,r,n))for(let a of WN(t,e,r,o+1,s.index)){let c=XN(s.bindings,a);c!=null&&(yield c)}yield*WN(t,e,r,o+1,n)}function*dye(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 pye(t,e,s))yield{bindings:a,index:o+i}}}function*pye(t,e,r){let o=tZ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*fye(t,e,r)),yield*o}function*fye(t,e,r){let o=rZ(r,e.allowReserved);if(o==null)return;let n=mye(r,e);n!=null&&(yield yc(t,n)),yield yc(t,o)}var mye=(t,e)=>hye(t.join(e.sep),e);function hye(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=gye(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 gye(t,e,r){for(let o=e;o<t.length;o++)if(yye(t,o,r))return o;return t.length}var yye=(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*tZ(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=YN(r,",");if(i.length<2){yield n;return}let s=rZ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?$ye(i,e.allowReserved):null;a!=null&&(yield yc(t,a)),yield yc(t,s),yield n}var vye=(t,e,r)=>JN(t,e,YN(r,e.sep).map(kye),0,0);function*JN(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of wye(i,e,r,n,t))for(let a of JN(t,e,r,o+1,s.index)){let c=XN(s.bindings,a);c!=null&&(yield c)}yield*JN(t,e,r,o+1,n)}function*wye(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*_ye(t,e,r,o,n);return}yield*bye(t,e,r,o)}}function*bye(t,e,r,o){let n=r[o];if(n.name===Ep(t.name))for(let i of tZ(t,e,n.value))yield{bindings:i,index:o+1}}function*_ye(t,e,r,o,n){yield*xye(t,e,r,o),yield*Eye(t,e,r,o,n)}function*xye(t,e,r,o){let n=[...Sye(Ep(t.name),e,r,o)];n.length>0&&(yield{bindings:yc(t,n),index:o+n.length})}function*Sye(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*Eye(t,e,r,o,n){let i=[...Iye(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*Iye(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 kye(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function $ye(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 rZ(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 XN(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=Aye(i,n);if(s==null)return null;r[o]=s}return r}var Aye=(t,e)=>S0(t)||S0(e)?Tye(t,e):Pye(t.value,e.value)?t:null;function Tye(t,e){let r=KK(t.value),o=KK(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 Rg(o,t.prefix)===r?e:null;if(!n&&i)return Rg(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Rg(o,s)===r?e:null:Rg(r,a)===o?t:null}var S0=t=>t.prefix!=null,KK=t=>typeof t=="string"?t:null;function Pye(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):ZK(t)?ZK(e)&&Rye(Object.entries(t),Object.entries(e)):t===e}var Rye=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),ZK=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Cye=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),YN=(t,e)=>e===""?[t]:t.split(e),Oye=["=",",","!","@","|"];function Nye(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new Oge(e,r));let n=t[0];if(Mye(n))return o(new Nge(e,r+1,n));if(!WK(n)&&KN(t,0)<1)return o(new Dge(e,r+1,n));let i=WK(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:Dye(t,e,r+1,s)}}function Dye(t,e,r,o){if(o>=t.length)throw new BN(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new VK(e,r+i):new BN(e,r+i);let s=i,a=zye(t,i);if(a===s)throw new BN(e,r+i);let c=t.slice(s,a);i=a;let u=jye(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new Mge(e,r+i,t[i]):new zge(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 VK(e,r+i-1)}return n}function zye(t,e){let r=e,o=!0;for(;r<t.length;){let n=KN(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||KN(t,r+1)<1)break;r++,o=!0}return r}function jye(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&&Uye(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new jge(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function WK(t){return Fge.includes(t)&&t!==""}function Mye(t){return Oye.includes(t)}function Uye(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function Lye(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 Tge(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new Rge(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(Nye(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 Pge(t,i)),n(s),i++;continue}let a=qge(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Ng(t,i);r(new Cge(t,i,c)),n(c),i+=u}return o}var nZ=class oZ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=Bye(r),this.#e=Fye(Lye(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new oZ(e,r)}get tokens(){return this.#e}expand=e=>eZ(this.#e,e,this.#t);match=e=>iye(this.#e,e,this.#t);toString=()=>this.uriTemplate},Fye=t=>Object.freeze(t.map(Vye)),Vye=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(qye))}),qye=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),Hye=()=>{},Bye=({strict:t,report:e})=>(e??=Hye,t??=!0,e=t?Kye(e):e,{strict:t,report:e}),Kye=t=>e=>{throw t(e),e};var ha=class extends Error{constructor(r,o){super(o);this.code=r}code};function Zye(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(!Zye(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,iZ.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 jn(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 sZ(t,e=Tg(t)){return e.accountVerified?e.accountId:null}function aZ(t,e=Tg(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"?jn(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(),QN=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(),Dg={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(),Pr=m.union([m.object({...Dg,method:FS,oauth:QN.optional(),requestedScopes:m.array(m.string()).optional(),implicitApp:vn.optional(),fields:wc.optional(),aws:ga}).strict(),m.object({...Dg,method:VS,fields:wc,facts:hc.optional(),oauth:ga,aws:ga}).strict(),m.object({...Dg,method:BS,fields:wc,oauth:ga,aws:ga}).strict(),m.object({...Dg,method:HS,fields:wc,ovh:hg.optional(),requestedScopes:m.array(m.string()).optional(),oauth:ga,aws:ga}).strict(),m.object({...Dg,method:qS,aws:NS,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."})}),hHe=m.object({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),generation:x,fields:wc.optional()}).strict(),Wye=m.object({methodId:m.string().min(1).max(200),methodKind:dN,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:DS.optional(),ovh:hg.optional()}).strict();async function kp(t,e=Tg(t)){let{outputs:r,revocable:o}=Vt(t.method),n=t.method.kind!=="aws"&&t.fields?jn(t.method.config.fields,t.fields):{},i=await oe(aZ(t,e));return Wye.parse({methodId:t.methodId,methodKind:t.method.kind,...t.method.http?{http:t.method.http}:{},generation:t.generation,authorizationDigest:i,appId:t.appId,accountId:sZ(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 Jye=m.array(m.object({name:m.string(),label:m.string(),value:m.string()}).strict()),cZ=m.object({methodName:ne,account:m.string().max(2e3),settings:Jye.optional()}).strict();function $0(t){let e=Vt(t.method).fields,r=t.method.kind!=="aws"&&t.fields?jn(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 eD=m.discriminatedUnion("action",[m.object({action:m.literal("refresh"),id:x}).strict(),m.object({action:m.literal("revoke"),id:x}).strict()]);var tD=ca.extend({name:ne}),EHe=ca.extend({previousSignature:zt.optional()}).strict(),uZ=m.object({name:ne,content:Ar,labels:cZ.optional(),version:m.number().int().positive().optional()}).strict(),zg=m.object({content:Ar,version:m.number().int().positive()}).strict(),lZ=m.object({id:x,reason:m.enum(["grantExpired","recipients"]),remove:m.array(x).max(1e3).default([])}).strict(),IHe=m.record(x,m.object({version:m.number().int().positive(),content:Ar}).strict()),dZ=m.object({id:x,name:ne,version:m.number().int().positive(),content:Ar,policy:$r}).strict(),pZ=m.object({registration:IN,stoppedAt:m.iso.datetime().nullable(),heartbeatAt:m.iso.datetime().nullable()}).strict(),fZ=m.object({lease:x,request:$g,sources:m.array(Ar).max(100)}).strict().nullable(),Gye=m.object({lease:x}).strict(),kHe=Gye.extend({receipt:d0}).strict(),jg=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:Ar.nullable()}),$He=m.object({id:x,resourceId:x,expectedRevision:m.number().int().positive()}).strict(),Xye=m.object({fence:m.string().regex(/^\d+$/)}).strict(),AHe=Xye.extend({content:Ar}).strict(),THe=m.object({id:x,executionId:x,index:m.number().int().nonnegative(),stateDigest:Dt,expiresAt:ge}).strict(),rD=m.object({id:x,executionId:x,context:m.string(),sealed:eo.nullable(),expiresAt:ge,receivedAt:ge.nullable()}).strict(),mZ=(t,e)=>"oauth-callback:"+t+":"+e;var Yye=m.object({binding:bt,verifiedAt:ge}).strict(),nD=m.object({origin:m.url(),ownerId:x,signerId:x,revision:m.number().int().positive(),keys:m.array(Yye).max(1e3)}).strict(),Qye=m.object({version:m.number().int().positive(),signature:zt}).strict(),oD=m.object({keyring:Qye.nullable()}).strict(),DHe=m.object({version:m.number().int().positive().nullable(),signature:zt}).strict();function hZ(t,e){return Jt(nD.parse(t),e,"keyring")}function gZ(t){return nD.parse(JSON.parse(gn(GS(t.split(".")[1]??""))))}async function yZ(t,e){let r=nD.parse(await Sg(t,e.signing,"keyring"));if(r.signerId!==e.id)throw new Error("Another identity signed this keyring.");return r}var $p=$t(wZ(),1);var Rr=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 Rr(t,e,r,o)}var eve=$p.default.IPv6.parseCIDR("2000::/3"),tve=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 tve.has(e.range())&&(!(e instanceof $p.default.IPv6)||e.match(eve))}function Mn(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 fi(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=Mn(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 iD(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=Mn(e.url??n??"",r);return n&&i.origin!==Mn(n,r).origin&&N(400,"invalid_destination","Use this connection only at its configured destination host."),i.href}function bZ(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 wn=class extends Error{constructor(r,o){super(o);this.code=r}code},aD=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},sD=(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 e.principalId!==this.binding.principalId&&await this.known(e.principalId)?new wn("identity_changed","Identity "+e.principalId+" replaced the keys verified before. Verify its current keys."):new wn("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.known(e.principalId);return!!r&&P(r)===P(e)}async known(e){return(await this.keyring()).get(e)?.binding??await this.trust.binding(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(sD(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 wn)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,{},oD),o=await this.trust.keyring(),n=()=>new wn("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=gZ(r.signature);if(i.signerId!==this.binding.id)return{version:r.version,revision:i.revision,keyring:null};let s=await yZ(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 hZ(n,this.keys.signing)}},oD)}catch(i){if(r<3&&sD(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 wn("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(!sD(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",{},pZ);if(await kN(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(tD));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-delegates",{},lr(tD)),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 wn&&["identity_untrusted","identity_changed"].includes(a.code)))throw a}}return[...r.map(i=>i.binding),...n]}async read(e){let r=await this.latest(e);if(r.replaced)throw new wn("key_replaced","This item is sealed only for keys this identity has since replaced. Enter its value again.");return r}async latest(e){let r=await this.api.json("/api/custody/"+x.parse(e),{},zg);return this.replaces(r.content.policy)?{...r,replaced:!0}:(await this.observe(r.content,e),{...r,replaced:!1})}replaces(e){return!e.readers.some(r=>P(r)===P(this.binding))&&e.readers.some(r=>r.principalId===this.binding.principalId)}async observe(e,r=e.policy.id){let o=await di(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=xN(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&$r.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 wn("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!o0(i.policy,o)&&!i.policy.authorities.some(s=>s.principalId===n.principalId&&s.id!==n.id))throw new wn("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(dZ))).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 wn("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!==ye.clientCredential,expiresAt:s});return $r.parse({format:2,id:n.id??n.previous?.id??n.replacing?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??n.replacing?.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&&!this.replaces(i.content.policy)?i.content:void 0),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(lZ))).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=new Map(c.map(k=>[k.principalId,k])),l=[...i.readers,...i.authorities,...i.grants.flatMap(k=>"actor"in k?[k.actor,k.executor]:[k.executor])];if(r==="recipients")for(let k of new Set(l.map(U=>U.principalId))){if(k===this.binding.principalId||u.has(k)||a.has(k))continue;let U=await this.inspectIdentity(k).then(Z=>Z.binding,()=>null);U&&l.some(Z=>Z.principalId===k&&Z.id!==U.id)&&u.set(k,await this.trusted(U))}let d=k=>u.get(k.principalId)??k,f=k=>[...new Map(k.map(U=>[U.id,U])).values()],p=k=>!a.has(k.principalId),h=i.grants.filter(k=>nl(k,s)&&p(k.executor)&&(!("actor"in k)||p(k.actor))).map(k=>"actor"in k?{...k,actor:d(k.actor),executor:d(k.executor)}:{...k,executor:d(k.executor)}),g=f(i.readers.filter(p).map(d)),y=f(i.authorities.filter(p).map(d)),w=c.filter(k=>!g.some(U=>U.id===k.id)),b={...i,revision:i.revision+1,grants:h,producers:[],readers:[...g,...w],authorities:[...y,...w.filter(k=>!y.some(U=>U.id===k.id))],...i.observers?{observers:i.observers.filter(k=>!a.has(k))}:{}},_=i.contentType!==ye.executionResult&&i.producers.some(k=>Date.parse(k.expiresAt)>s);if(P({...b,revision:i.revision})===P(i)||_)return null;let I=await il(n.content,this.binding,this.keys.encryption);if(i.contentType===ye.executionResult){let k=await ol(I,b,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:k,version:n.version}},zg),await this.trust.rememberContent(k),e}let A=await this.api.json("/api/resources/"+i.id,{},Ut);return this.save(A.name,I,b,{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===ye.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 d=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),f=await this.api.json("/api/principals/"+e+"/resources?"+d,{},lr(Ut));s=f.items.find(p=>p.name===r),a=f.next}while(!s&&a);let c=s?await this.latest(s.id):void 0,u=c?.content,l=u&&!c.replaced?{...u.policy,revision:u.policy.revision+1,producers:[]}:await this.policy(e,ye.value,[],{replacing:u?.policy});return l.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(u?.materialRevision??0)+1}],{name:r,approval:await a0(l,this.binding,this.keys,c?.replaced?void 0:u)}}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!==tK)throw new wn("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===ye.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 k=await this.read(w.policy.id),U=await this.api.json("/api/resources/"+w.policy.id,{},Ut),Z={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([_,...w.policy.contentType===ye.tokenSet?[ie.refresh]:[]])],origins:I?[I]:[],functionDigests:[],callerProgram:!b,expiresAt:c},be=re=>P({...re,expiresAt:null}),xe=k.content.policy.grants.filter(re=>be(re)===be(Z)),Xe=$r.parse({...k.content.policy,revision:k.content.policy.revision+1,grants:[...k.content.policy.grants.filter(re=>nl(re)&&be(re)!==be(Z)),{...Z,expiresAt:new Date(Math.max(Date.parse(c),...xe.map(re=>n0(re)))).toISOString()}]});await this.save(U.name,await il(k.content,this.binding,this.keys.encryption),Xe,{previous:k,metadata:k.content.metadata}),f[y]=(await this.read(w.policy.id)).content}let p=await this.policy(e,ye.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===ye.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 rK(s,h);let g=y=>y.policy.contentType===ye.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 eK(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 aD(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 Sg(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 wn("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?cK(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 wn("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,ye.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await aK(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 rve,mkdir as _Z,readFile as nve,readdir as xZ,rm as ove}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}$/),Mg=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 rve(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 nve(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 _Z(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 _Z(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 ove(Ap(this.directory,"pending",e),{force:!0})}async pending(e){await this.index();let r;try{r=await xZ(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 xZ(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 Rr(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},fZ)}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}},jg),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},jg),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},Ar),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}},jg),state:r=>e.json("/api/connections/"+r+"/operation",{},jg.nullable())}}};import{randomUUID as PPe}from"node:crypto";var Ta=$t(foe(),1);import{randomUUID as STe}from"node:crypto";function moe(t){let e=OS.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 hoe(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&pp(t.arn)===pp(e.arn)}function w4(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)}:{}};w4(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();w4(d.expiration),c=new Ta.STSClient({region:n.region,credentials:d});let f=r?.sourceIdentity?moe(await c.send(new Ta.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&f&&!hoe(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-"+STe().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},w4(p.expiration),r?.identity&&(c.destroy(),c=new Ta.STSClient({region:n.region,credentials:p}),h=moe(await c.send(new Ta.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&h&&!hoe(h,r.identity)&&N(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:NS.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 Rr)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=zN;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var b4;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(b4="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 voe=Symbol(),ETe=Symbol(),ITe=Symbol(),T4=Symbol();var oA=Symbol();var kTe=new TextEncoder,$Te=new TextDecoder;function _4(t){return typeof t=="string"?kTe.encode(t):$Te.decode(t)}var x4;Uint8Array.prototype.toBase64?x4=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):x4=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 S4;Uint8Array.fromBase64?S4=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw sr("The input to be decoded is not correctly encoded.",Vs,e)}}:S4=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 E4(t){return typeof t=="string"?S4(t):x4(t)}var Qf=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=iPe,Error.captureStackTrace?.(this,this.constructor)}},qv=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 qv(t,{code:e,cause:r})}function iA(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function woe(t){lA(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(b4&&!e.has("user-agent")&&e.set("user-agent",b4),e.has("authorization"))throw sr('"options.headers" must not include the "authorization" header name',Vs);return e}function ATe(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 boe(t){PTe(t,"application/json")}function TTe(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,aPe,t)}function PTe(t,e){if(HTe(t)!==e)throw TTe(t,e)}async function _oe(t){return nn(t,"codeVerifier"),E4(await crypto.subtle.digest("SHA-256",_4(t)))}function xoe(t){let e=t?.[ETe];return typeof e=="number"&&Number.isFinite(e)?e:0}function Soe(t){let e=t?.[ITe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Eoe(){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 goe(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 Ioe(t){return nn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function koe(t){return nn(t,'"clientSecret"'),(e,r,o,n)=>{let i=goe(r.client_id),s=goe(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function $oe(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var RTe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function CTe(t,e){if(e&&t.protocol!=="https:")throw ke("only requests to HTTPS are allowed",uPe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw ke("only HTTP and HTTPS requests are allowed",lPe,t)}function yoe(t,e,r,o){let n;if(typeof t!="string"||!(n=RTe(t)))throw ke(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?dPe:pPe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return CTe(n,o),n}function Aoe(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?yoe(t.mtls_endpoint_aliases[e],e,r,o):yoe(t[e],e,r,o)}var I4=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=oPe,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)}},Hv=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=sPe,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)}},k4=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=nPe,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!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",OTe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",NTe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',DTe="("+aA+")\\s*=\\s*"+NTe,zTe="("+aA+")\\s*=\\s*("+aA+")",jTe=new RegExp("^[,\\s]*("+aA+")"),MTe=new RegExp("^[,\\s]*"+DTe+"[,\\s]*(.*)"),UTe=new RegExp("^[,\\s]*"+zTe+"[,\\s]*(.*)"),LTe=new RegExp("^("+OTe+")(?:$|[,\\s])(.*)");function FTe(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(jTe),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(MTe)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(UTe)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(LTe)){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 VTe(t){if(t.status>399&&t.status<500){Boe(t),boe(t);try{let e=await t.clone().json();if(iA(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Toe(t,e,r){if(t.status!==e){KTe(t);let o;throw(o=await VTe(t))?(await t.body?.cancel(),new I4("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)`,cPe,t)}}function qTe(t){if(!R4.has(t))throw sr('"options.DPoP" is not a valid DPoPHandle',Vs)}function HTe(t){return t.headers.get("content-type")?.split(";")[0]}async function Poe(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?.[T4]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:ATe(o,s?.signal)})}async function P4(t,e,r,o,n,i){let s=Aoe(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[voe]!==!0);n.set("grant_type",o);let a=woe(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(qTe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await Poe(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Roe(t,e,r,o,n){tm(t),rm(e),nn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),P4(t,e,r,"refresh_token",i,n)}var Coe=new WeakMap,BTe=new WeakMap;function Ooe(t){if(!t.id_token)return;let e=Coe.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 Toe(r,200,"Token Endpoint"),Boe(r);let s=await yPe(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 YTe(t,e,s.id_token,a,n);ePe(e,c),QTe(c),BTe.set(r,u),Coe.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 KTe(t){let e;if(e=FTe(t))throw new k4("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function Noe(t,e,r,o){return dA(t,e,r,void 0,o?.[oA],o?.recognizedTokenTypes)}function ZTe(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 WTe(t,e){let r=t[vPe]?.(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 R4=new WeakSet;function JTe(t){return R4.add(t),t}var C4=Symbol();async function Doe(t,e,r,o,n,i,s){if(tm(t),rm(e),!R4.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!==C4&&(nn(i,'"codeVerifier"'),c.set("code_verifier",i)),P4(t,e,r,"authorization_code",c,s)}var zoe={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 GTe(t,e){for(let r of t)if(e.claims[r]===void 0)throw ke(`JWT "${r}" (${zoe[r]}) claim missing`,mt,{claims:e.claims});return e}function XTe(t,e){if(typeof e.claims[t]!="string")throw ke(`unexpected JWT "${t}" (${zoe[t]}) claim type`,mt,{claims:e.claims});return e}function YTe(t,e,r,o,n){return fPe(r,mPe.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),xoe(e),Soe(e),n).then(GTe.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(WTe.bind(void 0,t)).then(ZTe.bind(void 0,e.client_id)).then(XTe.bind(void 0,"sub"))}function joe(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 QTe(t){t.auth_time!==void 0&&sA(t.auth_time,!0,'ID Token "auth_time" (authentication time)',mt,{claims:t})}function Moe(t,e,r){if(r===uA)return;let o=Eoe()+xoe(t),n=Soe(t);if(e.auth_time+r<o-n)throw ke("too much time has elapsed since the last End-User authentication",A4,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Uoe(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 ePe(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 Loe(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?tPe(t,e,r,o.expectedNonce,o.maxAge,o[oA],o.recognizedTokenTypes):rPe(t,e,r,o?.maxAge,o?.[oA],o?.recognizedTokenTypes)}async function tPe(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=joe(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=Ooe(c);return Moe(e,u,n),Uoe(u,o),c}async function rPe(t,e,r,o,n,i){let s=await dA(t,e,r,void 0,n,i),a=Ooe(s);return a&&(Moe(e,a,joe(e,o)),Uoe(a,cA)),s}var nPe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",oPe="OAUTH_RESPONSE_BODY_ERROR",iPe="OAUTH_UNSUPPORTED_OPERATION",sPe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var $4="OAUTH_PARSE_ERROR",mt="OAUTH_INVALID_RESPONSE";var aPe="OAUTH_RESPONSE_IS_NOT_JSON",cPe="OAUTH_RESPONSE_IS_NOT_CONFORM",uPe="OAUTH_HTTP_REQUEST_FORBIDDEN",lPe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",A4="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",em="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var dPe="OAUTH_MISSING_SERVER_METADATA",pPe="OAUTH_INVALID_SERVER_METADATA";async function Foe(t,e,r,o,n){return tm(t),rm(e),P4(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Voe(t,e,r,o){return dA(t,e,r,void 0,o?.[oA],o?.recognizedTokenTypes)}async function qoe(t,e,r,o,n){tm(t),rm(e),nn(o,'"token"');let i=Aoe(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[voe]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=woe(n?.headers);return a.delete("accept"),Poe(t,e,r,i,s,a,n)}async function Hoe(t){if(!lA(t,Response))throw sr('"response" must be an instance of Response',Pa);await Toe(t,200,"Revocation Endpoint")}function Boe(t){if(t.bodyUsed)throw sr('"response" body has been used already',Vs)}async function fPe(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(_4(E4(i)))}catch(d){throw ke("failed to parse JWT Header body as base64url encoded JSON",$4,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(_4(E4(s)))}catch(d){throw ke("failed to parse JWT Payload body as base64url encoded JSON",$4,d)}if(!iA(u))throw ke("JWT Payload must be a top level object",mt,t);let l=Eoe()+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',A4,{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',A4,{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 mPe(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 hPe=Symbol(),gPe=Symbol();function Koe(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 gPe:if(i!==void 0)throw ke('unexpected "state" response parameter encountered',mt,{expected:void 0,parameters:r});break;case hPe: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 Hv("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 JTe(new URLSearchParams(r))}async function yPe(t,e=boe){let r;try{r=await t.json()}catch(o){throw e(t),ke('failed to parse "response" body as JSON',$4,o)}if(!iA(r))throw ke('"response" body must be a top level object',mt,{body:r});return r}var vPe=Symbol();function bPe(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 bPe(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 O4(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Zoe=Object.assign(Object.create(null),{dpop:()=>N(502,"invalid_response","The service returned an unsupported token.")}),_Pe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Zoe,{"user access token":()=>{}})},xPe={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"},SPe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+O4(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},EPe={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:Zoe,...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"?_Pe:t.adapter==="openrouter"?xPe:t.adapter==="vultr"?EPe:{},...t.revoke?.style==="github"?SPe:{}}}function Ca(t,e){try{return Mn(new nZ(t).expand(e)).href}catch{N(400,"invalid_service_url","Check the service URL and its required fields.")}}var Woe=(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 _oe(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&&Mn(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?$oe():(e.clientSecret||N(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?koe(e.clientSecret):Ioe(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[T4]: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 fi({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?Noe:e.grantType==="client_credentials"?Voe:Loe)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:qs(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof Rr)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?Woe(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,fi(f))}else{let{server:f,client:p}=this.configuration(e,r),h;try{let g=Koe(f,p,o.parameters,o.state);h=await Doe(f,p,this.authentication(r,e.clientAuth),g,l.redirectUri?.(r,i)??i,e.pkce?n:C4,{...this.options(e),additionalParameters:e.tokenParams})}catch(g){throw(g instanceof qv||g instanceof Hv)&&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 Foe(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 Roe(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 qoe({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Hoe(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 "+O4(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 N4(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function D4(t){return t||N(409,"app_required","Choose an OAuth application."),t}function IPe(t){return{token:QN.parse(t.token),response:pt.parse(t.response)}}var mA=class{constructor(e){this.transport=e}transport;facts=NN;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=N4(r),n=D4(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??pi(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return Pr.parse({...e.material,oauth:a})}async recover(e,r,o){let i=IPe(o).token;return Pr.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(N4(e),D4(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(N4(e),D4(r),e.oauth)}};function kPe(t){if(t.method.kind!=="token"&&t.method.kind!=="approval")throw new Error("Use an input credential provider.");return t.method.config}var Bv=class{facts=_p;needsRenewal(){return!1}async outputs(e){let r=kPe(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=DN;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 $Pe}from"node:fs/promises";var APe=m.object({accessToken:m.string().min(1).max(16384).regex(/^\S+$/),expiresAt:m.number().int().positive()}).strict();async function TPe(t,e){if(t==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,i=n?await $Pe(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 Joe(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=TPe){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(Joe(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=fi(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=APe.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=Joe(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 Goe(t,e){let r={oauth:new mA(t),token:new Bv,aws:new nA(e),approval:new Bv,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 Xoe(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!TB(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=Goe(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(Pr.parse(JSON.parse(nm(a)))):o,i=Pr.safeParse(JSON.parse(nm(await Ag(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,ye.clientCredential,n),s=vn.parse(JSON.parse(nm(await Ag(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(jn(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=eD.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,ye.tokenSet,o),r);(n.action==="refresh"||Vt(i.method).revocable)&&await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=eD.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,ye.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=>iD(i,o,r.origin));return iD(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 bZ(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 YB(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=PPe(),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 Rr&&["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 RPe}from"node:dns/promises";import{request as CPe}from"node:https";import{brotliDecompressSync as OPe,gunzipSync as NPe,inflateSync as DPe}from"node:zlib";var om=class{constructor(e){this.origin=e}origin;async send(e){let r=Mn(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 RPe(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=CPe(r,d,p=>{let h=[],g=0;p.on("data",y=>{g+=y.length,g>n?p.destroy(new Rr(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"?NPe:w==="deflate"?DPe:w==="br"?OPe:null;if(!_)throw new Rr(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 Rr)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 In(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=z4(zPe(la()),"custody",r.id),i=new Mg(z4(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 Mg(z4(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 Yoe(t,e){let{custody:r,keys:o,binding:n,connections:i}=In(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===ye.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Xoe(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ye.value)return Ag(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 jPe}from"node:child_process";import{fileURLToPath as MPe}from"node:url";function Qoe(t,e){return new Promise((r,o)=>{let n=jPe(process.execPath,[MPe(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&&!r.replaced?r.content:void 0,i=n?.policy??await t.policy(e,ye.tokenSet,[],r?{replacing:r.content.policy}:{});if(!o)return i;let s=await Promise.all([...new Set(o)].map(async a=>{let{binding:c}=await t.inspectIdentity(a);return await t.trusted(c),c}));return i=$r.parse({...i,revision:i.revision+(n?1:0),grants:[...i.grants.filter(a=>!("actor"in a)),...s.map(a=>({actor:a,executor:a,operations:[...lc(ye.tokenSet)],origins:[],functionDigests:[],callerProgram:!0,expiresAt:new Date(Date.now()+30*864e5).toISOString()}))]}),i}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 eie(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 Pr.parse({...r,aws:ia.parse(t.aws)});if(t.method.kind==="oauth")return Pr.parse({...r,requestedScopes:t.scopes,fields:jn(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 Pr.parse({...r,fields:I0(o,i,n)})}var _A=m.object({consumerKey:m.string().min(1).max(16384),validationUrl:m.url()});async function tie(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:Mn(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(fi(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:bB(pi(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(fi(a)),u=Mn(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 rie(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:jn(Vt(t.method).fields,t.app.fields),requestedScopes:t.scopes};if(t.method.kind==="ovh")return Pr.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 Pr.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 nie(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=fi(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 oie(t){let e=await nie(t,`mutation createFlashAuthRequest {
|
|
131
|
+
`,!!r)}async function uK(t){if(process.platform==="win32")return;let e=await TN(t,"r");try{await e.sync()}finally{await e.close()}}async function fc(t,e,r){let o=Khe(t),n=Bhe(o);if(await Vhe(n,{recursive:!0,mode:448}),!r){let s=await TN(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await uK(n);return}let i=PN(n,".foundation-"+Whe());try{let s=await TN(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await qhe(i,o),await uK(n)}finally{await Hhe(i,{force:!0})}}import{spawn as Jhe}from"node:child_process";import{chmod as Ghe,mkdtemp as Xhe,rm as Yhe,writeFile as Qhe}from"node:fs/promises";import{tmpdir as ege}from"node:os";import{join as gK}from"node:path";import{StringDecoder as tge}from"node:string_decoder";function hK(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 rge(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 tge("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 yK(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await Xhe(gK(ege(),"foundation-"));await Ghe(r,448);try{let o=hK(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=gK(r,i);await Qhe(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=Jhe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=rge(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 Yhe(r,{recursive:!0,force:!0})}}import{dirname as zPe,join as z4}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 pi(t,e){return[...new Set([...t.required??[],...e??t.default])]}function mc(t){return Vt(t).requiresApp}function vK(t){return t.kind==="approval"?"unavailable":!Vt(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth"?"available":t.config.browserTokenExchange??"unknown"}var nge=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),wK=pt.refine(t=>Object.keys(t).every(e=>!nge.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:wK,details:wK}).strict();function NN(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 DN(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 zN(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:yB(t.aws)},details:{aws:vB(t.aws)}})}var oge={oauth:NN,token:_p,aws:zN,ovh:DN,approval:_p};function Tg(t){return oge[t.method.kind](t)}var iZ=$t(FK(),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"}},Tge=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"}},Pge=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"}},Rge=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"}},Cge=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"}},Oge=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"}},Nge=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"}},Dge=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"}},BN=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"}},zge=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"}},jge=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"}},VK=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"}},Mge=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"}},Uge=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},Lge=class extends Uge{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"}},Fge=["","+",".","/",";","?","&","#"],JK={"":{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}},Vge=new TextEncoder,qK="0123456789ABCDEF",HK=t=>vc(Gr(48,57),Gr(65,70),Gr(97,102))(t.charCodeAt(0)),Og=(t,e)=>t[e]==="%"&&e+2<t.length&&HK(t[e+1])&&HK(t[e+2]);function KN(t,e){let r=t[e];return r==null?0:vc(GK,XK,cl("_"))(r)?1:Og(t,e)?3:0}function qge(t,e){if(Og(t,e))return 3;let{char:r,size:o}=Ng(t,e);return Bge(r)?o:0}function Ng(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 GN=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Og(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Ng(e,o);r+=vc(YK,s=>t&&Hge(s))(n)?n:QK(n),o+=i}return r};function Ep(t){let e="";for(let r=0;r<t.length;){if(Og(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Ng(t,r);e+=YK(o)?o:QK(o),r+=n}return e}function Rg(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Og(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Ng(t,n);r+=i,n+=s}return r}var GK=t=>vc(Gr(65,90),Gr(97,122))(t.charCodeAt(0)),XK=t=>Gr(48,57)(t.charCodeAt(0)),YK=t=>vc(GK,XK,e=>"-._~".includes(e))(t),Hge=t=>":/?#[]@!$&'()*+,;=".includes(t),Bge=t=>Kge(t.codePointAt(0)),Kge=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),Zge,Wge)(t);function Zge(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 Wge=t=>vc(Gr(57344,63743),Gr(983040,1048573),Gr(1048576,1114109))(t),QK=t=>Array.from(Vge.encode(t)).map(e=>`%${qK[e>>4]}${qK[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 eZ(t,e,r){return t.map(o=>o.kind==="literal"?o.text:Jge(o.vars,o.operator,e,r)).join("")}function Jge(t,e,r,o){let n=JK[e],i=t.flatMap(s=>Gge(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function Gge(t,e,r,o){if(e==null)return[];if(oye(e)){let n=eye(e,r.allowReserved);return n.length<1?[]:BK(t,"list",o)?Yge(t,n,r):[]}if(nye(e)){let n=tye(e,r.allowReserved);return n.length<1?[]:BK(t,"associative",o)?Qge(t,n,r):[]}return Xge(t,e,r)}function Xge(t,e,r){let o=String(e),n=t.prefix==null?o:Rg(o,t.prefix),i=GN(r.allowReserved)(n);return r.named?[Cg(Ep(t.name),i,r)]:[i]}function Yge(t,e,r){let o=Ep(t.name);if(t.explode)return r.named?e.map(i=>Cg(o,i,r)):[...e];let n=e.join(",");return r.named?[Cg(o,n,r)]:[n]}function Qge(t,e,r){if(t.explode)return e.map(([n,i])=>Cg(n,i,r));let o=e.flat(1).join(",");return r.named?[Cg(Ep(t.name),o,r)]:[o]}var Cg=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,eye=(t,e)=>t.filter(r=>r!=null).map(String).map(GN(e)),tye=(t,e)=>Object.entries(t).map(([r,o])=>[r,rye(o)]).filter(([,r])=>r!=null).map(r=>r.map(GN(e)));function rye(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 nye=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),oye=t=>Array.isArray(t);function BK(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new Lge(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function iye(t,e,r){return ZN(t,e,r,0,0,{})}function ZN(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=Cye(i);return eZ(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?ZN(t,e,r,o+1,n+s.text.length,i):null;for(let a of sye(t,e,o,n)){let c=e.slice(n,a);for(let u of cye(s.vars,s.operator,c)){let l=XN(i,u);if(l==null)continue;let d=ZN(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*sye(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*aye(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*aye(t,e){for(let r=t;r>=e;r--)yield r}function*cye(t,e,r){if(r===""){yield*uye(t,e);return}let o=JK[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?vye(t,o,n):lye(t,o,n)}var uye=(t,e)=>(e===""||e==="+")&&t.length===1?[yc(t[0],"")]:[{}],lye=(t,e,r)=>WN(t,e,YN(r,e.sep),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 dye(i,e,r,n))for(let a of WN(t,e,r,o+1,s.index)){let c=XN(s.bindings,a);c!=null&&(yield c)}yield*WN(t,e,r,o+1,n)}function*dye(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 pye(t,e,s))yield{bindings:a,index:o+i}}}function*pye(t,e,r){let o=tZ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*fye(t,e,r)),yield*o}function*fye(t,e,r){let o=rZ(r,e.allowReserved);if(o==null)return;let n=mye(r,e);n!=null&&(yield yc(t,n)),yield yc(t,o)}var mye=(t,e)=>hye(t.join(e.sep),e);function hye(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=gye(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 gye(t,e,r){for(let o=e;o<t.length;o++)if(yye(t,o,r))return o;return t.length}var yye=(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*tZ(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=YN(r,",");if(i.length<2){yield n;return}let s=rZ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?$ye(i,e.allowReserved):null;a!=null&&(yield yc(t,a)),yield yc(t,s),yield n}var vye=(t,e,r)=>JN(t,e,YN(r,e.sep).map(kye),0,0);function*JN(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of wye(i,e,r,n,t))for(let a of JN(t,e,r,o+1,s.index)){let c=XN(s.bindings,a);c!=null&&(yield c)}yield*JN(t,e,r,o+1,n)}function*wye(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*_ye(t,e,r,o,n);return}yield*bye(t,e,r,o)}}function*bye(t,e,r,o){let n=r[o];if(n.name===Ep(t.name))for(let i of tZ(t,e,n.value))yield{bindings:i,index:o+1}}function*_ye(t,e,r,o,n){yield*xye(t,e,r,o),yield*Eye(t,e,r,o,n)}function*xye(t,e,r,o){let n=[...Sye(Ep(t.name),e,r,o)];n.length>0&&(yield{bindings:yc(t,n),index:o+n.length})}function*Sye(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*Eye(t,e,r,o,n){let i=[...Iye(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*Iye(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 kye(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function $ye(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 rZ(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 XN(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=Aye(i,n);if(s==null)return null;r[o]=s}return r}var Aye=(t,e)=>S0(t)||S0(e)?Tye(t,e):Pye(t.value,e.value)?t:null;function Tye(t,e){let r=KK(t.value),o=KK(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 Rg(o,t.prefix)===r?e:null;if(!n&&i)return Rg(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Rg(o,s)===r?e:null:Rg(r,a)===o?t:null}var S0=t=>t.prefix!=null,KK=t=>typeof t=="string"?t:null;function Pye(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):ZK(t)?ZK(e)&&Rye(Object.entries(t),Object.entries(e)):t===e}var Rye=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),ZK=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Cye=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),YN=(t,e)=>e===""?[t]:t.split(e),Oye=["=",",","!","@","|"];function Nye(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new Oge(e,r));let n=t[0];if(Mye(n))return o(new Nge(e,r+1,n));if(!WK(n)&&KN(t,0)<1)return o(new Dge(e,r+1,n));let i=WK(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:Dye(t,e,r+1,s)}}function Dye(t,e,r,o){if(o>=t.length)throw new BN(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new VK(e,r+i):new BN(e,r+i);let s=i,a=zye(t,i);if(a===s)throw new BN(e,r+i);let c=t.slice(s,a);i=a;let u=jye(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new Mge(e,r+i,t[i]):new zge(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 VK(e,r+i-1)}return n}function zye(t,e){let r=e,o=!0;for(;r<t.length;){let n=KN(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||KN(t,r+1)<1)break;r++,o=!0}return r}function jye(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&&Uye(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new jge(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function WK(t){return Fge.includes(t)&&t!==""}function Mye(t){return Oye.includes(t)}function Uye(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function Lye(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 Tge(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new Rge(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(Nye(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 Pge(t,i)),n(s),i++;continue}let a=qge(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Ng(t,i);r(new Cge(t,i,c)),n(c),i+=u}return o}var nZ=class oZ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=Bye(r),this.#e=Fye(Lye(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new oZ(e,r)}get tokens(){return this.#e}expand=e=>eZ(this.#e,e,this.#t);match=e=>iye(this.#e,e,this.#t);toString=()=>this.uriTemplate},Fye=t=>Object.freeze(t.map(Vye)),Vye=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(qye))}),qye=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),Hye=()=>{},Bye=({strict:t,report:e})=>(e??=Hye,t??=!0,e=t?Kye(e):e,{strict:t,report:e}),Kye=t=>e=>{throw t(e),e};var ha=class extends Error{constructor(r,o){super(o);this.code=r}code};function Zye(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(!Zye(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,iZ.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 jn(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 sZ(t,e=Tg(t)){return e.accountVerified?e.accountId:null}function aZ(t,e=Tg(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"?jn(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(),QN=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(),Dg={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(),Pr=m.union([m.object({...Dg,method:FS,oauth:QN.optional(),requestedScopes:m.array(m.string()).optional(),implicitApp:vn.optional(),fields:wc.optional(),aws:ga}).strict(),m.object({...Dg,method:VS,fields:wc,facts:hc.optional(),oauth:ga,aws:ga}).strict(),m.object({...Dg,method:BS,fields:wc,oauth:ga,aws:ga}).strict(),m.object({...Dg,method:HS,fields:wc,ovh:hg.optional(),requestedScopes:m.array(m.string()).optional(),oauth:ga,aws:ga}).strict(),m.object({...Dg,method:qS,aws:NS,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."})}),hHe=m.object({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),generation:x,fields:wc.optional()}).strict(),Wye=m.object({methodId:m.string().min(1).max(200),methodKind:dN,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:DS.optional(),ovh:hg.optional()}).strict();async function kp(t,e=Tg(t)){let{outputs:r,revocable:o}=Vt(t.method),n=t.method.kind!=="aws"&&t.fields?jn(t.method.config.fields,t.fields):{},i=await oe(aZ(t,e));return Wye.parse({methodId:t.methodId,methodKind:t.method.kind,...t.method.http?{http:t.method.http}:{},generation:t.generation,authorizationDigest:i,appId:t.appId,accountId:sZ(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 Jye=m.array(m.object({name:m.string(),label:m.string(),value:m.string()}).strict()),cZ=m.object({methodName:ne,account:m.string().max(2e3),settings:Jye.optional()}).strict();function $0(t){let e=Vt(t.method).fields,r=t.method.kind!=="aws"&&t.fields?jn(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 eD=m.discriminatedUnion("action",[m.object({action:m.literal("refresh"),id:x}).strict(),m.object({action:m.literal("revoke"),id:x}).strict()]);var tD=ca.extend({name:ne}),EHe=ca.extend({previousSignature:zt.optional()}).strict(),uZ=m.object({name:ne,content:Ar,labels:cZ.optional(),version:m.number().int().positive().optional()}).strict(),zg=m.object({content:Ar,version:m.number().int().positive()}).strict(),lZ=m.object({id:x,reason:m.enum(["grantExpired","recipients"]),remove:m.array(x).max(1e3).default([])}).strict(),IHe=m.record(x,m.object({version:m.number().int().positive(),content:Ar}).strict()),dZ=m.object({id:x,name:ne,version:m.number().int().positive(),content:Ar,policy:$r}).strict(),pZ=m.object({registration:IN,stoppedAt:m.iso.datetime().nullable(),heartbeatAt:m.iso.datetime().nullable()}).strict(),fZ=m.object({lease:x,request:$g,sources:m.array(Ar).max(100)}).strict().nullable(),Gye=m.object({lease:x}).strict(),kHe=Gye.extend({receipt:d0}).strict(),jg=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:Ar.nullable()}),$He=m.object({id:x,resourceId:x,expectedRevision:m.number().int().positive()}).strict(),Xye=m.object({fence:m.string().regex(/^\d+$/)}).strict(),AHe=Xye.extend({content:Ar}).strict(),THe=m.object({id:x,executionId:x,index:m.number().int().nonnegative(),stateDigest:Dt,expiresAt:ge}).strict(),rD=m.object({id:x,executionId:x,context:m.string(),sealed:eo.nullable(),expiresAt:ge,receivedAt:ge.nullable()}).strict(),mZ=(t,e)=>"oauth-callback:"+t+":"+e;var Yye=m.object({binding:bt,verifiedAt:ge}).strict(),nD=m.object({origin:m.url(),ownerId:x,signerId:x,revision:m.number().int().positive(),keys:m.array(Yye).max(1e3)}).strict(),Qye=m.object({version:m.number().int().positive(),signature:zt}).strict(),oD=m.object({keyring:Qye.nullable()}).strict(),DHe=m.object({version:m.number().int().positive().nullable(),signature:zt}).strict();function hZ(t,e){return Jt(nD.parse(t),e,"keyring")}function gZ(t){return nD.parse(JSON.parse(gn(GS(t.split(".")[1]??""))))}async function yZ(t,e){let r=nD.parse(await Sg(t,e.signing,"keyring"));if(r.signerId!==e.id)throw new Error("Another identity signed this keyring.");return r}var $p=$t(wZ(),1);var Rr=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 Rr(t,e,r,o)}var eve=$p.default.IPv6.parseCIDR("2000::/3"),tve=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 tve.has(e.range())&&(!(e instanceof $p.default.IPv6)||e.match(eve))}function Mn(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 fi(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=Mn(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 iD(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.method.kind==="token"?t.method.config.constants?.[o]:void 0)??t.fields?.[o]);o&&!n&&N(409,"reconnect_required","Reconnect with a destination URL.");let i=Mn(e.url??n??"",r);return n&&i.origin!==Mn(n,r).origin&&N(400,"invalid_destination","Use this connection only at its configured destination host."),i.href}function bZ(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 wn=class extends Error{constructor(r,o){super(o);this.code=r}code},aD=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},sD=(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 e.principalId!==this.binding.principalId&&await this.known(e.principalId)?new wn("identity_changed","Identity "+e.principalId+" replaced the keys verified before. Verify its current keys."):new wn("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.known(e.principalId);return!!r&&P(r)===P(e)}async known(e){return(await this.keyring()).get(e)?.binding??await this.trust.binding(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(sD(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 wn)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,{},oD),o=await this.trust.keyring(),n=()=>new wn("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=gZ(r.signature);if(i.signerId!==this.binding.id)return{version:r.version,revision:i.revision,keyring:null};let s=await yZ(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 hZ(n,this.keys.signing)}},oD)}catch(i){if(r<3&&sD(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 wn("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(!sD(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",{},pZ);if(await kN(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(tD));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-delegates",{},lr(tD)),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 wn&&["identity_untrusted","identity_changed"].includes(a.code)))throw a}}return[...r.map(i=>i.binding),...n]}async read(e){let r=await this.latest(e);if(r.replaced)throw new wn("key_replaced","This item is sealed only for keys this identity has since replaced. Enter its value again.");return r}async latest(e){let r=await this.api.json("/api/custody/"+x.parse(e),{},zg);return this.replaces(r.content.policy)?{...r,replaced:!0}:(await this.observe(r.content,e),{...r,replaced:!1})}replaces(e){return!e.readers.some(r=>P(r)===P(this.binding))&&e.readers.some(r=>r.principalId===this.binding.principalId)}async observe(e,r=e.policy.id){let o=await di(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=xN(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&$r.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 wn("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!o0(i.policy,o)&&!i.policy.authorities.some(s=>s.principalId===n.principalId&&s.id!==n.id))throw new wn("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(dZ))).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 wn("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!==ye.clientCredential,expiresAt:s});return $r.parse({format:2,id:n.id??n.previous?.id??n.replacing?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??n.replacing?.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&&!this.replaces(i.content.policy)?i.content:void 0),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(lZ))).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=new Map(c.map(k=>[k.principalId,k])),l=[...i.readers,...i.authorities,...i.grants.flatMap(k=>"actor"in k?[k.actor,k.executor]:[k.executor])];if(r==="recipients")for(let k of new Set(l.map(U=>U.principalId))){if(k===this.binding.principalId||u.has(k)||a.has(k))continue;let U=await this.inspectIdentity(k).then(Z=>Z.binding,()=>null);U&&l.some(Z=>Z.principalId===k&&Z.id!==U.id)&&u.set(k,await this.trusted(U))}let d=k=>u.get(k.principalId)??k,f=k=>[...new Map(k.map(U=>[U.id,U])).values()],p=k=>!a.has(k.principalId),h=i.grants.filter(k=>nl(k,s)&&p(k.executor)&&(!("actor"in k)||p(k.actor))).map(k=>"actor"in k?{...k,actor:d(k.actor),executor:d(k.executor)}:{...k,executor:d(k.executor)}),g=f(i.readers.filter(p).map(d)),y=f(i.authorities.filter(p).map(d)),w=c.filter(k=>!g.some(U=>U.id===k.id)),b={...i,revision:i.revision+1,grants:h,producers:[],readers:[...g,...w],authorities:[...y,...w.filter(k=>!y.some(U=>U.id===k.id))],...i.observers?{observers:i.observers.filter(k=>!a.has(k))}:{}},_=i.contentType!==ye.executionResult&&i.producers.some(k=>Date.parse(k.expiresAt)>s);if(P({...b,revision:i.revision})===P(i)||_)return null;let I=await il(n.content,this.binding,this.keys.encryption);if(i.contentType===ye.executionResult){let k=await ol(I,b,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:k,version:n.version}},zg),await this.trust.rememberContent(k),e}let A=await this.api.json("/api/resources/"+i.id,{},Ut);return this.save(A.name,I,b,{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===ye.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 d=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),f=await this.api.json("/api/principals/"+e+"/resources?"+d,{},lr(Ut));s=f.items.find(p=>p.name===r),a=f.next}while(!s&&a);let c=s?await this.latest(s.id):void 0,u=c?.content,l=u&&!c.replaced?{...u.policy,revision:u.policy.revision+1,producers:[]}:await this.policy(e,ye.value,[],{replacing:u?.policy});return l.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(u?.materialRevision??0)+1}],{name:r,approval:await a0(l,this.binding,this.keys,c?.replaced?void 0:u)}}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!==tK)throw new wn("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===ye.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 k=await this.read(w.policy.id),U=await this.api.json("/api/resources/"+w.policy.id,{},Ut),Z={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([_,...w.policy.contentType===ye.tokenSet?[ie.refresh]:[]])],origins:I?[I]:[],functionDigests:[],callerProgram:!b,expiresAt:c},be=re=>P({...re,expiresAt:null}),xe=k.content.policy.grants.filter(re=>be(re)===be(Z)),Xe=$r.parse({...k.content.policy,revision:k.content.policy.revision+1,grants:[...k.content.policy.grants.filter(re=>nl(re)&&be(re)!==be(Z)),{...Z,expiresAt:new Date(Math.max(Date.parse(c),...xe.map(re=>n0(re)))).toISOString()}]});await this.save(U.name,await il(k.content,this.binding,this.keys.encryption),Xe,{previous:k,metadata:k.content.metadata}),f[y]=(await this.read(w.policy.id)).content}let p=await this.policy(e,ye.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===ye.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 rK(s,h);let g=y=>y.policy.contentType===ye.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 eK(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 aD(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 Sg(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 wn("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?cK(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 wn("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,ye.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await aK(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 rve,mkdir as _Z,readFile as nve,readdir as xZ,rm as ove}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}$/),Mg=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 rve(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 nve(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 _Z(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 _Z(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 ove(Ap(this.directory,"pending",e),{force:!0})}async pending(e){await this.index();let r;try{r=await xZ(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 xZ(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 Rr(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},fZ)}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}},jg),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},jg),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},Ar),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}},jg),state:r=>e.json("/api/connections/"+r+"/operation",{},jg.nullable())}}};import{randomUUID as PPe}from"node:crypto";var Ta=$t(foe(),1);import{randomUUID as STe}from"node:crypto";function moe(t){let e=OS.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 hoe(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&pp(t.arn)===pp(e.arn)}function w4(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)}:{}};w4(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();w4(d.expiration),c=new Ta.STSClient({region:n.region,credentials:d});let f=r?.sourceIdentity?moe(await c.send(new Ta.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&f&&!hoe(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-"+STe().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},w4(p.expiration),r?.identity&&(c.destroy(),c=new Ta.STSClient({region:n.region,credentials:p}),h=moe(await c.send(new Ta.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&h&&!hoe(h,r.identity)&&N(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:NS.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 Rr)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=zN;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var b4;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(b4="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 voe=Symbol(),ETe=Symbol(),ITe=Symbol(),T4=Symbol();var oA=Symbol();var kTe=new TextEncoder,$Te=new TextDecoder;function _4(t){return typeof t=="string"?kTe.encode(t):$Te.decode(t)}var x4;Uint8Array.prototype.toBase64?x4=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):x4=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 S4;Uint8Array.fromBase64?S4=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw sr("The input to be decoded is not correctly encoded.",Vs,e)}}:S4=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 E4(t){return typeof t=="string"?S4(t):x4(t)}var Qf=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=iPe,Error.captureStackTrace?.(this,this.constructor)}},qv=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 qv(t,{code:e,cause:r})}function iA(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function woe(t){lA(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(b4&&!e.has("user-agent")&&e.set("user-agent",b4),e.has("authorization"))throw sr('"options.headers" must not include the "authorization" header name',Vs);return e}function ATe(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 boe(t){PTe(t,"application/json")}function TTe(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,aPe,t)}function PTe(t,e){if(HTe(t)!==e)throw TTe(t,e)}async function _oe(t){return nn(t,"codeVerifier"),E4(await crypto.subtle.digest("SHA-256",_4(t)))}function xoe(t){let e=t?.[ETe];return typeof e=="number"&&Number.isFinite(e)?e:0}function Soe(t){let e=t?.[ITe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Eoe(){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 goe(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 Ioe(t){return nn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function koe(t){return nn(t,'"clientSecret"'),(e,r,o,n)=>{let i=goe(r.client_id),s=goe(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function $oe(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var RTe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function CTe(t,e){if(e&&t.protocol!=="https:")throw ke("only requests to HTTPS are allowed",uPe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw ke("only HTTP and HTTPS requests are allowed",lPe,t)}function yoe(t,e,r,o){let n;if(typeof t!="string"||!(n=RTe(t)))throw ke(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?dPe:pPe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return CTe(n,o),n}function Aoe(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?yoe(t.mtls_endpoint_aliases[e],e,r,o):yoe(t[e],e,r,o)}var I4=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=oPe,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)}},Hv=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=sPe,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)}},k4=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=nPe,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!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",OTe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",NTe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',DTe="("+aA+")\\s*=\\s*"+NTe,zTe="("+aA+")\\s*=\\s*("+aA+")",jTe=new RegExp("^[,\\s]*("+aA+")"),MTe=new RegExp("^[,\\s]*"+DTe+"[,\\s]*(.*)"),UTe=new RegExp("^[,\\s]*"+zTe+"[,\\s]*(.*)"),LTe=new RegExp("^("+OTe+")(?:$|[,\\s])(.*)");function FTe(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(jTe),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(MTe)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(UTe)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(LTe)){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 VTe(t){if(t.status>399&&t.status<500){Boe(t),boe(t);try{let e=await t.clone().json();if(iA(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Toe(t,e,r){if(t.status!==e){KTe(t);let o;throw(o=await VTe(t))?(await t.body?.cancel(),new I4("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)`,cPe,t)}}function qTe(t){if(!R4.has(t))throw sr('"options.DPoP" is not a valid DPoPHandle',Vs)}function HTe(t){return t.headers.get("content-type")?.split(";")[0]}async function Poe(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?.[T4]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:ATe(o,s?.signal)})}async function P4(t,e,r,o,n,i){let s=Aoe(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[voe]!==!0);n.set("grant_type",o);let a=woe(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(qTe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await Poe(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Roe(t,e,r,o,n){tm(t),rm(e),nn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),P4(t,e,r,"refresh_token",i,n)}var Coe=new WeakMap,BTe=new WeakMap;function Ooe(t){if(!t.id_token)return;let e=Coe.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 Toe(r,200,"Token Endpoint"),Boe(r);let s=await yPe(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 YTe(t,e,s.id_token,a,n);ePe(e,c),QTe(c),BTe.set(r,u),Coe.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 KTe(t){let e;if(e=FTe(t))throw new k4("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function Noe(t,e,r,o){return dA(t,e,r,void 0,o?.[oA],o?.recognizedTokenTypes)}function ZTe(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 WTe(t,e){let r=t[vPe]?.(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 R4=new WeakSet;function JTe(t){return R4.add(t),t}var C4=Symbol();async function Doe(t,e,r,o,n,i,s){if(tm(t),rm(e),!R4.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!==C4&&(nn(i,'"codeVerifier"'),c.set("code_verifier",i)),P4(t,e,r,"authorization_code",c,s)}var zoe={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 GTe(t,e){for(let r of t)if(e.claims[r]===void 0)throw ke(`JWT "${r}" (${zoe[r]}) claim missing`,mt,{claims:e.claims});return e}function XTe(t,e){if(typeof e.claims[t]!="string")throw ke(`unexpected JWT "${t}" (${zoe[t]}) claim type`,mt,{claims:e.claims});return e}function YTe(t,e,r,o,n){return fPe(r,mPe.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),xoe(e),Soe(e),n).then(GTe.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(WTe.bind(void 0,t)).then(ZTe.bind(void 0,e.client_id)).then(XTe.bind(void 0,"sub"))}function joe(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 QTe(t){t.auth_time!==void 0&&sA(t.auth_time,!0,'ID Token "auth_time" (authentication time)',mt,{claims:t})}function Moe(t,e,r){if(r===uA)return;let o=Eoe()+xoe(t),n=Soe(t);if(e.auth_time+r<o-n)throw ke("too much time has elapsed since the last End-User authentication",A4,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Uoe(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 ePe(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 Loe(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?tPe(t,e,r,o.expectedNonce,o.maxAge,o[oA],o.recognizedTokenTypes):rPe(t,e,r,o?.maxAge,o?.[oA],o?.recognizedTokenTypes)}async function tPe(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=joe(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=Ooe(c);return Moe(e,u,n),Uoe(u,o),c}async function rPe(t,e,r,o,n,i){let s=await dA(t,e,r,void 0,n,i),a=Ooe(s);return a&&(Moe(e,a,joe(e,o)),Uoe(a,cA)),s}var nPe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",oPe="OAUTH_RESPONSE_BODY_ERROR",iPe="OAUTH_UNSUPPORTED_OPERATION",sPe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var $4="OAUTH_PARSE_ERROR",mt="OAUTH_INVALID_RESPONSE";var aPe="OAUTH_RESPONSE_IS_NOT_JSON",cPe="OAUTH_RESPONSE_IS_NOT_CONFORM",uPe="OAUTH_HTTP_REQUEST_FORBIDDEN",lPe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",A4="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",em="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var dPe="OAUTH_MISSING_SERVER_METADATA",pPe="OAUTH_INVALID_SERVER_METADATA";async function Foe(t,e,r,o,n){return tm(t),rm(e),P4(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Voe(t,e,r,o){return dA(t,e,r,void 0,o?.[oA],o?.recognizedTokenTypes)}async function qoe(t,e,r,o,n){tm(t),rm(e),nn(o,'"token"');let i=Aoe(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[voe]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=woe(n?.headers);return a.delete("accept"),Poe(t,e,r,i,s,a,n)}async function Hoe(t){if(!lA(t,Response))throw sr('"response" must be an instance of Response',Pa);await Toe(t,200,"Revocation Endpoint")}function Boe(t){if(t.bodyUsed)throw sr('"response" body has been used already',Vs)}async function fPe(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(_4(E4(i)))}catch(d){throw ke("failed to parse JWT Header body as base64url encoded JSON",$4,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(_4(E4(s)))}catch(d){throw ke("failed to parse JWT Payload body as base64url encoded JSON",$4,d)}if(!iA(u))throw ke("JWT Payload must be a top level object",mt,t);let l=Eoe()+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',A4,{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',A4,{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 mPe(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 hPe=Symbol(),gPe=Symbol();function Koe(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 gPe:if(i!==void 0)throw ke('unexpected "state" response parameter encountered',mt,{expected:void 0,parameters:r});break;case hPe: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 Hv("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 JTe(new URLSearchParams(r))}async function yPe(t,e=boe){let r;try{r=await t.json()}catch(o){throw e(t),ke('failed to parse "response" body as JSON',$4,o)}if(!iA(r))throw ke('"response" body must be a top level object',mt,{body:r});return r}var vPe=Symbol();function bPe(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 bPe(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 O4(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Zoe=Object.assign(Object.create(null),{dpop:()=>N(502,"invalid_response","The service returned an unsupported token.")}),_Pe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Zoe,{"user access token":()=>{}})},xPe={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"},SPe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+O4(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},EPe={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:Zoe,...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"?_Pe:t.adapter==="openrouter"?xPe:t.adapter==="vultr"?EPe:{},...t.revoke?.style==="github"?SPe:{}}}function Ca(t,e){try{return Mn(new nZ(t).expand(e)).href}catch{N(400,"invalid_service_url","Check the service URL and its required fields.")}}var Woe=(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 _oe(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&&Mn(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?$oe():(e.clientSecret||N(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?koe(e.clientSecret):Ioe(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[T4]: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 fi({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?Noe:e.grantType==="client_credentials"?Voe:Loe)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:qs(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof Rr)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?Woe(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,fi(f))}else{let{server:f,client:p}=this.configuration(e,r),h;try{let g=Koe(f,p,o.parameters,o.state);h=await Doe(f,p,this.authentication(r,e.clientAuth),g,l.redirectUri?.(r,i)??i,e.pkce?n:C4,{...this.options(e),additionalParameters:e.tokenParams})}catch(g){throw(g instanceof qv||g instanceof Hv)&&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 Foe(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 Roe(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 qoe({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Hoe(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 "+O4(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 N4(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function D4(t){return t||N(409,"app_required","Choose an OAuth application."),t}function IPe(t){return{token:QN.parse(t.token),response:pt.parse(t.response)}}var mA=class{constructor(e){this.transport=e}transport;facts=NN;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=N4(r),n=D4(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??pi(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return Pr.parse({...e.material,oauth:a})}async recover(e,r,o){let i=IPe(o).token;return Pr.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(N4(e),D4(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(N4(e),D4(r),e.oauth)}};function kPe(t){if(t.method.kind!=="token"&&t.method.kind!=="approval")throw new Error("Use an input credential provider.");return t.method.config}var Bv=class{facts=_p;needsRenewal(){return!1}async outputs(e){let r=kPe(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=DN;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 $Pe}from"node:fs/promises";var APe=m.object({accessToken:m.string().min(1).max(16384).regex(/^\S+$/),expiresAt:m.number().int().positive()}).strict();async function TPe(t,e){if(t==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,i=n?await $Pe(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 Joe(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=TPe){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(Joe(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=fi(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=APe.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=Joe(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 Goe(t,e){let r={oauth:new mA(t),token:new Bv,aws:new nA(e),approval:new Bv,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 Xoe(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!TB(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=Goe(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(Pr.parse(JSON.parse(nm(a)))):o,i=Pr.safeParse(JSON.parse(nm(await Ag(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,ye.clientCredential,n),s=vn.parse(JSON.parse(nm(await Ag(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(jn(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=eD.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,ye.tokenSet,o),r);(n.action==="refresh"||Vt(i.method).revocable)&&await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=eD.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,ye.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=>iD(i,o,r.origin));return iD(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 bZ(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 YB(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=PPe(),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 Rr&&["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 RPe}from"node:dns/promises";import{request as CPe}from"node:https";import{brotliDecompressSync as OPe,gunzipSync as NPe,inflateSync as DPe}from"node:zlib";var om=class{constructor(e){this.origin=e}origin;async send(e){let r=Mn(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 RPe(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=CPe(r,d,p=>{let h=[],g=0;p.on("data",y=>{g+=y.length,g>n?p.destroy(new Rr(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"?NPe:w==="deflate"?DPe:w==="br"?OPe:null;if(!_)throw new Rr(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 Rr)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 In(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=z4(zPe(la()),"custody",r.id),i=new Mg(z4(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 Mg(z4(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 Yoe(t,e){let{custody:r,keys:o,binding:n,connections:i}=In(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===ye.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Xoe(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ye.value)return Ag(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 jPe}from"node:child_process";import{fileURLToPath as MPe}from"node:url";function Qoe(t,e){return new Promise((r,o)=>{let n=jPe(process.execPath,[MPe(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&&!r.replaced?r.content:void 0,i=n?.policy??await t.policy(e,ye.tokenSet,[],r?{replacing:r.content.policy}:{});if(!o)return i;let s=await Promise.all([...new Set(o)].map(async a=>{let{binding:c}=await t.inspectIdentity(a);return await t.trusted(c),c}));return i=$r.parse({...i,revision:i.revision+(n?1:0),grants:[...i.grants.filter(a=>!("actor"in a)),...s.map(a=>({actor:a,executor:a,operations:[...lc(ye.tokenSet)],origins:[],functionDigests:[],callerProgram:!0,expiresAt:new Date(Date.now()+30*864e5).toISOString()}))]}),i}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 eie(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 Pr.parse({...r,aws:ia.parse(t.aws)});if(t.method.kind==="oauth")return Pr.parse({...r,requestedScopes:t.scopes,fields:jn(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 Pr.parse({...r,fields:I0(o,i,n)})}var _A=m.object({consumerKey:m.string().min(1).max(16384),validationUrl:m.url()});async function tie(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:Mn(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(fi(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:bB(pi(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(fi(a)),u=Mn(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 rie(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:jn(Vt(t.method).fields,t.app.fields),requestedScopes:t.scopes};if(t.method.kind==="ovh")return Pr.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 Pr.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 nie(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=fi(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 oie(t){let e=await nie(t,`mutation createFlashAuthRequest {
|
|
132
132
|
createFlashAuthRequest { id status expiresAt }
|
|
133
133
|
}`),r=m.object({id:m.string().min(1).max(1e3),expiresAt:m.iso.datetime({offset:!0})}).parse(e.createFlashAuthRequest),o=xA.parse({id:r.id,expiresAt:Date.parse(r.expiresAt)});o.expiresAt<=Date.now()&&N(409,"authorization_expired","Start the RunPod connection again.");let n=new URL("https://console.runpod.io/flash/login");return n.searchParams.set("request",r.id),{approval:o,url:n.href}}async function iie(t,e){e.expiresAt<=Date.now()&&N(409,"authorization_expired","Start the RunPod connection again.");let r=await nie(t,`query flashAuthRequestStatus($flashAuthRequestId: String!) {
|
|
134
134
|
flashAuthRequestStatus(flashAuthRequestId: $flashAuthRequestId) { id status expiresAt apiKey }
|