@tomato414941/foundation 3.2.0 → 3.2.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.
Files changed (2) hide show
  1. package/dist/cli.mjs +2 -2
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -125,9 +125,9 @@ ${c}`:c:"",l=Function,d=`return (input) => {
125
125
  ${c}
126
126
  }`,p;try{p=new l(...s,d)(...a)}catch(f){throw new Re(`this schema (generated code failed to evaluate: ${f.message})`)}return e?.debug&&(p.code=u),p.definite=o.definite,p}function ne(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 fu(t,e){return t.definite=!1,ne(t,e)}function ee(t){return`v${t.varCounter++}`}function Mle(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return Yr;let o=r;return o.issues.length===0?o.value:Yr}function Or(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return At(t,e,r,o,n)}catch(u){if(!(u instanceof Re)||!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,Ule(t,e,r,o)}}function Ule(t,e,r,o){e.definite=!1;let n=ne(e,r),i=ne(e,Mle),s=ee(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var Lle=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Fle(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&&!Lle.has(a.check))throw new Re('check with a custom "when" condition');switch(a.check){case"greater_than":Vle(t,e,a,i);break;case"less_than":Ble(t,e,a,i);break;case"multiple_of":Hle(t,e,a,i);break;case"number_format":MF(t,a,i);break;case"min_length":{let c=lu(a.minimum,"min_length"),u=NP(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=lu(a.maximum,"max_length"),u=NP(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=lu(a.length,"length_equals"),u=NP(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 < ${lu(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${lu(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${lu(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=UF(t,e,a,i);break;case"custom":i=Gle(t,e,s,i);break;case"bigint_format":qle(t,a,i);break;case"mime_type":Zle(t,e,a,i);break;case"property":Wle(t,e,a,i);break;case"properties":Kle(t,e,a,i);break;case"overwrite":{let c=ee(e);Jle(t,e,s,i,c),i=c;break}default:throw new Re(`check type ${a.check}`)}}return i}function NP(t,e,r,o){let n=ne(e,iu),i=ee(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function lu(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Re(`${e} bound of type ${typeof t}`);return`${t}`}function jF(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Re("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Re("comparison check with Invalid Date bound");return ne(t,e)}throw new Re(`comparison check bound of type ${typeof e}`)}function Vle(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${jF(e,r.value)}) return INVALID;`)}function Ble(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${jF(e,r.value)}) return INVALID;`)}function Hle(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Re("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ne(e,_m);t.write(`if (${n}(${o}, ${lu(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function MF(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 Re(`number format ${o}`)}}function qle(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 Re(`bigint format ${o}`)}}function Zle(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=ne(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function Kle(t,e,r,o){if(r.when)throw new Re('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"?ne(e,i):Gr(i),a=ee(e);t.write(`const ${a} = ${o}[${s}];`),Or(t,e,n[i],a,!1)}}function Wle(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;At(t,e,r.schema,n)}function Jle(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Re("overwrite check without a transform function");if(pu(i))throw new jo("z.compile: async overwrite transforms are not supported");let s=ne(e,i);t.write(`const ${n} = ${s}(${o});`)}function DP(){throw new hn}function MP(t){this.issues.push(t)}function Gle(t,e,r,o){let n=r._zod.def;if(n.fn){if(pu(n.fn))throw new jo("z.compile: async .refine() predicates are not supported");let i=fu(e,n.fn),s=ne(e,DP),a=ee(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(pu(r._zod.check))throw new jo("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=fu(e,u=>{let l={value:u,issues:[],addIssue:MP};return i(l)instanceof Promise&&DP(),l.issues.length===0?l.value:Yr}),c=ee(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Re("custom check without a predicate or check function")}var Xle=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 UF(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=ne(e,jm);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=ne(e,pb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ne(e,bb),l=ne(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=ne(e,zm);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=ne(e,ub);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ne(e,gb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ne(e,vb);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=ne(e,Ww),l=ne(e,r),d=ee(e),p=ee(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${p} = ${u}(${d}, ${l});`),t.write(`if (typeof ${p} === "number") return INVALID;`),s.hostname!==void 0){let h=ne(e,Jw);t.write(`if (!${h}(${p}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let h=ne(e,Gw);t.write(`if (!${h}(${p}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let f=ee(e),m=s.normalize?`${p}.href`:`${ne(e,Dm)}(${d})`;return t.write(`const ${f} = ${m};`),f}let a=r.fn;if(a){if(pu(a))throw new Re(`async string format ${i}`);let u=ne(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(Xle.has(i)&&r.pattern){let u=ne(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 Re("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(${Gr(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${Gr(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${Gr(u)}) return INVALID;`);break}default:throw new Re(`string format ${c}`)}return o}function At(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Re(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=Yle(t,e,r,o,a);break;case"number":c=Qle(t,r,o);break;case"boolean":c=ede(t,o);break;case"bigint":c=tde(t,r,o);break;case"symbol":c=rde(t,o);break;case"undefined":c=nde(t,o);break;case"null":c=ode(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=ide(t,o);break;case"nan":c=sde(t,o);break;case"date":c=ade(t,o);break;case"object":c=cde(t,e,r,o,a);break;case"optional":c=ude(t,e,r,o,a);break;case"nullable":c=fde(t,e,r,o,a);break;case"array":c=pde(t,e,r,o,a);break;case"literal":c=mde(t,e,r,o);break;case"enum":c=hde(t,e,r,o);break;case"readonly":{let u=NF(t,e,r,o),l=ee(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":NF(t,e,r,o),c="true";break;case"default":case"prefault":c=gde(t,e,r,o);break;case"nonoptional":c=yde(t,e,r,o);break;case"tuple":c=vde(t,e,r,o);break;case"union":c=wde(t,e,r,o);break;case"intersection":c=Sde(t,e,r,o);break;case"record":c=xde(t,e,r,o);break;case"map":c=kde(t,e,r,o);break;case"set":c=Ide(t,e,r,o);break;case"file":c=$de(t,o);break;case"template_literal":c=Ade(t,e,r,o);break;case"lazy":c=Tde(t,e,r,o);break;case"pipe":c=Pde(t,e,r,o);break;case"custom":c=Rde(t,e,r,o);break;case"transform":c=Nde(t,e,r,o);break;case"catch":c=Ode(t,e,r,o);break;default:throw new Re(`schema type ${s}`)}return c===null?null:Fle(t,e,r,c)}function Yle(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:UF(t,e,i,o,n)}function Qle(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&&MF(t,{format:o.format},r),r}function ede(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function tde(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 rde(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function nde(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function ode(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function ide(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function sde(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function ade(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function cde(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"?ne(e,b):Gr(b),d=b=>typeof b=="symbol"?`[${l(b)}]`:Gr(b),p=s;if(a.includes("__proto__"))throw new Re('object shape key "__proto__"');let f=new Map;for(let b of u){let _=p[b],x=l(b),$=ee(e);if(t.write(`const ${$} = ${o}[${x}];`),_._zod.optin!==void 0){let O=ee(e);t.write(`let ${O} = (() => {`),t.indented(H=>{let te=Or(H,e,_,$);H.write(`return ${te};`)}),t.write("})();"),_._zod.optout==="optional"?(t.write(`if (${O} === INVALID) {`),t.indented(H=>{H.write(`if (${x} in ${o}) return INVALID;`),H.write(`${O} = undefined;`)}),t.write("}")):t.write(`if (${O} === INVALID) return INVALID;`),f.set(b,O)}else{dde(_)&&t.write(`if (!(${x} in ${o})) return INVALID;`);let O=Or(t,e,_,$,n);O!==null&&f.set(b,O)}}let m=i.catchall,h="none";if(m){let b=m._zod.def.type;if(b==="never"){let _=a.map(x=>`k !== ${Gr(x)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(x=>{x.write(`if (${_}) return INVALID;`)}),t.write("}")}else(b==="unknown"||b==="any")&&!m._zod.def.checks?.length?h="passthrough":h="schema"}let y=ee(e),w=u.some(b=>OF(p[b])||zP(p[b]));if(!n){if(h==="schema"){let b=a.length>0?ne(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 x=ee(e);_.write(`const ${x} = ${o}[k];`),Or(_,e,m,x,!1)}),t.write("}")}return null}if(w){t.write(`const ${y} = {};`);for(let b of u){let _=l(b),x=f.get(b);zP(p[b])?t.write(`if (${_} in ${o}) ${y}[${_}] = ${x};`):OF(p[b])?t.write(`if (${x} !== undefined || ${_} in ${o}) ${y}[${_}] = ${x};`):t.write(`${y}[${_}] = ${x};`)}}else{let b=u.map(_=>`${d(_)}: ${f.get(_)}`).join(", ");t.write(`const ${y} = { ${b} };`)}if(h!=="none"){let b=a.length>0?ne(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;`),h==="passthrough")_.write(`${y}[k] = ${o}[k];`);else{let x=ee(e);_.write(`const ${x} = ${o}[k];`);let $=Or(_,e,m,x);_.write(`${y}[k] = ${$};`)}}),t.write("}")}return y}function ude(t,e,r,o,n=!0){let i=r._zod.def;if(lde(r))return At(t,e,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=ee(e),c=ee(e);return t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=At(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=At(u,e,i.innerType,o);u.write(`${a} = ${l};`)}),t.write("}"),a}let s=n?ee(e):null;return s&&t.write(`let ${s};`),t.write(`if (${o} !== undefined) {`),t.indented(a=>{let c=At(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function lde(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function dde(t){return t._zod.optin===void 0&&du(t)}function du(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?du(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?du(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(du):!0;case"intersection":return!e.left||!e.right?!0:du(e.left)&&du(e.right);case"pipe":return e.in?du(e.in):!0;default:return!0}}function zP(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function OF(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&ud(t)}function ud(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?ud(e.innerType):!0;case"union":return e.options?e.options.some(ud):!0;case"intersection":return!e.left||!e.right||ud(e.left)||ud(e.right);case"pipe":return e.out?ud(e.out):!0;default:return!0}}function fde(t,e,r,o,n=!0){let i=r._zod.def,s=n?ee(e):null;return s&&t.write(`let ${s} = null;`),t.write(`if (${o} !== null) {`),t.indented(a=>{let c=At(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function pde(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (!Array.isArray(${o})) return INVALID;`);let s=n?ee(e):null,a=ee(e),c=ee(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=Or(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function mde(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=ne(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=ne(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${Gr(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 Re(`literal type ${typeof s}`);return o}function hde(t,e,r,o){let n=r._zod.values;if(!n)throw new Re("enum schema without enumerated values");let i=ne(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function NF(t,e,r,o){let n=r._zod.def;return At(t,e,n.innerType,o)}function gde(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 At(t,e,n.innerType,o);let c=ne(e,s),u=ee(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),At(t,e,n.innerType,u)}let a=ee(e);if(s){let c=ne(e,s),u=ne(e,Hl);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=At(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=At(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function yde(t,e,r,o){let n=r._zod.def,i=At(t,e,n.innerType,o),s=ee(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function vde(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=DF(i,"optin"),c=DF(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=ee(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(p=>{p.write(`if (${l} < ${o}.length) {`),p.indented(f=>{let m=ee(e);f.write(`const ${m} = ${o}[${l}];`);let h=Or(f,e,d,m);f.write(`${u}[${l}] = ${h};`)}),p.write("} else {"),p.indented(f=>{if(zP(d)){f.write(`${u}.length = ${l};`);return}let m=ee(e),h=ee(e);f.write(`const ${m} = undefined;`),f.write(`const ${h} = (() => {`),f.indented(y=>{let w=Or(y,e,d,m);y.write(`return ${w};`)}),f.write("})();"),f.write(`if (${h} === INVALID || ${h} === undefined) ${u}.length = ${l};`),f.write(`else ${u}[${l}] = ${h};`)}),p.write("}")}),t.write("}");else{let p=ee(e);t.write(`const ${p} = ${o}[${l}];`);let f=Or(t,e,d,p);t.write(`${u}[${l}] = ${f};`)}}if(s){let l=ee(e),d=ee(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(p=>{p.write(`const ${d} = ${o}[${l}];`);let f=Or(p,e,s,d);p.write(`${u}[${l}] = ${f};`)}),t.write("}")}return u}function DF(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 wde(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return bde(t,e,n,o);if(n.inclusive===!1)throw new Re("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return At(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=ne(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=ee(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=At(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function bde(t,e,r,o){if(r.unionFallback)throw new Re("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=ee(e),i=ee(e);t.write(`const ${n} = ${o}?.[${Gr(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 Re("discriminated union option without static discriminator values");for(let p of u){if(a.has(p))throw new Re(`duplicate discriminator value ${String(p)}`);a.add(p)}let l=Array.from(u,p=>_de(e,n,p)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(p=>{let f=At(p,e,c,o);p.write(`${i} = ${f};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function _de(t,e,r){if(typeof r=="string")return`${e} === ${Gr(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=ne(t,r);return`${e} === ${o}`}throw new Re(`literal discriminator value ${String(r)}`)}function Sde(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=Or(t,e,n.left,o),s=Or(t,e,n.right,o),a=ne(e,td),c=ee(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function xde(t,e,r,o){let n=r._zod.def,i=ne(e,Yn);t.write(`if (!${i}(${o})) return INVALID;`);let s=ee(e),a=ee(e),c=ee(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let f=[];for(let h of l){if(!(typeof h=="string"||typeof h=="number"||typeof h=="symbol"))throw new Re(`record key value ${String(h)}`);let y=typeof h=="number"?h.toString():h;if(y==="__proto__")throw new Re('record key "__proto__"');f.push(y);let w=ne(e,h),b=At(t,e,n.keyType,w),_=ee(e);t.write(`const ${_} = ${o}[${Ede(e,y)}];`);let x=Or(t,e,n.valueType,_);t.write(`${s}[${b}] = ${x};`)}let m=ne(e,new Set(f));return t.write(`for (const ${a} in ${o}) {`),t.indented(h=>{h.write(`if (${m}.has(${a})) continue;`),u.mode==="loose"?h.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):h.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 f=n.mode==="loose",m=g_(n.keyType);m.definite===!1&&(e.definite=!1);let h=ne(e,m),y=ne(e,js),w=ee(e);return zF(t,e,o,a,b=>{b.write(`let ${w} = ${h}(${a});`),b.write(`if (${w} === INVALID && typeof ${a} === "string" && ${y}.test(${a})) ${w} = ${h}(Number(${a}));`),f?b.write(`if (${w} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):b.write(`if (${w} === INVALID) return INVALID;`),b.write(`if (${w} === "__proto__") continue;`);let _=ee(e);b.write(`const ${_} = ${o}[${a}];`);let x=Or(b,e,n.valueType,_);b.write(`${s}[${w}] = ${x};`)}),s}return zF(t,e,o,a,f=>{f.write(`const ${c} = ${o}[${a}];`);let m=Or(f,e,n.valueType,c);f.write(`${s}[${a}] = ${m};`)},"return INVALID;"),s}function zF(t,e,r,o,n,i){let s=ne(e,Object.prototype.propertyIsEnumerable),a=ee(e),c=ee(e),u=ee(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 Ede(t,e){return typeof e=="string"?Gr(e):ne(t,e)}function kde(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Map)) return INVALID;`);let i=ee(e),s=ee(e),a=ee(e);return t.write(`const ${i} = new Map();`),t.write(`for (const [${s}, ${a}] of ${o}) {`),t.indented(c=>{let u=At(c,e,n.keyType,s),l=At(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function Ide(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Set)) return INVALID;`);let i=ee(e),s=ee(e);return t.write(`const ${i} = new Set();`),t.write(`for (const ${s} of ${o}) {`),t.indented(a=>{let c=At(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function $de(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function Ade(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=ne(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function Tde(t,e,r,o){let n=r._zod.def,i=fu(e,n.getter),s=ne(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=ee(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function Pde(t,e,r,o){let n=r._zod.def,i=At(t,e,n.in,o);if(n.transform){if(pu(n.transform))throw new jo("z.compile: async transforms in pipes are not supported");let s=n.transform,c=fu(e,l=>{let d={value:l,issues:[],addIssue:MP},p=s(l,d);return p instanceof Promise?Yr:d.issues.length===0?p:Yr}),u=ee(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),At(t,e,n.out,u)}else return At(t,e,n.out,i)}function pu(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function Rde(t,e,r,o){let n=r._zod.def;if(n.fn){if(pu(n.fn))throw new jo("z.compile: async custom predicates are not supported");let i=fu(e,n.fn),s=ne(e,DP),a=ee(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new Re("custom schema without a predicate function");return o}function Cde(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return Yr;let n=o;return n.issues.length===0?n.value:e()}function Ode(t,e,r,o){let n=r._zod.def;if(!n.catchValue[Ew])throw new Re("catch with a callback (only a constant catch value compiles)",!1);let i=ee(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=Or(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=ne(e,n.innerType),a=fu(e,n.catchValue),c=ne(e,Cde);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 Nde(t,e,r,o){let n=r._zod.def;if(n.transform){if(pu(n.transform))throw new jo("z.compile: async transforms are not supported");let i=n.transform,a=fu(e,u=>{let l={value:u,issues:[],addIssue:MP},d=i(u,l);return d instanceof Promise?Yr:l.issues.length===0?d:Yr}),c=ee(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function y_(t){return t.checks&&(t.checks=[...t.checks]),t}function v_(t,e){return new t(y_({type:"string",...D(e)}))}function UP(t,e){return new t(y_({type:"string",coerce:!0,...D(e)}))}function Wm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...D(e)})}function Jm(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...D(e)})}function Gm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...D(e)})}function Xm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(e)})}function Ym(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(e)})}function Qm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(e)})}function ld(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...D(e)})}function eh(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...D(e)})}function th(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(e)})}function rh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...D(e)})}function nh(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(e)})}function oh(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...D(e)})}function ih(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...D(e)})}function sh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(e)})}function ah(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(e)})}function ch(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(e)})}function w_(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...D(e)})}function uh(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(e)})}function lh(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(e)})}function dh(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...D(e)})}function fh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...D(e)})}function ph(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...D(e)})}function b_(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...D(e)})}function __(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...D(e)})}function mh(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...D(e)})}var LP={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function hh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(e)})}function gh(t,e){return new t({type:"string",format:"date",check:"string_format",...D(e)})}function yh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...D(e)})}function vh(t,e){return new t({type:"string",format:"duration",check:"string_format",...D(e)})}function S_(t,e){return new t(y_({type:"number",checks:[],...D(e)}))}function FP(t,e){return new t(y_({type:"number",coerce:!0,checks:[],...D(e)}))}function x_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...D(e)})}function E_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...D(e)})}function k_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...D(e)})}function I_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...D(e)})}function $_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...D(e)})}function A_(t,e){return new t({type:"boolean",...D(e)})}function VP(t,e){return new t({type:"boolean",coerce:!0,...D(e)})}function T_(t,e){return new t({type:"bigint",...D(e)})}function BP(t,e){return new t({type:"bigint",coerce:!0,...D(e)})}function P_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...D(e)})}function R_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...D(e)})}function C_(t,e){return new t({type:"symbol",...D(e)})}function O_(t,e){return new t({type:"undefined",...D(e)})}function N_(t,e){return new t({type:"null",...D(e)})}function D_(t){return new t({type:"any"})}function z_(t){return new t({type:"unknown"})}function j_(t,e){return new t({type:"never",...D(e)})}function M_(t,e){return new t({type:"void",...D(e)})}function U_(t,e){return new t({type:"date",...D(e)})}function HP(t,e){return new t({type:"date",coerce:!0,...D(e)})}function L_(t,e){return new t({type:"nan",...D(e)})}function Pi(t,e){return new Mw({check:"less_than",...D(e),value:t,inclusive:!1})}function Cn(t,e){return new Mw({check:"less_than",...D(e),value:t,inclusive:!0})}function Ri(t,e){return new Uw({check:"greater_than",...D(e),value:t,inclusive:!1})}function On(t,e){return new Uw({check:"greater_than",...D(e),value:t,inclusive:!0})}function F_(t){return Ri(0,t)}function V_(t){return Pi(0,t)}function B_(t){return Cn(0,t)}function H_(t){return On(0,t)}function _a(t,e){return new eP({check:"multiple_of",...D(e),value:t})}function Sa(t,e){return new nP({check:"max_size",...D(e),maximum:t})}function Ci(t,e){return new oP({check:"min_size",...D(e),minimum:t})}function mu(t,e){return new iP({check:"size_equals",...D(e),size:t})}function hu(t,e){return new sP({check:"max_length",...D(e),maximum:t})}function Ms(t,e){return new aP({check:"min_length",...D(e),minimum:t})}function gu(t,e){return new cP({check:"length_equals",...D(e),length:t})}function dd(t,e){return new uP({check:"string_format",format:"regex",...D(e),pattern:t})}function fd(t){return new lP({check:"string_format",format:"lowercase",...D(t)})}function pd(t){return new dP({check:"string_format",format:"uppercase",...D(t)})}function md(t,e){return new fP({check:"string_format",format:"includes",...D(e),includes:t})}function hd(t,e){return new pP({check:"string_format",format:"starts_with",...D(e),prefix:t})}function gd(t,e){return new mP({check:"string_format",format:"ends_with",...D(e),suffix:t})}function q_(t,e,r){return new hP({check:"property",property:t,schema:e,...D(r)})}function yd(t,e){return new gP({check:"properties",shape:t,...D(e)})}function vd(t,e){return new yP({check:"mime_type",mime:t,...D(e)})}function Mo(t){return new vP({check:"overwrite",tx:t})}function wd(t){return Mo(e=>e.normalize(t))}function bd(){return Mo(t=>t.trim())}function _d(){return Mo(t=>t.toLowerCase())}function Sd(){return Mo(t=>t.toUpperCase())}function xd(){return Mo(t=>tT(t))}function qP(t,e,r){return new t({type:"array",element:e,...D(r)})}function Dde(t,e,r){return new t({type:"union",options:e,...D(r)})}function zde(t,e,r){return new t({type:"union",options:e,inclusive:!1,...D(r)})}function jde(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...D(o)})}function Mde(t,e,r){return new t({type:"intersection",left:e,right:r})}function Ude(t,e,r,o){let n=r instanceof ae,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...D(i)})}function Lde(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...D(o)})}function Fde(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...D(o)})}function Vde(t,e,r){return new t({type:"set",valueType:e,...D(r)})}function Bde(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...D(r)})}function Hde(t,e,r){return new t({type:"enum",entries:e,...D(r)})}function qde(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...D(r)})}function Z_(t,e){return new t({type:"file",...D(e)})}function Zde(t,e){return new t({type:"transform",transform:e})}function Kde(t,e){return new t({type:"optional",innerType:e})}function Wde(t,e){return new t({type:"nullable",innerType:e})}function Jde(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():Hl(r)}})}function Gde(t,e,r){return new t({type:"nonoptional",innerType:e,...D(r)})}function Xde(t,e){return new t({type:"success",innerType:e})}function Yde(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:cT(r)})}function Qde(t,e,r){return new t({type:"pipe",in:e,out:r})}function efe(t,e){return new t({type:"readonly",innerType:e})}function tfe(t,e,r){return new t({type:"template_literal",parts:e,...D(r)})}function rfe(t,e){return new t({type:"lazy",getter:e})}function nfe(t,e){return new t({type:"promise",innerType:e})}function K_(t,e,r){let o=D(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function W_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...D(r)})}function J_(t,e){let r=LF(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(ql(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(ql(i))}},t(o.value,o)),e);return r}function LF(t,e){let r=new it({check:"custom",...D(e)});return r._zod.check=t,r}function G_(t){let e=new it({check:"describe"});return e._zod.onattach=[r=>{let o=lr.get(r)??{};lr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function X_(t){let e=new it({check:"meta"});return e._zod.onattach=[r=>{let o=lr.get(r)??{};lr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function Y_(t,e){let r=D(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(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(o),s=new Set(n),a=t.Codec??od,c=t.Boolean??rd,u=t.String??ba,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new a({type:"pipe",in:l,out:d,transform:((f,m)=>{let h=f;return r.case!=="sensitive"&&(h=h.toLowerCase()),i.has(h)?!0:s.has(h)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:p,continue:!1}),{})}),reverseTransform:((f,m)=>f===!0?o[0]||"true":n[0]||"false"),error:r.error});return p._zod.bag.truthy=o,p._zod.bag.falsy=n,p._zod.bag.case=r.case??"insensitive",p}function xa(t,e,r,o={}){let n=D(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 wh(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&ur(t,o,r[o]);return t}function Ea(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??lr,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 Wt(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 nt(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 p=s.schema,f=e.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),nt(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&wh(s.schema,c),e.io==="input"&&Qr(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 FF(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function ka(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,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${FF(f)}`}}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+FF(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 HF(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;HF(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 qF=new Set(["type","properties","required","additionalProperties"]),VF=["oneOf","anyOf"];function BF(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function ZP(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!qF.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]??BF(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:ZP(a)??{allOf:a};ur(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=BF(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 ofe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of qF)if(n in t)return;let r=e.filter(n=>VF.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=ZP(e);else{let n=r[0],i=VF.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=>ZP([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,wh(t,o))}function Ia(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 f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):wh(u,m),wh(u,l),a._zod.parent===d)for(let y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(m.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}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())HF(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)??[])ofe(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)}wh(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,ur(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:Ed(e,"input",t.processors),output:Ed(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Qr(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 Qr(o.element,r);if(o.type==="set")return Qr(o.valueType,r);if(o.type==="lazy")return Qr(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 Qr(o.innerType,r);if(o.type==="intersection")return Qr(o.left,r)||Qr(o.right,r);if(o.type==="record"||o.type==="map")return Qr(o.keyType,r)||Qr(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Qr(o.in,r)||Qr(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Qr(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Qr(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Qr(n,r))return!0;return!!(o.rest&&Qr(o.rest,r))}return!1}var KP=(t,e={})=>r=>{let o=Ea({...r,processors:e});return nt(t,o),ka(o,t),Ia(o,t)},Ed=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Ea({...n??{},target:i,io:e,processors:r});return nt(t,s),ka(s,t),Ia(s,t)};var kd=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},Id=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},ZF=(t,e)=>{kd(t,"minimum",e),Id(t,"maximum",e)},GF=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},XF=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},YF=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},QF=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},KF=(t,e)=>kd(t,"minimum",e.minimum),WF=(t,e)=>Id(t,"maximum",e.maximum),JF=t=>(e,r)=>{QF(e,r.format);let[o,n]=t[r.format];kd(e,"minimum",o),Id(e,"maximum",n)},ife={greater_than:(t,e)=>kd(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>Id(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>GF(t,e.value),number_format:JF(xm),bigint_format:JF(Em),min_length:KF,max_length:WF,length_equals:(t,e)=>ZF(t,e.length),min_size:KF,max_size:WF,size_equals:(t,e)=>ZF(t,e.size),string_format:(t,e)=>{QF(t,e.format),e.pattern&&XF(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)=>YF(t,e.mime)};function Jt(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)ife[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&kd(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&kd(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Id(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Id(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&GF(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&YF(e,n.mime);for(let i of n.patterns??[])XF(e,i);return e}var sfe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},afe=new Map([[db,NT],[Mm,DT]]),eV=t=>afe.get(t)??t,GP=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Jt(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=sfe[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(eV);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},XP=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Jt(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let w of a)Number.isFinite(w)&&w!==0?m.add(Math.abs(w)):Wt(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[h,...y]=m;h!==void 0&&(n.multipleOf=h),y.length&&(n.allOf=[...n.allOf??[],...y.map(w=>({multipleOf:w}))])}},YP=(t,e,r,o)=>{r.type="boolean"},QP=(t,e,r,o)=>{Wt(t,e,r,o,"BigInt cannot be represented in JSON Schema")},eR=(t,e,r,o)=>{Wt(t,e,r,o,"Symbols cannot be represented in JSON Schema")},tR=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},rR=(t,e,r,o)=>{Wt(t,e,r,o,"Undefined cannot be represented in JSON Schema")},nR=(t,e,r,o)=>{Wt(t,e,r,o,"Void cannot be represented in JSON Schema")},oR=(t,e,r,o)=>{r.not={}},iR=(t,e,r,o)=>{},sR=(t,e,r,o)=>{},aR=(t,e,r,o)=>{Wt(t,e,r,o,"Date cannot be represented in JSON Schema")},cR=(t,e,r,o)=>{let n=t._zod.def,i=Ll(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},uR=(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(Wt(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Wt(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},lR=(t,e,r,o)=>{Wt(t,e,r,o,"NaN cannot be represented in JSON Schema")},dR=(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},fR=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Jt(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})))},pR=(t,e,r,o)=>{r.type="boolean"},mR=(t,e,r,o)=>{Wt(t,e,r,o,"Custom types cannot be represented in JSON Schema")},hR=(t,e,r,o)=>{Wt(t,e,r,o,"Function types cannot be represented in JSON Schema")},gR=(t,e,r,o)=>{Wt(t,e,r,o,"Transforms cannot be represented in JSON Schema")},yR=(t,e,r,o)=>{Wt(t,e,r,o,"Map cannot be represented in JSON Schema")},vR=(t,e,r,o)=>{Wt(t,e,r,o,"Set cannot be represented in JSON Schema")},wR=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Jt(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=nt(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 bR=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Wt(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)ur(n.properties,u,nt(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=nt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},eS=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>nt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},_R=(t,e,r,o)=>{let n=t._zod.def,i=nt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=nt(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)},SR=(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((h,y)=>nt(h,e,{...o,path:[...o.path,s,y]})),u=i.rest?nt(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 h=i.items[l-1];if(!(e.io==="input"?bh(h)!==void 0:h._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=Jt(t);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function WP(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let h=WP(t,m,r);return h===m?e:h}for(let m of["anyOf","oneOf"]){let h=e[m];if(!Array.isArray(h))continue;let y=h.map(w=>WP(t,w,r));y.some((w,b)=>w!==h[b])&&(e={...e,[m]:y})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?js:Rm).source)),f}var JP=new WeakMap;function cfe(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 JP.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=WP(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 xR=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Jt(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=nt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)ur(n.patternProperties,eV(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=nt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=JP.get(e);l||(l=[],JP.set(e,l),e.deferred.push(()=>cfe(e))),l.push(t)}n.additionalProperties=nt(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))}},ER=(t,e,r,o)=>{let n=t._zod.def,i=nt(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"}]},kR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},IR=Symbol();function tV(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Wt(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),IR):JSON.parse(s)}var $R=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=tV(n.defaultValue,t,e,r,o);s!==IR&&(r.default=s)},AR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=tV(n.defaultValue,t,e,r,o);s!==IR&&(r._prefault=s)},TR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Wt(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},PR=(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;nt(s,e,o);let a=e.seen.get(t);a.ref=s},RR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},CR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},tS=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},OR=(t,e,r,o)=>{let n=t._zod.innerType;nt(n,e,o);let i=e.seen.get(t);i.ref=n},Q_={string:GP,number:XP,boolean:YP,bigint:QP,symbol:eR,null:tR,undefined:rR,void:nR,never:oR,any:iR,unknown:sR,date:aR,enum:cR,literal:uR,nan:lR,template_literal:dR,file:fR,success:pR,custom:mR,function:hR,transform:gR,map:yR,set:vR,array:wR,object:bR,union:eS,intersection:_R,tuple:SR,record:xR,nullable:ER,nonoptional:kR,default:$R,prefault:AR,catch:TR,pipe:PR,readonly:RR,promise:CR,optional:tS,lazy:OR};function yu(t,e){if("_idmap"in t){let o=t,n=Ea({...e,processors:Q_}),i={};for(let c of o._idmap.entries()){let[u,l]=c;nt(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;ka(n,l),ur(s,u,Ia(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=Ea({...e,processors:Q_});return nt(t,r),ka(r,t),Ia(r,t)}var rS=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=Ea({processors:Q_,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 nt(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,ka(this.ctx,e);let o=Ia(this.ctx,e),{"~standard":n,...i}=o;return i}};var rV={};var Nd={};vt(Nd,{ZodAny:()=>YR,ZodArray:()=>rC,ZodBase64:()=>_S,ZodBase64URL:()=>SS,ZodBigInt:()=>Cd,ZodBigIntFormat:()=>kS,ZodBoolean:()=>Rd,ZodCIDRv4:()=>wS,ZodCIDRv6:()=>bS,ZodCUID:()=>fS,ZodCUID2:()=>pS,ZodCatch:()=>_C,ZodCodec:()=>Th,ZodCreditCard:()=>KR,ZodCustom:()=>Ph,ZodCustomStringFormat:()=>wu,ZodDate:()=>Eh,ZodDefault:()=>hC,ZodDiscriminatedUnion:()=>oC,ZodE164:()=>xS,ZodEmail:()=>cS,ZodEmoji:()=>lS,ZodEnum:()=>Ad,ZodExactOptional:()=>AS,ZodFile:()=>dC,ZodFunction:()=>RC,ZodGUID:()=>uS,ZodIBAN:()=>WR,ZodIPv4:()=>yS,ZodIPv6:()=>vS,ZodISODate:()=>Aa,ZodISODateTime:()=>$a,ZodISODuration:()=>Pa,ZodISOTime:()=>Ta,ZodInstanceOf:()=>NC,ZodIntersection:()=>iC,ZodJWT:()=>ES,ZodKSUID:()=>gS,ZodLazy:()=>AC,ZodLiteral:()=>lC,ZodMAC:()=>ZR,ZodMap:()=>cC,ZodNaN:()=>xC,ZodNanoID:()=>dS,ZodNever:()=>eC,ZodNonOptional:()=>TS,ZodNull:()=>XR,ZodNullable:()=>mC,ZodNumber:()=>Pd,ZodNumberFormat:()=>bu,ZodObject:()=>kh,ZodOptional:()=>_u,ZodPipe:()=>Ah,ZodPrefault:()=>yC,ZodPreprocess:()=>EC,ZodPromise:()=>PC,ZodReadonly:()=>kC,ZodRecord:()=>$d,ZodSet:()=>uC,ZodString:()=>Td,ZodStringFormat:()=>at,ZodSuccess:()=>bC,ZodSymbol:()=>JR,ZodTemplateLiteral:()=>$C,ZodTransform:()=>fC,ZodTuple:()=>sC,ZodType:()=>ve,ZodULID:()=>mS,ZodURL:()=>Sh,ZodUUID:()=>Oi,ZodUndefined:()=>GR,ZodUnion:()=>Ih,ZodUnknown:()=>QR,ZodVoid:()=>tC,ZodXID:()=>hS,ZodXor:()=>nC,_ZodString:()=>aS,_default:()=>gC,_function:()=>lB,any:()=>qV,array:()=>Ae,base64:()=>kV,base64url:()=>IV,bigint:()=>LV,boolean:()=>Lt,catch:()=>SC,check:()=>dB,cidrv4:()=>xV,cidrv6:()=>EV,codec:()=>sB,creditCard:()=>AV,cuid:()=>hV,cuid2:()=>gV,currencyCode:()=>NV,custom:()=>PS,date:()=>KV,describe:()=>fB,discriminatedUnion:()=>$h,e164:()=>$V,email:()=>iV,emoji:()=>pV,enum:()=>fr,exactOptional:()=>pC,file:()=>rB,float32:()=>zV,float64:()=>jV,function:()=>lB,guid:()=>sV,hash:()=>DV,hex:()=>OV,hostname:()=>CV,httpUrl:()=>fV,iban:()=>TV,instanceof:()=>mB,int:()=>iS,int32:()=>MV,int64:()=>FV,intersection:()=>Od,invertCodec:()=>aB,ipv4:()=>bV,ipv6:()=>SV,json:()=>gB,jwt:()=>PV,keyof:()=>WV,ksuid:()=>wV,lazy:()=>TC,literal:()=>G,looseObject:()=>dr,looseRecord:()=>YV,mac:()=>_V,map:()=>QV,meta:()=>pB,nan:()=>iB,nanoid:()=>mV,nativeEnum:()=>tB,never:()=>IS,nonoptional:()=>wC,null:()=>xh,nullable:()=>_h,nullish:()=>nB,number:()=>We,object:()=>B,optional:()=>st,partialRecord:()=>XV,pipe:()=>sS,prefault:()=>vC,preprocess:()=>Rh,promise:()=>uB,readonly:()=>IC,record:()=>ct,refine:()=>CC,set:()=>eB,strictObject:()=>JV,string:()=>I,stringFormat:()=>RV,stringbool:()=>hB,success:()=>oB,superRefine:()=>OC,symbol:()=>BV,templateLiteral:()=>cB,transform:()=>$S,tuple:()=>aC,uint32:()=>UV,uint64:()=>VV,ulid:()=>yV,undefined:()=>HV,union:()=>ot,unknown:()=>ft,url:()=>dV,uuid:()=>aV,uuidv4:()=>cV,uuidv6:()=>uV,uuidv7:()=>lV,void:()=>ZV,xid:()=>vV,xor:()=>GV});var nS={};vt(nS,{endsWith:()=>gd,gt:()=>Ri,gte:()=>On,includes:()=>md,length:()=>gu,lowercase:()=>fd,lt:()=>Pi,lte:()=>Cn,maxLength:()=>hu,maxSize:()=>Sa,mime:()=>vd,minLength:()=>Ms,minSize:()=>Ci,multipleOf:()=>_a,negative:()=>V_,nonnegative:()=>H_,nonpositive:()=>B_,normalize:()=>wd,overwrite:()=>Mo,positive:()=>F_,properties:()=>yd,property:()=>q_,regex:()=>dd,size:()=>mu,slugify:()=>xd,startsWith:()=>hd,toLowerCase:()=>_d,toUpperCase:()=>Sd,trim:()=>bd,uppercase:()=>pd});var nV=new WeakSet([Object.prototype,Error.prototype]);function oS(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 oV=(t,e)=>{mT.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);nV.has(r)||(nV.add(r),oS(r,"format",o=>n=>Tm(o,n)),oS(r,"flatten",o=>n=>Am(o,n)),oS(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Fl,2)}),oS(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Fl,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},lfe=S("ZodError",oV),yn=S("ZodError",oV,void 0,{Parent:Error});var NR=Zl(yn),DR=Kl(yn),zR=Wl(yn),jR=Gl(yn),MR=Iw(yn),UR=$w(yn),LR=Aw(yn),FR=Tw(yn),VR=Pw(yn),BR=Rw(yn),HR=Cw(yn),qR=Ow(yn);function ffe(){Qt.localeError||Nt(l_())}function vu(){Qt.memoizer||Nt({memoizer:Zm()})}var ve=S("ZodType",(t,e)=>(ffe(),ae.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(A.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return Ke(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(CC(t,e))},superRefine(t,e){return this.check(OC(t,e))},overwrite(t){return this.check(Mo(t))},optional(){return st(this)},exactOptional(){return pC(this)},nullable(){return _h(this)},nullish(){return st(_h(this))},nonoptional(t){return wC(this,t)},array(){return Ae(this)},or(t){return ot([this,t])},and(t){return Od(this,t)},transform(t){return sS(this,$S(t))},default(t){return gC(this,t)},prefault(t){return vC(this,t)},catch(t){return SC(this,t)},pipe(t){return sS(this,t)},readonly(){return IC(this)},describe(t){let e=this.clone();return lr.add(e,{description:t}),e},meta(...t){if(t.length===0)return lr.get(this);let e=this.clone();return lr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return A.hide(this,"~standard",{...Hw(this),jsonSchema:{input:Ed(this,"input"),output:Ed(this,"output")}})},set"~standard"(t){A.own(this,"~standard",t)},parse:function t(e,r){return NR(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await DR(this,e,r,{callee:t})},safeParse(t,e){return zR(this,t,e)},async safeParseAsync(t,e){return jR(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){A.own(this,"spa",t)},validate(t,e){return Yl(this,t,e)},validateAsync(t,e){return Ql(this,t,e)},encode:function t(e,r){return MR(this,e,r,{callee:t})},decode:function t(e,r){return UR(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await LR(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await FR(this,e,r,{callee:t})},safeEncode(t,e){return VR(this,t,e)},safeDecode(t,e){return BR(this,t,e)},async safeEncodeAsync(t,e){return HR(this,t,e)},async safeDecodeAsync(t,e){return qR(this,t,e)},toJSONSchema(t){return KP(this,{})(t)},get description(){return lr.get(this)?.description},get _def(){return this._zod.def}}),aS=S("_ZodString",(t,e)=>{ba.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GP(t,r,o,n)},A.derived({format:t=>Jt(t).format??null,minLength:t=>Jt(t).minimum??null,maxLength:t=>Jt(t).maximum??null},{regex(...t){return this.check(dd(...t))},includes(...t){return this.check(md(...t))},startsWith(...t){return this.check(hd(...t))},endsWith(...t){return this.check(gd(...t))},min(...t){return this.check(Ms(...t))},max(...t){return this.check(hu(...t))},length(...t){return this.check(gu(...t))},nonempty(...t){return this.check(Ms(1,...t))},lowercase(t){return this.check(fd(t))},uppercase(t){return this.check(pd(t))},trim(){return this.check(bd())},normalize(...t){return this.check(wd(...t))},toLowerCase(){return this.check(_d())},toUpperCase(){return this.check(Sd())},slugify(){return this.check(xd())}})),Td=S("ZodString",(t,e)=>{ba.init(t,e),aS.init(t,e)},{email(t){return this.check(Wm(cS,t))},url(t){return this.check(ld(Sh,t))},jwt(t){return this.check(mh(ES,t))},emoji(t){return this.check(eh(lS,t))},guid(t){return this.check(Jm(uS,t))},uuid(t){return this.check(Gm(Oi,t))},uuidv4(t){return this.check(Xm(Oi,t))},uuidv6(t){return this.check(Ym(Oi,t))},uuidv7(t){return this.check(Qm(Oi,t))},nanoid(t){return this.check(th(dS,t))},cuid(t){return this.check(rh(fS,t))},cuid2(t){return this.check(nh(pS,t))},ulid(t){return this.check(oh(mS,t))},base64(t){return this.check(dh(_S,t))},base64url(t){return this.check(fh(SS,t))},xid(t){return this.check(ih(hS,t))},ksuid(t){return this.check(sh(gS,t))},ipv4(t){return this.check(ah(yS,t))},ipv6(t){return this.check(ch(vS,t))},cidrv4(t){return this.check(uh(wS,t))},cidrv6(t){return this.check(lh(bS,t))},e164(t){return this.check(ph(xS,t))},datetime(t){return this.check(hh($a,t))},date(t){return this.check(gh(Aa,t))},time(t){return this.check(yh(Ta,t))},duration(t){return this.check(vh(Pa,t))}});function I(t){return v_(Td,t)}var at=S("ZodStringFormat",(t,e)=>{Xe.init(t,e),aS.init(t,e)}),$a=S("ZodISODateTime",(t,e)=>{xP.init(t,e),at.init(t,e)}),Aa=S("ZodISODate",(t,e)=>{EP.init(t,e),at.init(t,e)}),Ta=S("ZodISOTime",(t,e)=>{kP.init(t,e),at.init(t,e)}),Pa=S("ZodISODuration",(t,e)=>{IP.init(t,e),at.init(t,e)}),cS=S("ZodEmail",(t,e)=>{Kw.init(t,e),at.init(t,e)});function iV(t){return Wm(cS,t)}var uS=S("ZodGUID",(t,e)=>{qw.init(t,e),at.init(t,e)});function sV(t){return Jm(uS,t)}var Oi=S("ZodUUID",(t,e)=>{Zw.init(t,e),at.init(t,e)});function aV(t){return Gm(Oi,t)}function cV(t){return Xm(Oi,t)}function uV(t){return Ym(Oi,t)}function lV(t){return Qm(Oi,t)}var Sh=S("ZodURL",(t,e)=>{Xw.init(t,e),at.init(t,e)});function dV(t){return ld(Sh,t)}function fV(t){return ld(Sh,{protocol:Pm,hostname:jT,...A.normalizeParams(t)})}var lS=S("ZodEmoji",(t,e)=>{Yw.init(t,e),at.init(t,e)});function pV(t){return eh(lS,t)}var dS=S("ZodNanoID",(t,e)=>{Qw.init(t,e),at.init(t,e)});function mV(t){return th(dS,t)}var fS=S("ZodCUID",(t,e)=>{eb.init(t,e),at.init(t,e)});function hV(t){return rh(fS,t)}var pS=S("ZodCUID2",(t,e)=>{tb.init(t,e),at.init(t,e)});function gV(t){return nh(pS,t)}var mS=S("ZodULID",(t,e)=>{rb.init(t,e),at.init(t,e)});function yV(t){return oh(mS,t)}var hS=S("ZodXID",(t,e)=>{nb.init(t,e),at.init(t,e)});function vV(t){return ih(hS,t)}var gS=S("ZodKSUID",(t,e)=>{ob.init(t,e),at.init(t,e)});function wV(t){return sh(gS,t)}var yS=S("ZodIPv4",(t,e)=>{ib.init(t,e),at.init(t,e)});function bV(t){return ah(yS,t)}var ZR=S("ZodMAC",(t,e)=>{ab.init(t,e),at.init(t,e)});function _V(t){return w_(ZR,t)}var vS=S("ZodIPv6",(t,e)=>{sb.init(t,e),at.init(t,e)});function SV(t){return ch(vS,t)}var wS=S("ZodCIDRv4",(t,e)=>{cb.init(t,e),at.init(t,e)});function xV(t){return uh(wS,t)}var bS=S("ZodCIDRv6",(t,e)=>{lb.init(t,e),at.init(t,e)});function EV(t){return lh(bS,t)}var _S=S("ZodBase64",(t,e)=>{fb.init(t,e),at.init(t,e)});function kV(t){return dh(_S,t)}var SS=S("ZodBase64URL",(t,e)=>{mb.init(t,e),at.init(t,e)});function IV(t){return fh(SS,t)}var xS=S("ZodE164",(t,e)=>{hb.init(t,e),at.init(t,e)});function $V(t){return ph(xS,t)}var KR=S("ZodCreditCard",(t,e)=>{yb.init(t,e),at.init(t,e)});function AV(t){return b_(KR,t)}var WR=S("ZodIBAN",(t,e)=>{wb.init(t,e),at.init(t,e)});function TV(t){return __(WR,t)}var ES=S("ZodJWT",(t,e)=>{_b.init(t,e),at.init(t,e)});function PV(t){return mh(ES,t)}var wu=S("ZodCustomStringFormat",(t,e)=>{Sb.init(t,e),at.init(t,e)});function RV(t,e,r={}){return xa(wu,t,e,r)}function CV(t){return xa(wu,"hostname",zT,t)}function OV(t){return xa(wu,"hex",XT,t)}function NV(t){return xa(wu,"currency_code",UT,t)}function DV(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Rn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return xa(wu,o,n,e)}var Pd=S("ZodNumber",(t,e)=>{Um.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XP(t,r,o,n),t.isFinite=!0},A.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Jt(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Jt(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Jt(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Jt(t).format??null},{gt(t,e){return this.check(Ri(t,e))},gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},lt(t,e){return this.check(Pi(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},int(t){return this.check(iS(t))},safe(t){return this.check(iS(t))},positive(t){return this.check(Ri(0,t))},nonnegative(t){return this.check(On(0,t))},negative(t){return this.check(Pi(0,t))},nonpositive(t){return this.check(Cn(0,t))},multipleOf(t,e){return this.check(_a(t,e))},step(t,e){return this.check(_a(t,e))},finite(){return this}}));function We(t){return S_(Pd,t)}var bu=S("ZodNumberFormat",(t,e)=>{xb.init(t,e),Pd.init(t,e)});function iS(t){return x_(bu,t)}function zV(t){return E_(bu,t)}function jV(t){return k_(bu,t)}function MV(t){return I_(bu,t)}function UV(t){return $_(bu,t)}var Rd=S("ZodBoolean",(t,e)=>{rd.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YP(t,r,o,n)});function Lt(t){return A_(Rd,t)}var Cd=S("ZodBigInt",(t,e)=>{Lm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QP(t,r,o,n)},A.derived({minValue:t=>Jt(t).minimum??null,maxValue:t=>Jt(t).maximum??null,format:t=>Jt(t).format??null},{gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},gt(t,e){return this.check(Ri(t,e))},lt(t,e){return this.check(Pi(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},positive(t){return this.check(Ri(BigInt(0),t))},negative(t){return this.check(Pi(BigInt(0),t))},nonpositive(t){return this.check(Cn(BigInt(0),t))},nonnegative(t){return this.check(On(BigInt(0),t))},multipleOf(t,e){return this.check(_a(t,e))}}));function LV(t){return T_(Cd,t)}var kS=S("ZodBigIntFormat",(t,e)=>{Eb.init(t,e),Cd.init(t,e)});function FV(t){return P_(kS,t)}function VV(t){return R_(kS,t)}var JR=S("ZodSymbol",(t,e)=>{kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eR(t,r,o,n)});function BV(t){return C_(JR,t)}var GR=S("ZodUndefined",(t,e)=>{Ib.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rR(t,r,o,n)});function HV(t){return O_(GR,t)}var XR=S("ZodNull",(t,e)=>{$b.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tR(t,r,o,n)});function xh(t){return N_(XR,t)}var YR=S("ZodAny",(t,e)=>{Ab.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iR(t,r,o,n)});function qV(){return D_(YR)}var QR=S("ZodUnknown",(t,e)=>{Tb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sR(t,r,o,n)});function ft(){return z_(QR)}var eC=S("ZodNever",(t,e)=>{Pb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oR(t,r,o,n)});function IS(t){return j_(eC,t)}var tC=S("ZodVoid",(t,e)=>{Rb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nR(t,r,o,n)});function ZV(t){return M_(tC,t)}var Eh=S("ZodDate",(t,e)=>{Cb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aR(t,r,o,n),t.min=(r,o)=>t.check(On(r,o)),t.max=(r,o)=>t.check(Cn(r,o))},A.derived({minDate:t=>{let{minimum:e}=Jt(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Jt(t);return e?new Date(e):null}},{}));function KV(t){return U_(Eh,t)}var rC=S("ZodArray",(t,e)=>{vu(),Ob.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wR(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ms(t,e))},nonempty(t){return this.check(Ms(1,t))},max(t,e){return this.check(hu(t,e))},length(t,e){return this.check(gu(t,e))},unwrap(){return this.element}});function Ae(t,e){return qP(rC,t,e)}function WV(t){let e=t._zod.def.shape;return fr(Object.keys(e))}var kh=S("ZodObject",(t,e)=>{vu(),$P.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bR(t,r,o,n),A.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return fr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(A.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ft()}))},loose(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ft()}))},strict(){return this.clone(A.mergeDefs(this._zod.def,{catchall:IS()}))},strip(){return this.clone(A.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return A.extend(this,t)},safeExtend(t){return A.safeExtend(this,t)},merge(t){return A.merge(this,t)},pick(t){return A.pick(this,t)},omit(t){return A.omit(this,t)},partial(...t){return A.partial(_u,this,t[0])},exactPartial(...t){return A.partial(AS,this,t[0],"exactPartial")},required(...t){return A.required(TS,this,t[0])}});function B(t,e){let r={type:"object",shape:t??{},...A.normalizeParams(e)};return new kh(r)}function JV(t,e){return new kh({type:"object",shape:t,catchall:IS(),...A.normalizeParams(e)})}function dr(t,e){return new kh({type:"object",shape:t,catchall:ft(),...A.normalizeParams(e)})}var Ih=S("ZodUnion",(t,e)=>{nd.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eS(t,r,o,n),t.options=e.options});function ot(t,e){return new Ih({type:"union",options:t,...A.normalizeParams(e)})}var nC=S("ZodXor",(t,e)=>{Ih.init(t,e),Db.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eS(t,r,o,n),t.options=e.options});function GV(t,e){return new nC({type:"union",options:t,inclusive:!1,...A.normalizeParams(e)})}var oC=S("ZodDiscriminatedUnion",(t,e)=>{Ih.init(t,e),zb.init(t,e)});function $h(t,e,r){return new oC({type:"union",options:e,discriminator:t,...A.normalizeParams(r)})}var iC=S("ZodIntersection",(t,e)=>{jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_R(t,r,o,n)});function Od(t,e){return new iC({type:"intersection",left:t,right:e})}var sC=S("ZodTuple",(t,e)=>{vu(),Fm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SR(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 _u({type:"optional",innerType:e}))})}});function aC(t,e,r){let o=e instanceof ae,n=o?r:e,i=o?e:null;return new sC({type:"tuple",items:t,rest:i,...A.normalizeParams(n)})}var $d=S("ZodRecord",(t,e)=>{vu(),Mb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function ct(t,e,r){return!e||!e._zod?new $d({type:"record",keyType:I(),valueType:t,...A.normalizeParams(e)}):new $d({type:"record",keyType:t,valueType:e,...A.normalizeParams(r)})}function XV(t,e,r){return new $d({type:"record",keyType:t,valueType:e,...A.normalizeParams(r),partial:!0})}function YV(t,e,r){return new $d({type:"record",keyType:t,valueType:e,mode:"loose",...A.normalizeParams(r)})}var cC=S("ZodMap",(t,e)=>{vu(),Ub.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ci(...r)),t.nonempty=r=>t.check(Ci(1,r)),t.max=(...r)=>t.check(Sa(...r)),t.size=(...r)=>t.check(mu(...r))});function QV(t,e,r){return new cC({type:"map",keyType:t,valueType:e,...A.normalizeParams(r)})}var uC=S("ZodSet",(t,e)=>{vu(),Lb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vR(t,r,o,n),t.min=(...r)=>t.check(Ci(...r)),t.nonempty=r=>t.check(Ci(1,r)),t.max=(...r)=>t.check(Sa(...r)),t.size=(...r)=>t.check(mu(...r))});function eB(t,e){return new uC({type:"set",valueType:t,...A.normalizeParams(e)})}var Ad=S("ZodEnum",(t,e)=>{Fb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(o,n,i)=>cR(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 Ad({...e,checks:[],...A.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Ad({...e,checks:[],...A.normalizeParams(n),entries:i})}});function fr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Ad({type:"enum",entries:r,...A.normalizeParams(e)})}function tB(t,e){return new Ad({type:"enum",entries:t,...A.normalizeParams(e)})}var lC=S("ZodLiteral",(t,e)=>{Vb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uR(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function G(t,e){return new lC({type:"literal",values:Array.isArray(t)?t:[t],...A.normalizeParams(e)})}var dC=S("ZodFile",(t,e)=>{Bb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fR(t,r,o,n),t.min=(r,o)=>t.check(Ci(r,o)),t.max=(r,o)=>t.check(Sa(r,o)),t.mime=(r,o)=>t.check(vd(Array.isArray(r)?r:[r],o))});function rB(t){return Z_(dC,t)}var fC=S("ZodTransform",(t,e)=>{vu(),Hb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gR(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new wa(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(A.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(A.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function $S(t){return new fC({type:"transform",transform:t})}var _u=S("ZodOptional",(t,e)=>{Vm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tS(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function st(t){return new _u({type:"optional",innerType:t})}var AS=S("ZodExactOptional",(t,e)=>{qb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tS(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pC(t){return new AS({type:"optional",innerType:t})}var mC=S("ZodNullable",(t,e)=>{Zb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ER(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function _h(t){return new mC({type:"nullable",innerType:t})}function nB(t){return st(_h(t))}var hC=S("ZodDefault",(t,e)=>{Kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function gC(t,e){return new hC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var yC=S("ZodPrefault",(t,e)=>{Wb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function vC(t,e){return new yC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var TS=S("ZodNonOptional",(t,e)=>{Jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wC(t,e){return new TS({type:"nonoptional",innerType:t,...A.normalizeParams(e)})}var bC=S("ZodSuccess",(t,e)=>{Gb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function oB(t){return new bC({type:"success",innerType:t})}var _C=S("ZodCatch",(t,e)=>{Xb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function SC(t,e){return new _C({type:"catch",innerType:t,catchValue:typeof e=="function"?e:A.constantCatch(e)})}var xC=S("ZodNaN",(t,e)=>{Yb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lR(t,r,o,n)});function iB(t){return L_(xC,t)}var Ah=S("ZodPipe",(t,e)=>{Bm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PR(t,r,o,n),t.in=e.in,t.out=e.out});function sS(t,e){return new Ah({type:"pipe",in:t,out:e})}var Th=S("ZodCodec",(t,e)=>{Ah.init(t,e),od.init(t,e)});function sB(t,e,r){return new Th({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function aB(t){let e=t._zod.def;return new Th({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var EC=S("ZodPreprocess",(t,e)=>{Ah.init(t,e),TP.init(t,e)}),kC=S("ZodReadonly",(t,e)=>{Qb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function IC(t){return new kC({type:"readonly",innerType:t})}var $C=S("ZodTemplateLiteral",(t,e)=>{e_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dR(t,r,o,n)});function cB(t,e){return new $C({type:"template_literal",parts:t,...A.normalizeParams(e)})}var AC=S("ZodLazy",(t,e)=>{id.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OR(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function TC(t){return new AC({type:"lazy",getter:t})}var PC=S("ZodPromise",(t,e)=>{r_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function uB(t){return new PC({type:"promise",innerType:t})}var RC=S("ZodFunction",(t,e)=>{t_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hR(t,r,o,n)});function lB(t){return new RC({type:"function",input:Array.isArray(t?.input)?aC(t?.input):t?.input??Ae(ft()),output:t?.output??ft()})}var Ph=S("ZodCustom",(t,e)=>{n_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mR(t,r,o,n)});function dB(t){let e=new it({check:"custom"});return e._zod.check=t,e}function PS(t,e){return K_(Ph,t??(()=>!0),e)}function CC(t,e={}){return W_(Ph,t,e)}function OC(t,e){return J_(t,e)}var fB=G_,pB=X_,NC=S("ZodInstanceOf",(t,e)=>{Ph.init(t,e)},{properties(t,e){return this.check(yd(t,e))}});function mB(t,e={}){let r=new NC({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...A.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var hB=(...t)=>Y_({Codec:Th,Boolean:Rd,String:Td},...t);function gB(t){let e=TC(()=>ot([I(t),We(),Lt(),xh(),Ae(e),ct(I(),e)]));return e}function Rh(t,e){return new EC({type:"pipe",in:$S(t),out:e})}var pfe={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 mfe(t){Nt({customError:t})}function hfe(){return Nt().customError}var DC;DC||(DC={});var Su={};vt(Su,{ZodISODate:()=>Aa,ZodISODateTime:()=>$a,ZodISODuration:()=>Pa,ZodISOTime:()=>Ta,date:()=>yfe,datetime:()=>gfe,duration:()=>wfe,time:()=>vfe});function gfe(t){return hh($a,t)}function yfe(t){return gh(Aa,t)}function vfe(t){return yh(Ta,t)}function wfe(t){return vh(Pa,t)}var V={...Nd,...nS,iso:Su},bfe=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 _fe(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 yB(t,e){return t.map((r,o)=>o<e?r:r.optional())}function Sfe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function xfe(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:Sfe(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 Efe(t,e){return V.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function zC(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=zC(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=zC(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 kfe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),Ife=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Ch(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(Ch):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>kfe.has(e)?Ch(r):!Ife.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(Ch))}function vB(t){return t===1?"element":"elements"}function $fe(t,e){return V.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=zC(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 ${vB(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 ${vB(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function wB(t,e){if(t!==!1)return t===void 0||t===!0?V.any():en(t,e)}var Afe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function bB(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return V.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return V.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=xfe(n,e),s=en(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return V.null();if(n.length===0)return V.never();if(n.length===1)return V.literal(n[0]);if(n.every(s=>typeof s=="string"))return V.enum(n);let i=n.map(s=>V.literal(s));return i.length<2?i[0]:V.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return V.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return bB(s,e)});return n.length===0?V.never():n.length===1?n[0]:V.union(n)}if(!r)return V.any();let o;switch(r){case"string":{let n=V.string();if(t.format){let i=t.format;i==="email"?n=n.check(V.email()):i==="uri"||i==="uri-reference"?n=n.check(V.url()):i==="uuid"||i==="guid"?n=n.check(V.uuid()):i==="date-time"?n=n.check(V.iso.datetime({offset:!0})):i==="date"?n=n.check(V.iso.date()):i==="time"?n=n.check(V.regex(Afe)):i==="duration"?n=n.check(V.iso.duration()):i==="hostname"?n=n.check(V.hostname()):i==="ipv4"?n=n.check(V.ipv4()):i==="ipv6"?n=n.check(V.ipv6()):i==="mac"?n=n.check(V.mac()):i==="cidr"?n=n.check(V.cidrv4()):i==="cidr-v6"?n=n.check(V.cidrv6()):i==="base64"?n=n.check(V.base64()):i==="base64url"?n=n.check(V.base64url()):i==="e164"?n=n.check(V.e164()):i==="credit_card"?n=n.check(V.creditCard()):i==="iban"?n=n.check(V.iban()):i==="jwt"?n=n.check(V.jwt()):i==="emoji"?n=n.check(V.emoji()):i==="nanoid"?n=n.check(V.nanoid()):i==="cuid"?n=n.check(V.cuid()):i==="cuid2"?n=n.check(V.cuid2()):i==="ulid"?n=n.check(V.ulid()):i==="xid"?n=n.check(V.xid()):i==="ksuid"&&(n=n.check(V.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?V.number().int():V.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=V.boolean();break}case"null":{o=V.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?en(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=en(p,e);ur(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let h of p){let y=en(d[h],e),w=V.string().regex(new RegExp(h));f.push(V.looseRecord(w,y))}let m=[];if(Object.keys(n).length>0&&m.push(V.object(n).passthrough()),m.push(...f),m.length===0)o=V.object({}).passthrough();else if(m.length===1)o=m[0];else{let h=V.intersection(m[0],m[1]);for(let y=2;y<m.length;y++)h=V.intersection(h,m[y]);o=h}if(t.additionalProperties===!1){let h=Object.keys(n),y=p.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!Yn(b.value))return;let _=[];for(let x of Object.keys(b.value))h.includes(x)||y.some($=>$.test(x))||_.push(x);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=V.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=en(p,e)}o=Efe(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=>en(d,e)),c=yB(a,s),u=Array.isArray(i)?void 0:wB(i,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>en(d,e)),c=yB(a,s),u=wB(t.additionalItems,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(i!==void 0){let s=en(i,e),a=V.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=V.array(V.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=$fe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?en(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 en(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r=bB(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=>en(u,e)),c=V.union(a);r=o?V.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>en(u,e)),c=V.xor(a);r=o?V.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:V.any();else{let a=o?r:en(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=V.intersection(a,en(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=V.nullable(r)),t.readOnly===!0&&(r=V.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!Ch(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&&!Ch(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))bfe.has(a)||ur(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function _B(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=_fe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??lr};return en(r,i)}var SB=Symbol("z.visit/resolving");function Oh(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===SB)return new id({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,SB);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let h=n(u[m]);h!==u[m]&&(d=!0),p[m]=h}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?Ke(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:Ke(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?Ke(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:Ke(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:Ke(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?Ke(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:Ke(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:Ke(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:Ke(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:Ke(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return Ke(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 xB(t){return Oh(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:ot(r.options)}})}function Tfe(t,e){if(!e?.length)return t;let r=t._zod.def;return Ke(t,Xn(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function EB(t){return Tfe(t.out,t.checks)}function Pfe(t){return t.in._zod.traits.has("$ZodTransform")?EB(t):t.in}function kB(t){return Oh(t,{pipe:e=>Pfe(e._zod.def),default:(e,r)=>r?st(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function IB(t){return Oh(t,{pipe:e=>EB(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var jC={};vt(jC,{bigint:()=>Nfe,boolean:()=>Ofe,date:()=>Dfe,number:()=>Cfe,string:()=>Rfe});function Rfe(t){return UP(Td,t)}function Cfe(t){return FP(Pd,t)}function Ofe(t){return VP(Rd,t)}function Nfe(t){return BP(Cd,t)}function Dfe(t){return HP(Eh,t)}var Nh={name:"@tomato414941/foundation",version:"3.2.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};var Dd=new TextEncoder,zd=new TextDecoder,$B=new TextDecoder("utf-8",{fatal:!0}),RS=2**32;function tn(...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 MC(t,e,r){if(e<0||e>=RS)throw new RangeError(`value must be >= 0 and <= ${RS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function UC(t){let e=Math.floor(t/RS),r=t%RS,o=new Uint8Array(8);return MC(o,e,0),MC(o,r,4),o}function CS(t){let e=new Uint8Array(4);return MC(e,t),e}var jfe=/[^\x00-\x7f]/;function pr(t){if(typeof t=="string"&&t.length>=128){if(jfe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return Dd.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 AB(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 TB(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 OS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Us=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 xu=class extends Us{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},ut=class extends Us{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ra=class extends Us{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},M=class extends Us{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},xt=class extends Us{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var Dh=class extends Us{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var NS=class extends Us{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var Mfe="The input to be decoded is not correctly encoded.";function Eu(t){try{return TB(typeof t=="string"?t:zd.decode(t),!0)}catch(e){throw new TypeError(Mfe,{cause:e})}}function Tt(t){return AB(typeof t=="string"?Dd.encode(t):t,!0)}function Nn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Bt(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 Ca(...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 eo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function vn(t,e,r){try{return Eu(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function DS(t,e,r){try{return pr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function jd(t,e,r){let o;try{o=JSON.parse($B.decode(Eu(t)))}catch{throw new e(r)}if(!Bt(o))throw new e(r);return o}var zS={__proto__:null,b64:!0},jS={__proto__:null};function zh(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function MS(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Oa(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 ut(`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 US(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function ku(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(!Bt(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var Ufe=t=>t[Symbol.toStringTag],Lfe=(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 Lo(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(Bt(e)){if(s=qC(e),typeof s.kty!="string")throw PB(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(Lfe(t,s,r),s.kty==="oct")return Eu(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!VC(e))throw PB(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${Ufe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Na(e))return e;if(a=e,a.type==="secret")return a.export()}LC||=new WeakMap;let c=e,u=LC.get(c);if(u?.[o])return u[o];if(u||LC.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Ffe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await Ud(t,s)}var LC,Ffe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function FS(t){if(!Na(t))throw new Error("CryptoKey instance expected")}var Na=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},FC=t=>t?.[Symbol.toStringTag]==="KeyObject",VC=t=>Na(t)||FC(t);function RB(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 Ls=(t,...e)=>RB("Key must be ",t,...e);function PB(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(RB(`Key for the ${t} algorithm must be `,e,...o))}var LS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function BC(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Md(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 HC(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw LS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw LS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw LS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw LS(e.length,"algorithm.length");BC(t,r)}function VS(t){return{__proto__:null,...t}}function qC(t){let e=VS(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function BS(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function Ud(t,e,r){if(!t.kty.includes(e.kty))throw new ut('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 Fo(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),HC(t,e,r),t}var Iu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function HS(t,e){let r=t.byteLength<<3;if(r!==e)throw new M(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var Vfe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function CB(t,e){if(e.length<<3!==t.ivBits)throw new M("Invalid Initialization Vector length")}async function OB(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Ls(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 NB(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Bfe(t,e,r,o,n){let[i,s,a]=await OB(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=tn(n,o,c,UC(n.length*8)),l=await NB(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Hfe(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 qfe(t,e,r,o,n,i){let[s,a,c]=await OB(t,e,"decrypt"),u=tn(i,o,r,UC(i.length*8)),l=await NB(a,u,c);try{if(await Hfe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Ra}async function qS(t,e,r,o,n){if(!Na(r)&&!(r instanceof Uint8Array))throw new TypeError(Ls(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?CB(t,o):o=Vfe(t),r instanceof Uint8Array&&HS(r,t.cekBits),t.cbc)return Bfe(t,e,r,o,n);let i=await Fo(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 ZS(t,e,r,o,n,i){if(!Na(e)&&!(e instanceof Uint8Array))throw new TypeError(Ls(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new M("JWE Initialization Vector missing");if(!n)throw new M("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new M("Invalid Authentication Tag length");if(CB(t,o),e instanceof Uint8Array&&HS(e,t.cekBits),t.cbc)return qfe(t,e,r,o,n,i);let s=await Fo(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,tn(r,n)))}catch{throw new Ra}}function jh(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var Zfe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Kfe=[[],["deriveBits"]],JS=[[],[]];function KS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:Zfe,ops:["wrapKey","unwrapKey"]}}function WS(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 ut('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Kfe,ops:[void 0,"deriveBits"]}}function Ld(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:JS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function ZC(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:JS,ops:["deriveBits","deriveBits"]}}var Fs=jh({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:JS,ops:["encrypt","decrypt"]},"RSA-OAEP":KS(1),"RSA-OAEP-256":KS(256),"RSA-OAEP-384":KS(384),"RSA-OAEP-512":KS(512),"ECDH-ES":WS("direct-key-agreement"),"ECDH-ES+A128KW":WS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":WS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":WS("key-agreement-with-key-wrapping"),A128KW:Ld(128),A192KW:Ld(192),A256KW:Ld(256),A128GCMKW:Ld(128,!0),A192GCMKW:Ld(192,!0),A256GCMKW:Ld(256,!0),"PBES2-HS256+A128KW":ZC(),"PBES2-HS384+A192KW":ZC(),"PBES2-HS512+A256KW":ZC()}),Wfe=["encrypt","decrypt"];function Fd(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:JS,ops:Wfe,cekBits:t,ivBits:e?128:96,cbc:e}}var Jfe=jh({A128GCM:Fd(128),A192GCM:Fd(192),A256GCM:Fd(256),"A128CBC-HS256":Fd(256,!0),"A192CBC-HS384":Fd(384,!0),"A256CBC-HS512":Fd(512,!0)});function DB(t,e){throw new ut(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Vo(t){return(typeof t=="string"?Fs[t]:void 0)??DB("alg","Algorithm")}function Bo(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function $u(t){return(typeof t=="string"?Jfe[t]:void 0)??DB("enc","Encryption Algorithm")}function zB(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");BC(t,e)}async function Gfe(t,e,r){let o=await Fo(e,Vo(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 Xfe(t,e,r){let o=await Fo(e,Vo(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 MB(t,e,r){HC(e,Vo(t).subtle,r),Md(t,e)}async function UB(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new M("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new M("PBES2 Count Input must be a positive integer");let n=tn(pr(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 Fo(o,Vo(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KC(t){return tn(CS(t.length),t)}async function Yfe(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 OS("sha256",tn(CS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function LB(t,e,r,o,n=new Uint8Array,i=new Uint8Array){zB(t),zB(e,"deriveBits");let s=tn(KC(pr(r)),KC(n),KC(i),CS(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return Yfe(a,o,s)}function FB(t){FS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new ut("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function GS(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new M(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return vn(r,e,M)}}function VB(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 M('JOSE Header "apu" and "apv" values must be distinct')}}function Qfe(t){if(t===void 0)throw new M("JWE Encrypted Key missing")}function jB(t){if(t!==void 0)throw new M("Encountered unexpected JWE Encrypted Key")}function epe(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 BB(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return jB(o),r;let c=a==="direct-key-agreement";switch(c?jB(o):Qfe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Bt(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new M('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');FB(r);let l=await Ud(t,u),d=GS(n,"apu"),p=GS(n,"apv");VB(d,p);let f=await LB(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return FS(r),MB(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new M('JOSE Header "p2c" (PBES2 Count) missing or invalid');epe(i);let u=i??1e4;if(n.p2c>u)throw new M('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new M('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=vn(n.p2s,"p2s",M);r=await UB(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new M('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new M('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=vn(n.iv,"iv",M),l=vn(n.tag,"tag",M);if(u.byteLength!==12)throw new M("Invalid Initialization Vector length");if(l.byteLength!==16)throw new M("Invalid Authentication Tag length");return ZS($u(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Xfe(s.slice(-6),r,o)}async function XS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Bo(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Lo(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Iu(e):void 0;l&&HS(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{FB(u);let{apu:f,apv:m}=i;f!==void 0&&Nn(f,'"apu"'),m!==void 0&&Nn(m,'"apv"');let h=f??GS(o,"apu"),y=m??GS(o,"apv");VB(h,y);let w;i.epk!==void 0?w=await Lo(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,y:$,crv:O,kty:H}=await b.exportKey("jwk",_),te=a==="direct-key-agreement",Ie=await LB(u,w,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),h,y),xe={x,crv:O,kty:H};if(H==="EC"&&(xe.y=$),p={epk:xe},f!==void 0&&(p.apu=Tt(f)),m!==void 0&&(p.apv=Tt(m)),te)return[Ie,void 0,p];u=Ie;break}case"RSA-OAEP":{FS(u),MB(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await UB(m,s,f,u),p={p2c:f,p2s:Tt(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await qS($u(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:Tt(m.iv),tag:Tt(m.tag)}}}if(d??=await Gfe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function YS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new ut('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new M('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function HB(t){if(typeof globalThis[t]>"u")throw new ut(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function qB(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 M("Decompressed plaintext exceeded the configured limit")}return tn(...n)}async function ZB(t){return HB("CompressionStream"),qB(new CompressionStream("deflate-raw"),t)}async function KB(t,e){return HB("DecompressionStream"),qB(new DecompressionStream("deflate-raw"),t,e)}function WB(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 M("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new M("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new M("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new M("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new M("JWE AAD incorrect type");if(s!==void 0&&!Bt(s))throw new M("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 JB(t){let e,r;try{let{header:o}=t;if(Bt(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 GB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new M("JWE Encrypted Key incorrect type");if(r!==void 0&&!Bt(r))throw new M("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new M("JOSE Header missing")}function WC(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=jd(e,M,"JWE Protected Header is invalid")),[s,vn(r,"ciphertext",M),o!==void 0?vn(o,"iv",M):void 0,n!==void 0?vn(n,"tag",M):void 0,DS((e??"")+(i!==void 0?`.${i}`:""),"aad",M)]}function QS(t){return[t&&zh("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&zh("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function JC(t,e,r,o=WC(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Ca(n,u,l))throw new M("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,h,y,w]=e,{encrypted_key:b}=t;Oa(M,jS,h,n,p),YS(p,n);let{alg:_,enc:x}=p;if(typeof _!="string"||!_)throw new M("missing JWE Algorithm (alg) in JWE Header");let $=Fs[_];if(b===""&&(!$||!Bo($)))throw new M("JWE Encrypted Key incorrect type");let O=$?.mode==="integrated-encryption";if(!O&&(typeof x!="string"||!x))throw new M("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(_)||!f&&_.startsWith("PBES2"))throw new xu('"alg" (Algorithm) Header Parameter value not allowed');let H;if(O){if(x!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new M("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new M("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(x))throw new xu('"enc" (Encryption Algorithm) Header Parameter value not allowed');H=$u(x)}let te;if(b!==void 0)try{te=vn(b,"encrypted_key",M)}catch($e){if(!$||!Bo($))throw $e;te=new Uint8Array}let Ie=!1;typeof r=="function"&&(r=await r(n,t),Ie=!0);let xe=$??Vo(_);Bo(xe)&&te===void 0&&(te=new Uint8Array);let rt=await Lo(xe.mode==="direct-encryption"?H:xe,r,"decrypt"),Ve;if(xe.mode==="integrated-encryption")Ve=await xe.decrypt(rt,te,i,c,n,p);else{let $e=H,J;try{J=await BB(xe,$e,rt,te,p,y),Bo(xe)&&J instanceof Uint8Array&&J.byteLength<<3!==$e.cekBits&&(J=Iu($e))}catch($t){if($t instanceof TypeError||$t instanceof M||$t instanceof ut)throw $t;J=Iu($e)}Ve=await ZS($e,J,i,s,a,c)}if(p.zip==="DEF"){let $e=w??25e4;if($e===0)throw new ut('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if($e!==1/0&&(!Number.isSafeInteger($e)||$e<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");Ve=await KB(Ve,$e).catch(J=>{throw J instanceof M?J:new M("Failed to decompress plaintext",{cause:J})})}return{plaintext:Ve,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:vn(d,"aad",M)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ie&&{key:rt}}}async function XB(t,e,r){if(t instanceof Uint8Array&&(t=zd.decode(t)),typeof t!="string")throw new M("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 M("Invalid Compact JWE");return JC({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Mh(t,e,r){return XB(t,QS(r),e)}async function GC(t,e,r){if(!Bt(t))throw new M("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new M("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Bt))throw new M("JWE Recipients missing or incorrect type");if(!n.length)throw new M("JWE Recipients has no members");let i,s,a;try{i=QS(r),s=WB(t),a=WC(s)}catch{throw new Ra}let c=n.map(u=>JB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Fs[l]:void 0;if(d&&!Bo(d))throw new M(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return GB(l),await JC(l,i,e,a)}catch{}throw new Ra}function ex(t,e,r){if(!Ca(t,e,r))throw new M("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function XC(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new M("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&&Nn(s,"JWE Additional Authenticated Data"),a!==void 0&&Nn(a,"JWE Content Encryption Key"),c!==void 0&&Nn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=ku(M,o)[0],t[1]=o),n!==void 0&&(n=ku(M,n)[0],t[2]=n),!r&&i!==void 0&&(i=ku(M,i)[0],t[3]=i),u!==void 0&&!Bt(u))throw new TypeError("JWE Key Management Parameters must be an object");ex(o,n,i);let d={...o,...n,...i};MS(M,o),Oa(M,jS,l,o,d),YS(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new M('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Fs[p];if(m?.mode==="integrated-encryption"){if(f!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,$u(f),m]}async function YC(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,m]=t,h=a,y=c,w=i??Vo(o.alg),b,_,x;w.mode==="integrated-encryption"?x=await Lo(w,r,"encrypt"):[x,b,_]=await XS(w,n,r,o,d,f),_&&(m?y=y?{...y,..._}:_:h=h?{...h,..._}:_,ex(h,y,u));let $=h?Tt(JSON.stringify(h)):"",O=l?.byteLength?Tt(l):void 0,H=pr(O?`${$}.${O}`:$),te=s;o.zip==="DEF"&&(te=await ZB(te).catch($e=>{throw new M("Failed to compress plaintext",{cause:$e})}));let Ie,xe,rt;w.mode==="integrated-encryption"?[b,Ie]=await w.encrypt(x,te,H,h,o,f):{ciphertext:Ie,tag:xe,iv:rt}=await qS(n,te,x,p,H);let Ve={ciphertext:Tt(Ie)};return rt&&(Ve.iv=Tt(rt)),xe&&(Ve.tag=Tt(xe)),b?.byteLength&&(Ve.encrypted_key=Tt(b)),O&&(Ve.aad=O),h&&(Ve.protected=$),u&&(Ve.unprotected=u),y&&(Ve.header=y),Ve}async function YB(t,e,r){return YC(t,XC(t,r),e)}function QB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var QC=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return eo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return eo(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}},Uh=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new QC(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return eo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return eo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new M("at least one recipient must be added");Nn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[h,y,w,b]=m.state,_=[this.#e,o,h,n,this.#o,void 0,void 0,y,b,e],x=XC(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,x,w]);let[{alg:$,enc:O},,H]=x;if(e&&H&&!Bo(H))throw new M(`"${$}" alg may only have a single recipient`);if(!r)r=O;else if(r!==O)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Vo(m[0].alg);let[s,a,c]=i[0],u=e?Iu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await YC(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[h,[y,w,b],_]=i[m],x=h[2],[,$,O]=await XS(b,w,_,y,u,h[7]),H={encrypted_key:Tt($)};if(x||O){let te={...x,...O};O&&ex(h[1],te,h[3]),H.header=te}f.recipients.push(H)}return f}};var Lh=[["verify"],["sign"]];function eO(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Lh}}function Vd(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:Lh,minRsaBits:2048}}function tO(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Lh}}function eH(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Lh}}function rO(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Lh}}var nO=jh({HS256:eO(256),HS384:eO(384),HS512:eO(512),RS256:Vd(256),RS384:Vd(384),RS512:Vd(512),PS256:Vd(256,32),PS384:Vd(384,48),PS512:Vd(512,64),ES256:tO("P-256",256),ES384:tO("P-384",384),ES512:tO("P-521",512),EdDSA:eH(),Ed25519:eH(),"ML-DSA-44":rO(44),"ML-DSA-65":rO(65),"ML-DSA-87":rO(87)});function tx(t){let e=typeof t=="string"?nO[t]:void 0;if(!e)throw new ut(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function tH(t){return[t&&zh("algorithms",t.algorithms),t?.crit]}function tpe(t){return t===void 0?{}:jd(t,xt,"JWS Protected Header is invalid")}function rpe(t){try{return pr(t)}catch{throw new xt("JWS Compact Serialization payload must use only ASCII characters")}}async function npe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??tpe(i);if(!Ca(c,s))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=US(c,Oa(xt,zS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new xu('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new xt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let m=tx(d),h=tn(i!==void 0?pr(i):new Uint8Array,pr("."),typeof p=="string"?e[2]??=DS(p,"payload",xt):p),y=vn(t.signature,"signature",xt),w=await Lo(m,r,"verify"),b=await Fo(w,m.subtle,"verify");m.minRsaBits&&Md(m.alg,b);let _=!1;try{_=await crypto.subtle.verify(m.signing,b,y,h)}catch{}if(!_)throw new NS;let x={payload:typeof p=="string"?vn(p,"payload",xt):p};return i!==void 0&&(x.protectedHeader=c),s!==void 0&&(x.unprotectedHeader=s),f?[{...x,key:w},l]:[x,l]}async function rH(t,e,r){if(t instanceof Uint8Array&&(t=zd.decode(t)),typeof t!="string")throw new xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new xt("Invalid Compact JWS");return npe({payload:n,protected:o,signature:i},e,r,rpe)}async function oO(t,e,r){let[o]=await rH(t,tH(r),e);return o}var Bd=class{#e;constructor(e){Nn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return eo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return eo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return eo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return eo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return QB(await YB([...this.#e],e,r))}};async function ope(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=ku(xt,n);n=w[0],a=Tt(w[1])}if(i!==void 0&&(i=ku(xt,i)[0]),!n&&!i)throw new xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Ca(n,i))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};MS(xt,n);let u=US(n,Oa(xt,zS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=tx(l),p="",f=o,m;if(u){let w=t[4];w?(p=w[0]??=Tt(o),f=w[1]??=pr(p)):(p=Tt(o),m=Dd.encode(`${a}.${p}`))}m??=tn(pr(a),pr("."),f);let h=await Fo(await Lo(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&Md(d.alg,h);let y={signature:Tt(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:p};return n&&(y.protected=a),i&&(y.header=i),[y,u]}async function nH(t,e,r,o,n){let[i]=await ope([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Fh=class{#e;#t;constructor(e){Nn(e,"payload"),this.#e=e}setProtectedHeader(e){return eo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return nH(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var iO='"alg" (Algorithm)';function sO(t='JWK "alg" (Algorithm) Parameter'){throw new ut(`Invalid or unsupported ${t} value`)}function Vh(t,e){return(typeof t=="string"?nO[t]??Fs[t]:void 0)??sO(e)}async function Da(t){if(FC(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Tt(t)};if(!Na(t))throw new TypeError(Ls(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 Vs=(t,e)=>{if(typeof t!="string"||!t)throw new Dh(`${e} missing or invalid`)};async function aO(t,e){let r;if(Bt(t)){if(r=VS(t),typeof r.kty!="string")throw new TypeError(Ls(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(VC(t))r=VS(await Da(t));else throw new TypeError(Ls(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":Vs(r.alg,'"alg" (Algorithm) Parameter'),Vs(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Vs(r.crv,'"crv" (Curve) Parameter'),Vs(r.x,'"x" (X Coordinate) Parameter'),Vs(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Vs(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Vs(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Vs(r.e,'"e" (Exponent) Parameter'),Vs(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 Dh('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new ut('"kty" (Key Type) Parameter missing or unsupported')}let n=pr(JSON.stringify(o));return Tt(await OS(e,n))}async function to(t,e,r){if(!Bt(t))throw new TypeError("JWK must be an object");let o=qC(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 Eu(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 Ud(Vh(e),o,n)}case"RSA":case"EC":case"OKP":return Ud(Vh(e),o,n);default:throw new ut('Unsupported "kty" (Key Type) Parameter value')}}function cO(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 jd(e,TypeError,r)}function ipe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new ut("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Bh(t,e){let r=BS(e?.extractable),o=Vh(t,iO);o.secret&&sO(iO);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new ut("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 ut(`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:ipe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}typeof window<"u"&&g.config({jitless:!0});var k=g.uuid(),le=g.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Be=g.iso.datetime(),ro=g.json(),Au=g.record(g.string(),ro),iH=g.enum(["ja","en"]),sH=g.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var aH=g.enum(["variable","connection","service","method","app","object","environment","function"]),Nr=g.object({kty:g.literal("EC"),crv:g.literal("P-256"),x:g.string().min(40).max(50),y:g.string().min(40).max(50)}).strict(),spe=g.object({alg:g.literal("dir"),enc:g.literal("A256GCM"),sub:k}).strict(),ox=g.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 spe.safeParse(cO(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ho=g.object({protected:g.string().max(2048),iv:g.string().max(64),ciphertext:g.string().max(2e6),tag:g.string().max(64),aad:g.string().max(2048).optional(),recipients:g.array(g.object({encrypted_key:g.string().max(2048),header:g.object({kid:k,epk:Nr.optional(),alg:g.string().optional()}).passthrough()})).min(1).max(100)}).strict(),H2e=g.object({id:k,name:le,publicKey:Nr}),Hd=g.object({id:k,name:le,owner:g.object({id:k,name:le}).nullable(),createdAt:Be,permissions:g.array(sH),createKinds:g.array(aH),publicKey:Nr.nullable()}),cH=g.object({id:k,kind:g.enum(["passkey","email","key"]),name:g.string(),createdAt:Be,lastUsedAt:Be.nullable(),expiresAt:Be.nullable(),canOpen:g.boolean()}),uH=g.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ape=g.object({subjectId:k,relation:uH,objectId:k}).strict(),q2e=ape.extend({objectType:g.enum(["principal",...aH.options]),subjectName:le,objectName:le,createdAt:Be}),Z2e=g.object({error:g.object({code:g.string(),message:g.string(),details:ro.optional()})}),K2e=g.object({ok:g.literal(!0)}),lH=g.object({name:g.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:g.string(),secret:g.boolean().optional(),required:g.boolean().optional(),placeholder:g.string().optional(),note:g.string().optional(),pattern:g.string().optional()}),dH=g.record(g.string().regex(/^[A-Z_][A-Z0-9_]*$/),g.string()),cpe=g.object({values:g.array(g.object({id:g.string(),name:g.string(),description:g.string().optional()})).optional(),default:g.array(g.string()).default([]),separator:g.string().default(" "),docs:g.url().optional()}),rx=g.string().min(1).max(4096),oH=g.union([g.string(),g.array(g.string()).min(1)]),fH=g.object({grantType:g.enum(["authorization_code","client_credentials"]).optional(),issuer:g.url().optional(),authorizeUrl:rx.optional(),tokenUrl:rx,identity:g.object({url:rx.optional(),from:g.enum(["token","app"]).optional(),method:g.enum(["GET","POST"]).default("GET"),id:oH.default("/id"),name:oH.default("/name"),headers:g.record(g.string(),g.string()).default({})}).optional(),revoke:g.object({url:rx,style:g.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:g.enum(["body","basic","none"]).optional()}).optional(),clientAuth:g.enum(["body","basic","none"]).default("body"),pkce:g.boolean().default(!0),tokenFormat:g.enum(["form","json"]).default("form"),okPointer:g.string().optional(),authorizeParams:g.record(g.string(),g.string()).default({}),tokenParams:g.record(g.string(),g.string()).default({}),defaults:g.record(g.string(),g.string()).default({}),scopes:cpe.default({default:[],separator:" "}),fields:g.array(lH).default([]),outputs:dH.default({ACCESS_TOKEN:"/accessToken"}),adapter:g.enum(["google","github","ebay","openrouter","cloudflare","slack"]).optional(),keep:g.array(g.string()).default([]),hint:g.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),pH=g.object({fields:g.array(lH).min(1),outputs:dH,console:g.url().optional(),instructions:g.string().optional(),hint:g.string().optional()}),lO=g.enum(["oauth","token","role"]),mH=g.object({kind:g.literal("aws"),hint:g.string().optional()}),dO={name:le,docs:g.url().optional(),console:g.url().optional()},hH=g.object({...dO,kind:g.literal("oauth"),config:fH}).strict(),gH=g.object({...dO,kind:g.literal("token"),config:pH}).strict(),yH=g.object({...dO,kind:g.literal("role"),config:mH}).strict(),Tu=g.discriminatedUnion("kind",[hH,gH,yH]),uO={id:g.string().min(1),builtin:g.boolean(),availability:g.enum(["ready","app-required","unavailable"])},fO=g.discriminatedUnion("kind",[hH.extend(uO),gH.extend(uO),yH.extend(uO)]),pO=g.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),ix=g.object({name:le,logo:g.string().regex(/^[a-z0-9-]+$/).optional(),api:g.url().optional(),docs:g.url().optional(),console:g.url().optional()}).strict(),upe=ix.extend({auth:g.object({oauth:fH.optional(),token:pH.optional(),role:mH.optional()}).strict()}).strict(),lpe=ix.extend({methods:g.record(pO,g.string().min(1))}).strict(),dpe=ix.extend({methods:g.record(pO,g.union([g.string().min(1),Tu]))}).strict(),vH=g.union([dpe,upe]),W2e=ix.extend({id:g.string(),builtin:g.boolean(),methods:g.record(pO,fO)}),wH=g.object({id:k,output:g.string().min(1).max(100).optional()}).strict(),mO=g.object({name:g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:wH,format:g.enum(["text","file","json"]).default("text"),pointer:g.string().optional()}).strict(),fpe=g.object({pointer:g.string().max(500),parts:g.array(g.union([g.string().max(8192),wH])).min(1).max(32)}).strict(),Pu=g.object({url:g.string().max(4096),method:g.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:g.record(g.string(),g.string().max(8192)).default({}),body:g.string().max(1e6).optional(),json:ro.optional(),form:g.record(g.string(),g.string()).optional(),bindings:g.array(fpe).max(32).default([])}).strict(),Hh=g.object({description:g.string().max(2e3).default(""),request:Pu,parameters:g.array(g.object({name:g.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:g.string().max(100),required:g.boolean().default(!0),default:g.string().optional()})).max(32).default([]),save:g.record(g.string(),le).default({}),outputOwnerId:k.optional()}).strict(),za={id:k,ownerId:k,name:le,createdAt:Be,updatedAt:Be,version:g.number().int().positive(),permissions:g.array(sH)},ppe=g.enum(["starting","running","stopping","stopped","failed"]),mpe=g.object({state:g.enum(["pending","failed","complete"]),error:g.string().nullable()}),hpe=g.object({idleSeconds:g.number().int().min(60).max(86400).default(3600),maxSeconds:g.number().int().min(60).max(86400).default(3600)}).strict(),bH=g.object({image:g.string().min(1).max(300).optional(),size:g.enum(["small","medium","large"]).default("small"),lifetime:hpe.default({idleSeconds:3600,maxSeconds:3600})}).strict(),hO={recipients:g.array(k).default([]),executors:g.array(k).default([]),custodyRevision:g.number().int().positive().nullable().default(null)},gpe=g.object({...za,kind:g.literal("variable"),data:g.object({...hO,bytes:g.number().int().nonnegative()})}),ype=g.object({...za,kind:g.literal("connection"),data:g.object({...hO,methodId:g.string(),methodName:g.string(),methodKind:lO,services:g.array(g.object({id:g.string(),name:le})).default([]),account:g.string(),accountId:g.string().nullable().default(null),accountVerified:g.boolean().default(!1),scopes:g.array(g.string()),scopesStatus:g.enum(["unknown","requested","reported"]).default("unknown"),outputs:g.array(g.string()),state:g.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:k.nullable(),generation:k.optional(),authorizationDigest:g.string().optional()})}),vpe=g.object({...za,kind:g.literal("service"),data:lpe}),wpe=g.object({...za,kind:g.literal("method"),data:Tu}),bpe=g.object({...za,kind:g.literal("app"),data:g.object({...hO,methodId:g.string(),clientId:g.string(),fields:g.record(g.string(),g.string()).default({}),generation:k.optional()})}),_pe=g.object({...za,kind:g.literal("object"),data:g.object({size:g.number().int().nonnegative(),contentType:g.string()})}),Spe=g.object({...za,kind:g.literal("environment"),data:bH.extend({executorId:k.optional(),operatorId:k.optional(),driver:g.enum(["attached","managed"]).optional(),capabilities:g.array(g.string()).optional(),isolation:g.enum(["process","container"]).optional(),manifestDigest:g.string().optional(),processes:g.object({workingDirectory:g.string()}).optional(),awsPrincipal:g.string().optional(),state:ppe,deletion:mpe.optional(),startedAt:Be.nullable(),stoppedAt:Be.nullable(),lastActiveAt:Be,error:g.string().nullable()})}),xpe=g.object({...za,kind:g.literal("function"),data:Hh}),no=g.discriminatedUnion("kind",[gpe,ype,vpe,wpe,bpe,_pe,Spe,xpe]),J2e=g.discriminatedUnion("kind",[g.object({kind:g.literal("service"),name:le,definition:vH}).strict(),g.object({kind:g.literal("method"),name:le,definition:Tu}).strict(),g.object({kind:g.literal("environment"),name:le.optional(),options:bH}).strict(),g.object({kind:g.literal("function"),name:le,definition:Hh}).strict()]),G2e=g.object({version:g.number().int().positive(),name:le.optional(),definition:g.union([vH,Tu,Hh]).optional()}).strict(),sx=g.object({command:g.array(g.string().max(8192)).min(1).max(100),stdin:g.string().max(1e6).optional(),timeoutSeconds:g.number().int().min(1).max(3600).default(60),inputs:g.array(mO).max(32).default([])}).strict(),_H=g.object({method:g.enum(["GET","POST","PUT","PATCH","DELETE","CONNECT"]),path:g.string().startsWith("/api/").max(2048),body:ro.optional(),inputs:g.array(g.object({pointer:g.string(),label:g.string().min(1).max(100),secret:g.boolean().default(!1),multiline:g.boolean().default(!1),site:g.url().optional()})).max(16).default([])}).strict(),Epe=g.object({ja:g.string(),en:g.string()}).strict(),SH=g.object({ownerId:g.union([k,g.literal("$approver")]),methodId:g.string().min(1).max(200),connectionId:k.optional(),environmentId:k.optional(),name:le.optional()}).strict(),xH=g.object({to:k.optional(),message:g.string().max(1e3).default(""),operations:g.array(_H).min(1).max(8),expiresInMinutes:g.number().int().min(1).max(1440).default(30)}).strict(),nx=g.object({id:k,name:le}),kpe=g.discriminatedUnion("kind",[g.object({kind:g.literal("line"),subject:nx,relation:uH,object:nx}),g.object({kind:g.literal("transfer"),item:nx,to:nx})]),ja=g.object({id:k,from:Hd.pick({id:!0,name:!0}),to:Hd.pick({id:!0,name:!0}).nullable(),message:g.string(),proposal:kpe.nullable(),operations:g.array(_H.extend({title:Epe})),state:g.enum(["pending","running","approved","declined","cancelled","expired"]),results:g.array(ro.nullable()),createdAt:Be,expiresAt:Be,url:g.url(),code:g.string().optional(),continueUrl:g.url().nullable(),returnUrl:g.url().nullable(),refreshUrl:g.url().nullable(),canRespond:g.boolean()}),X2e=g.object({id:k,name:le,publicKey:Nr,state:g.enum(["pending","approving","approved"]),principalId:k.nullable(),createdAt:Be,expiresAt:Be}),Y2e=g.object({available:g.boolean(),required:g.boolean(),active:g.boolean(),payer:Hd.pick({id:!0,name:!0}).nullable()}),Q2e=g.object({storageBytes:g.number().nonnegative(),storageLimit:g.number().positive(),computeSeconds:g.number().nonnegative(),computeLimit:g.number().positive(),month:g.string()}),e6e=g.object({id:g.string(),actorId:k.nullable(),action:g.string(),targetId:k.nullable(),createdAt:Be,details:Au}),t6e=g.object({returnUrl:g.url().optional(),refreshUrl:g.url().optional()}).strict(),Ma=t=>g.object({items:g.array(t),next:g.string().nullable().default(null)}),r6e=g.object({id:k}),n6e=g.object({owner:k}),Ipe=g.object({limit:g.coerce.number().int().min(1).max(200).default(100),after:g.string().optional()}),o6e=Ipe.extend({object:k.optional(),subject:k.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var $pe=new TextEncoder,Ape=new TextDecoder,qh="ECDH-ES+A256KW",gO="A256GCM",lt=t=>$pe.encode(t),Ru=t=>Ape.decode(t);function Ua(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 EH(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function ax(){let t=await Bh(qh,{crv:"P-256",extractable:!0});return{publicKey:Nr.parse(await Da(t.publicKey)),privateKey:await Da(t.privateKey)}}async function Cu(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 Uh(t).setProtectedHeader({enc:gO}).setAdditionalAuthenticatedData(lt(r));for(let n of e)o.addRecipient(await to(n.publicKey,qh)).setUnprotectedHeader({alg:qh,kid:n.id});return Ho.parse(await o.encrypt())}async function Ni(t,e,r,o){if(t.aad!==Ua(lt(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 to(e,qh);return(await GC({...t,recipients:[n]},i,{keyManagementAlgorithms:[qh],contentEncryptionAlgorithms:[gO]})).plaintext}async function Tpe(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:lt("Foundation"),info:lt("passkey encryption key")},e,256))}async function kH(t,e,r){let o=await Mh(t,await Tpe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[gO]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Ru(o.plaintext))}var mr=g.string().regex(/^[A-Za-z0-9_-]{43}$/),Dn=g.string().min(100).max(4e6),IH=Nr.extend({d:g.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Zh=g.object({encryption:IH,signing:IH}).strict(),hr=g.object({id:k,principalId:k,generation:g.number().int().positive(),previous:mr.nullable(),encryption:Nr,signing:Nr}).strict();function R(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,R).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)+":"+R(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function qd(t){return aO(Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function Ne(t){return Ua(new Uint8Array(await crypto.subtle.digest("SHA-256",lt(R(t)))))}async function Ou(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",lt(R(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function ux(){let[t,e]=await Promise.all([ax(),Bh("ES256",{crv:"P-256",extractable:!0})]),r=await Da(e.privateKey);return Zh.parse({encryption:t.privateKey,signing:r})}function cx(t){return Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function lx(t,e){return hr.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:cx(e.encryption),signing:cx(e.signing)})}async function wn(t,e,r){let o=e instanceof CryptoKey?e:await to(e,"ES256");return new Fh(lt(R(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function oo(t,e,r,o){if(R(await yO(e,r,o))!==R(t))throw new Error("The signature does not authorize this content.")}async function yO(t,e,r){let o=await oO(t,await to(Nr.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(R(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Di=g.object({binding:hr,signature:Dn}).strict();async function Kh(t,e){if(await La(t),await qd(e.encryption)!==await qd(t.encryption)||await qd(e.signing)!==await qd(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await wn(t,e.signing,"key-binding")}}async function La(t){let e=hr.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await qd(e.encryption)===await qd(e.signing))throw new Error("Use separate encryption and signing keys.");await to(e.encryption,"ECDH-ES+A256KW"),await to(e.signing,"ES256")}async function vO(t){let{binding:e,signature:r}=Di.parse(t);return await La(e),await oo(e,r,e.signing,"key-binding"),e}var Zd=g.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."),Me={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632"},Ppe=g.enum([Me.value,Me.tokenSet,Me.clientCredential]),pe={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"},dx=g.enum([pe.http,pe.command,pe.function,pe.connect,pe.refresh,pe.revoke]);var Rpe={[Me.value]:[pe.http,pe.command,pe.function],[Me.tokenSet]:[pe.http,pe.command,pe.function,pe.refresh,pe.revoke],[Me.clientCredential]:[pe.connect,pe.refresh,pe.revoke]},wO=t=>Rpe[t],bO=t=>t===Me.tokenSet,Cpe=g.object({actor:hr,executor:hr,operations:g.array(dx).min(1).max(6),functionDigests:g.array(mr).max(100).default([]),origins:g.array(Zd).max(100).default([]),callerProgram:g.boolean().default(!1),expiresAt:Be}).strict(),zi=g.object({format:g.literal(2),origin:Zd,id:k,ownerId:k,contentType:Ppe,revision:g.number().int().positive(),authorities:g.array(hr).min(1).max(100),readers:g.array(hr).min(1).max(100),grants:g.array(Cpe).max(100),observers:g.array(k).max(100).optional(),producers:g.array(g.object({executor:hr,runId:k,expiresAt:Be,materialRevision:g.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),$H=g.object({ownerId:k,authorities:g.array(hr).min(1).max(100)}).strict(),AH=g.object({origin:Zd,id:k,revision:g.number().int().positive(),from:$H,to:$H,policyDigest:mr,previous:mr.nullable(),signerId:k}).strict(),Ope=AH.extend({signature:Dn}),_O=g.array(Ope).max(16),Wh=g.object({policy:zi,authorityId:k,signature:Dn,lineage:_O.optional()}).strict(),io=g.object({policy:zi,authorityId:k,authorization:Dn,lineage:_O.optional(),materialRevision:g.number().int().positive(),updatedAt:Be,creationRunId:k.nullable(),metadata:Au,sealed:Ho,signerId:k,signature:Dn}).strict(),Nu=t=>({ownerId:t.ownerId,authorities:t.authorities});async function TH(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||R(r.to)!==R(o.from))||o.previous!==(r?await Ne(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 oo(i,n,s.signing,"authority-handoff"),r=o}if(r&&R(r.to)!==R(Nu(t)))throw new Error("Use the authorities approved by the latest handoff.")}function SO(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 PH(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=R(Nu(t));return r===R(Nu(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&R(o.from)===r)}async function RH(t,e,r,o){let n=[...t?.lineage??[]];if(t&&R(Nu(t.policy))!==R(Nu(e))){if(await qo(t),!t.policy.authorities.some(s=>R(s)===R(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=AH.parse({origin:e.origin,id:e.id,revision:e.revision,from:Nu(t.policy),to:Nu(e),policyDigest:await Ne(e),previous:n.length?await Ne(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await wn(i,o.signing,"authority-handoff")})}return n.length?{lineage:_O.parse(n)}:{}}async function fx(t){let e=zi.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>[n.actor,n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await La(n);let i=R(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=>!wO(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if(n.operations.some(i=>i===pe.http||i===pe.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(pe.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function px(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Kd(t,e){return R({purpose:"resource",policyDigest:await Ne(t),materialRevision:e})}async function xO(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await fx(e),c=await RH(s,a,o,n);if(!a.authorities.some(p=>R(p)===R(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Cu(t,px(a).map(p=>({id:p.id,publicKey:p.encryption})),await Kd(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await wn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===Me.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=io.parse({...l,signature:await wn(l,n.signing,"resource")});return await qo(d),d}async function qo(t){let e=io.parse(t),{signature:r,...o}=e;await fx(e.policy),await TH(e.policy,e.lineage);let n=SO(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await Ne(e.policy))throw new Error("The handoff approves a different access policy.");await oo(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&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor??(bO(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(pe.refresh)&&Date.parse(u.expiresAt)>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 oo(o,r,s.signing,"resource");let a=px(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(R(a)!==R(c)||e.sealed.aad!==Ua(lt(await Kd(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function CH(t,e,r,o,n=t.metadata){let i=await qo(t);if(!bO(i.policy.contentType)||!(i.policy.authorities.some(p=>R(p)===R(r))||i.policy.grants.some(p=>R(p.executor)===R(r)&&p.operations.includes(pe.refresh)&&Date.parse(p.expiresAt)>Date.now())))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 Cu(e,px(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await Kd(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 wn(l,o.signing,"resource")};return await qo(d),d}async function mx(t,e,r,o){let n=await fx(t);if(!n.authorities.some(s=>R(s)===R(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await RH(o,n,e,r),authorityId:e.id,signature:await wn(n,r.signing,"access-policy")};return await Wd(i),i}async function Wd(t){let e=Wh.parse(t);await fx(e.policy),await TH(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await Ne(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 oo(e.policy,e.signature,o.signing,"access-policy"),e}async function hx(t,e,r,o,n,i){let s=await Wd(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&R(p.executor)===R(o)&&Date.parse(p.expiresAt)>Date.now());if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let u=await Cu(t,px(a).map(p=>({id:p.id,publicKey:p.encryption})),await Kd(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 wn(l,n.signing,"resource")};return await qo(d),d}async function EO(t,e,r){let o=await qo(t);if(!o.policy.readers.some(n=>R(n)===R(e)))throw new Error("This identity cannot reveal the content.");return Ni(o.sealed,r,e.id,await Kd(o.policy,o.materialRevision))}var Npe=g.object({id:k,policyDigest:mr,materialRevision:g.number().int().positive(),authorizationDigest:mr.optional()}).strict();async function kO(t,e){return e.id===t.policy.id&&e.policyDigest===await Ne(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||bO(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var gx=g.object({format:g.literal(2),id:k,origin:Zd,ownerId:k,approval:g.object({id:k,index:g.number().int().min(0).max(7)}).strict().optional(),actor:hr,environmentId:k,executor:hr,environmentDigest:mr,operation:dx,functionDigest:mr.nullable(),operationDigest:mr,sources:g.array(Npe).max(100),resultRecipients:g.array(hr).min(1).max(100),createdAt:Be,expiresAt:Be}).strict(),yx=g.object({intent:gx,signature:Dn,sealed:Ho}).strict();async function Du(t,e){return R({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await Ne(t)})}async function OH(t,e,r){if(gx.parse(t),await Ne(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Cu(lt(R(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Du(t,"input"))};return yx.parse({...o,signature:await wn(o,r.signing,"run")})}async function Dpe(t,e=Date.now()){let r=yx.parse(t),{signature:o,...n}=r;await oo(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Ua(lt(await Du(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function NH(t,e,r){let o=await Dpe(t);if(R(o.intent.executor)!==R(e))throw new Error("This operation belongs to another executor.");let n=await Ni(o.sealed,r.encryption,e.id,await Du(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(R(s)!==i||await Ne(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function zu(t,e,r={}){let o=await qo(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await kO(o,i))throw new Error("The input changed after this execution was authorized.");if(R(e.actor)===R(e.executor)&&n.readers.some(c=>R(c)===R(e.actor)))return o;if(!n.grants.filter(c=>R(c.actor)===R(e.actor)&&R(c.executor)===R(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>e.operation===pe.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==pe.command&&e.operation!==pe.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function Fa(t,e,r,o={}){return await zu(t,e,o),Ni(t.sealed,r.encryption,e.executor.id,await Kd(t.policy,t.materialRevision))}var zpe=g.object({email:g.boolean(),environments:g.boolean(),objects:g.boolean(),payments:g.boolean()}),vx=g.object({principal:Hd.nullable(),credentialId:k.nullable(),wrappedKey:ox.nullable(),requestId:k.nullable(),server:g.object({name:le}),features:zpe,principals:g.array(Hd)}),_6e=g.object({email:g.email().max(254),returnTo:g.string().max(2048).optional(),locale:iH.default("ja"),principalId:k.optional()}).strict(),S6e=g.object({intent:g.enum(["register","authenticate"]),name:le.optional(),principalId:k.optional(),returnTo:g.string().max(2048).optional()}).strict(),x6e=g.object({challengeId:k,credential:g.json(),publicKey:Nr.optional(),existingPublicKey:Nr.optional(),wrappedKey:ox.optional()}).strict();var jpe=g.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/[\w+=,.@/-]{1,200}$/),zH=g.object({format:g.literal(3),id:k,origin:Zd,ownerId:k,name:le,executor:hr,operatorId:k,driver:g.enum(["attached","managed"]),capabilities:g.array(dx).min(1).max(6),isolation:g.enum(["process","container"]),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:jpe.optional(),revision:g.number().int().positive()}).strict(),IO=g.object({manifest:zH,signature:Dn}).strict();async function $O(t,e){let r=zH.parse(t),o={manifest:r,signature:await wn(r,e.signing,"environment")};return await Jd(o),o}async function Jd(t){let e=IO.parse(t),{manifest:r}=e;if(await La(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(pe.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(pe.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await oo(r,e.signature,r.executor.signing,"environment"),e}async function wx(t,e){let{manifest:r}=await Jd(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await Ne(r)||R(e.executor)!==R(r.executor)||!r.capabilities.includes(e.operation))throw new Error("This environment does not authorize the requested execution.")}var Mpe=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),jH=g.object({ok:g.boolean(),result:ro.nullable(),error:g.object({code:g.string().max(100),message:g.string().max(1e3)}).nullable()}).strict(),Gh=g.object({id:k,intentDigest:mr,executorId:k,state:g.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:Be,sealed:Ho,signature:Dn}).strict(),Jh=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Gd(t,e,r,o){let n=jH.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=lt(R(n));if(i.byteLength>14e5)throw new Jh;let s=await Cu(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Du(t,"result")),a={id:t.id,intentDigest:await Ne(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Gh.parse({...a,signature:await wn(a,o.signing,"receipt")})}async function Upe(t,e){let r=Gh.parse(t),{signature:o,...n}=r;if(await oo(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await Ne(e)||r.executorId!==e.executor.id||r.sealed.aad!==Ua(lt(await Du(e,"result")))||R(r.sealed.recipients.map(i=>i.header.kid).sort())!==R(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function MH(t,e,r,o){await Upe(t,e);let n=await Ni(t.sealed,o.encryption,r,await Du(e,"result")),i=jH.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 Lpe=g.enum(["http","command","function","connect","refresh","revoke"]),zn=g.object({id:k,ownerId:k,actorId:k,environmentId:k,kind:Lpe,state:Mpe,intent:gx,requestSignature:Dn,receipt:Gh.nullable(),error:g.string().nullable(),createdAt:Be,startedAt:Be.nullable(),finishedAt:Be.nullable()}).strict(),DH=g.object({name:le,approval:Wh}).strict(),Xd=g.discriminatedUnion("kind",[g.object({kind:g.literal("http"),request:Pu,save:g.record(g.string(),DH).default({})}).strict(),g.object({kind:g.literal("command"),...sx.shape}).strict(),g.object({kind:g.literal("function"),definition:Hh,arguments:g.record(g.string(),g.string()).default({}),outputs:g.record(g.string(),DH).default({})}).strict(),g.object({kind:g.enum(["connect","refresh","revoke"]),input:ro}).strict()]);var Va=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Bs=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=g.object({error:g.object({code:g.string(),message:g.string()})}).parse(await n.json())}catch{throw new Va("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new Va(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await(await this.response(e,r)).json();return o?o.parse(n):n}async session(){return this.json("/api/session",{},vx)}};import{chmod as Fpe,lstat as Vpe,mkdir as Bpe,open as AO,readFile as LH,rename as Hpe,rm as qpe}from"node:fs/promises";import{dirname as Zpe,join as TO,resolve as Kpe}from"node:path";import{homedir as Wpe}from"node:os";import{randomUUID as Jpe}from"node:crypto";var PO=g.object({origin:g.url(),principalId:g.uuid(),token:g.string().min(20),keys:Zh.nullable(),binding:hr.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),FH=g.object({current:g.uuid(),identities:g.array(PO).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Hs(){return TO(process.env.XDG_CONFIG_HOME||TO(Wpe(),".config"),"foundation","identity.json")}function Ba(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 bx(t){let e;try{let n=Hs(),i=await Vpe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await Fpe(n,384);let s=FH.parse(JSON.parse(await LH(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=Ba(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Ba(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return PO.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==Ba(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Xh(t){let e=Hs(),r;try{r=FH.parse(JSON.parse(await LH(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=PO.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Yd(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
128
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function HF(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;HF(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 qF=new Set(["type","properties","required","additionalProperties"]),VF=["oneOf","anyOf"];function BF(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function ZP(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!qF.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]??BF(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:ZP(a)??{allOf:a};ur(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=BF(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 ofe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of qF)if(n in t)return;let r=e.filter(n=>VF.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=ZP(e);else{let n=r[0],i=VF.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=>ZP([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,wh(t,o))}function Ia(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 f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):wh(u,m),wh(u,l),a._zod.parent===d)for(let y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(m.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}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())HF(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)??[])ofe(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)}wh(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,ur(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:Ed(e,"input",t.processors),output:Ed(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Qr(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 Qr(o.element,r);if(o.type==="set")return Qr(o.valueType,r);if(o.type==="lazy")return Qr(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 Qr(o.innerType,r);if(o.type==="intersection")return Qr(o.left,r)||Qr(o.right,r);if(o.type==="record"||o.type==="map")return Qr(o.keyType,r)||Qr(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Qr(o.in,r)||Qr(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Qr(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Qr(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Qr(n,r))return!0;return!!(o.rest&&Qr(o.rest,r))}return!1}var KP=(t,e={})=>r=>{let o=Ea({...r,processors:e});return nt(t,o),ka(o,t),Ia(o,t)},Ed=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Ea({...n??{},target:i,io:e,processors:r});return nt(t,s),ka(s,t),Ia(s,t)};var kd=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},Id=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},ZF=(t,e)=>{kd(t,"minimum",e),Id(t,"maximum",e)},GF=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},XF=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},YF=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},QF=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},KF=(t,e)=>kd(t,"minimum",e.minimum),WF=(t,e)=>Id(t,"maximum",e.maximum),JF=t=>(e,r)=>{QF(e,r.format);let[o,n]=t[r.format];kd(e,"minimum",o),Id(e,"maximum",n)},ife={greater_than:(t,e)=>kd(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>Id(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>GF(t,e.value),number_format:JF(xm),bigint_format:JF(Em),min_length:KF,max_length:WF,length_equals:(t,e)=>ZF(t,e.length),min_size:KF,max_size:WF,size_equals:(t,e)=>ZF(t,e.size),string_format:(t,e)=>{QF(t,e.format),e.pattern&&XF(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)=>YF(t,e.mime)};function Jt(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)ife[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&kd(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&kd(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Id(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Id(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&GF(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&YF(e,n.mime);for(let i of n.patterns??[])XF(e,i);return e}var sfe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},afe=new Map([[db,NT],[Mm,DT]]),eV=t=>afe.get(t)??t,GP=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Jt(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=sfe[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(eV);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},XP=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Jt(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let w of a)Number.isFinite(w)&&w!==0?m.add(Math.abs(w)):Wt(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[h,...y]=m;h!==void 0&&(n.multipleOf=h),y.length&&(n.allOf=[...n.allOf??[],...y.map(w=>({multipleOf:w}))])}},YP=(t,e,r,o)=>{r.type="boolean"},QP=(t,e,r,o)=>{Wt(t,e,r,o,"BigInt cannot be represented in JSON Schema")},eR=(t,e,r,o)=>{Wt(t,e,r,o,"Symbols cannot be represented in JSON Schema")},tR=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},rR=(t,e,r,o)=>{Wt(t,e,r,o,"Undefined cannot be represented in JSON Schema")},nR=(t,e,r,o)=>{Wt(t,e,r,o,"Void cannot be represented in JSON Schema")},oR=(t,e,r,o)=>{r.not={}},iR=(t,e,r,o)=>{},sR=(t,e,r,o)=>{},aR=(t,e,r,o)=>{Wt(t,e,r,o,"Date cannot be represented in JSON Schema")},cR=(t,e,r,o)=>{let n=t._zod.def,i=Ll(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},uR=(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(Wt(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Wt(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},lR=(t,e,r,o)=>{Wt(t,e,r,o,"NaN cannot be represented in JSON Schema")},dR=(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},fR=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Jt(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})))},pR=(t,e,r,o)=>{r.type="boolean"},mR=(t,e,r,o)=>{Wt(t,e,r,o,"Custom types cannot be represented in JSON Schema")},hR=(t,e,r,o)=>{Wt(t,e,r,o,"Function types cannot be represented in JSON Schema")},gR=(t,e,r,o)=>{Wt(t,e,r,o,"Transforms cannot be represented in JSON Schema")},yR=(t,e,r,o)=>{Wt(t,e,r,o,"Map cannot be represented in JSON Schema")},vR=(t,e,r,o)=>{Wt(t,e,r,o,"Set cannot be represented in JSON Schema")},wR=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Jt(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=nt(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 bR=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Wt(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)ur(n.properties,u,nt(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=nt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},eS=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>nt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},_R=(t,e,r,o)=>{let n=t._zod.def,i=nt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=nt(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)},SR=(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((h,y)=>nt(h,e,{...o,path:[...o.path,s,y]})),u=i.rest?nt(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 h=i.items[l-1];if(!(e.io==="input"?bh(h)!==void 0:h._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=Jt(t);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function WP(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let h=WP(t,m,r);return h===m?e:h}for(let m of["anyOf","oneOf"]){let h=e[m];if(!Array.isArray(h))continue;let y=h.map(w=>WP(t,w,r));y.some((w,b)=>w!==h[b])&&(e={...e,[m]:y})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?js:Rm).source)),f}var JP=new WeakMap;function cfe(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 JP.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=WP(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 xR=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Jt(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=nt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)ur(n.patternProperties,eV(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=nt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=JP.get(e);l||(l=[],JP.set(e,l),e.deferred.push(()=>cfe(e))),l.push(t)}n.additionalProperties=nt(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))}},ER=(t,e,r,o)=>{let n=t._zod.def,i=nt(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"}]},kR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},IR=Symbol();function tV(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Wt(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),IR):JSON.parse(s)}var $R=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=tV(n.defaultValue,t,e,r,o);s!==IR&&(r.default=s)},AR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=tV(n.defaultValue,t,e,r,o);s!==IR&&(r._prefault=s)},TR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Wt(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},PR=(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;nt(s,e,o);let a=e.seen.get(t);a.ref=s},RR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},CR=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},tS=(t,e,r,o)=>{let n=t._zod.def;nt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},OR=(t,e,r,o)=>{let n=t._zod.innerType;nt(n,e,o);let i=e.seen.get(t);i.ref=n},Q_={string:GP,number:XP,boolean:YP,bigint:QP,symbol:eR,null:tR,undefined:rR,void:nR,never:oR,any:iR,unknown:sR,date:aR,enum:cR,literal:uR,nan:lR,template_literal:dR,file:fR,success:pR,custom:mR,function:hR,transform:gR,map:yR,set:vR,array:wR,object:bR,union:eS,intersection:_R,tuple:SR,record:xR,nullable:ER,nonoptional:kR,default:$R,prefault:AR,catch:TR,pipe:PR,readonly:RR,promise:CR,optional:tS,lazy:OR};function yu(t,e){if("_idmap"in t){let o=t,n=Ea({...e,processors:Q_}),i={};for(let c of o._idmap.entries()){let[u,l]=c;nt(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;ka(n,l),ur(s,u,Ia(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=Ea({...e,processors:Q_});return nt(t,r),ka(r,t),Ia(r,t)}var rS=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=Ea({processors:Q_,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 nt(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,ka(this.ctx,e);let o=Ia(this.ctx,e),{"~standard":n,...i}=o;return i}};var rV={};var Nd={};vt(Nd,{ZodAny:()=>YR,ZodArray:()=>rC,ZodBase64:()=>_S,ZodBase64URL:()=>SS,ZodBigInt:()=>Cd,ZodBigIntFormat:()=>kS,ZodBoolean:()=>Rd,ZodCIDRv4:()=>wS,ZodCIDRv6:()=>bS,ZodCUID:()=>fS,ZodCUID2:()=>pS,ZodCatch:()=>_C,ZodCodec:()=>Th,ZodCreditCard:()=>KR,ZodCustom:()=>Ph,ZodCustomStringFormat:()=>wu,ZodDate:()=>Eh,ZodDefault:()=>hC,ZodDiscriminatedUnion:()=>oC,ZodE164:()=>xS,ZodEmail:()=>cS,ZodEmoji:()=>lS,ZodEnum:()=>Ad,ZodExactOptional:()=>AS,ZodFile:()=>dC,ZodFunction:()=>RC,ZodGUID:()=>uS,ZodIBAN:()=>WR,ZodIPv4:()=>yS,ZodIPv6:()=>vS,ZodISODate:()=>Aa,ZodISODateTime:()=>$a,ZodISODuration:()=>Pa,ZodISOTime:()=>Ta,ZodInstanceOf:()=>NC,ZodIntersection:()=>iC,ZodJWT:()=>ES,ZodKSUID:()=>gS,ZodLazy:()=>AC,ZodLiteral:()=>lC,ZodMAC:()=>ZR,ZodMap:()=>cC,ZodNaN:()=>xC,ZodNanoID:()=>dS,ZodNever:()=>eC,ZodNonOptional:()=>TS,ZodNull:()=>XR,ZodNullable:()=>mC,ZodNumber:()=>Pd,ZodNumberFormat:()=>bu,ZodObject:()=>kh,ZodOptional:()=>_u,ZodPipe:()=>Ah,ZodPrefault:()=>yC,ZodPreprocess:()=>EC,ZodPromise:()=>PC,ZodReadonly:()=>kC,ZodRecord:()=>$d,ZodSet:()=>uC,ZodString:()=>Td,ZodStringFormat:()=>at,ZodSuccess:()=>bC,ZodSymbol:()=>JR,ZodTemplateLiteral:()=>$C,ZodTransform:()=>fC,ZodTuple:()=>sC,ZodType:()=>ve,ZodULID:()=>mS,ZodURL:()=>Sh,ZodUUID:()=>Oi,ZodUndefined:()=>GR,ZodUnion:()=>Ih,ZodUnknown:()=>QR,ZodVoid:()=>tC,ZodXID:()=>hS,ZodXor:()=>nC,_ZodString:()=>aS,_default:()=>gC,_function:()=>lB,any:()=>qV,array:()=>Ae,base64:()=>kV,base64url:()=>IV,bigint:()=>LV,boolean:()=>Lt,catch:()=>SC,check:()=>dB,cidrv4:()=>xV,cidrv6:()=>EV,codec:()=>sB,creditCard:()=>AV,cuid:()=>hV,cuid2:()=>gV,currencyCode:()=>NV,custom:()=>PS,date:()=>KV,describe:()=>fB,discriminatedUnion:()=>$h,e164:()=>$V,email:()=>iV,emoji:()=>pV,enum:()=>fr,exactOptional:()=>pC,file:()=>rB,float32:()=>zV,float64:()=>jV,function:()=>lB,guid:()=>sV,hash:()=>DV,hex:()=>OV,hostname:()=>CV,httpUrl:()=>fV,iban:()=>TV,instanceof:()=>mB,int:()=>iS,int32:()=>MV,int64:()=>FV,intersection:()=>Od,invertCodec:()=>aB,ipv4:()=>bV,ipv6:()=>SV,json:()=>gB,jwt:()=>PV,keyof:()=>WV,ksuid:()=>wV,lazy:()=>TC,literal:()=>G,looseObject:()=>dr,looseRecord:()=>YV,mac:()=>_V,map:()=>QV,meta:()=>pB,nan:()=>iB,nanoid:()=>mV,nativeEnum:()=>tB,never:()=>IS,nonoptional:()=>wC,null:()=>xh,nullable:()=>_h,nullish:()=>nB,number:()=>We,object:()=>B,optional:()=>st,partialRecord:()=>XV,pipe:()=>sS,prefault:()=>vC,preprocess:()=>Rh,promise:()=>uB,readonly:()=>IC,record:()=>ct,refine:()=>CC,set:()=>eB,strictObject:()=>JV,string:()=>I,stringFormat:()=>RV,stringbool:()=>hB,success:()=>oB,superRefine:()=>OC,symbol:()=>BV,templateLiteral:()=>cB,transform:()=>$S,tuple:()=>aC,uint32:()=>UV,uint64:()=>VV,ulid:()=>yV,undefined:()=>HV,union:()=>ot,unknown:()=>ft,url:()=>dV,uuid:()=>aV,uuidv4:()=>cV,uuidv6:()=>uV,uuidv7:()=>lV,void:()=>ZV,xid:()=>vV,xor:()=>GV});var nS={};vt(nS,{endsWith:()=>gd,gt:()=>Ri,gte:()=>On,includes:()=>md,length:()=>gu,lowercase:()=>fd,lt:()=>Pi,lte:()=>Cn,maxLength:()=>hu,maxSize:()=>Sa,mime:()=>vd,minLength:()=>Ms,minSize:()=>Ci,multipleOf:()=>_a,negative:()=>V_,nonnegative:()=>H_,nonpositive:()=>B_,normalize:()=>wd,overwrite:()=>Mo,positive:()=>F_,properties:()=>yd,property:()=>q_,regex:()=>dd,size:()=>mu,slugify:()=>xd,startsWith:()=>hd,toLowerCase:()=>_d,toUpperCase:()=>Sd,trim:()=>bd,uppercase:()=>pd});var nV=new WeakSet([Object.prototype,Error.prototype]);function oS(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 oV=(t,e)=>{mT.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);nV.has(r)||(nV.add(r),oS(r,"format",o=>n=>Tm(o,n)),oS(r,"flatten",o=>n=>Am(o,n)),oS(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Fl,2)}),oS(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Fl,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},lfe=S("ZodError",oV),yn=S("ZodError",oV,void 0,{Parent:Error});var NR=Zl(yn),DR=Kl(yn),zR=Wl(yn),jR=Gl(yn),MR=Iw(yn),UR=$w(yn),LR=Aw(yn),FR=Tw(yn),VR=Pw(yn),BR=Rw(yn),HR=Cw(yn),qR=Ow(yn);function ffe(){Qt.localeError||Nt(l_())}function vu(){Qt.memoizer||Nt({memoizer:Zm()})}var ve=S("ZodType",(t,e)=>(ffe(),ae.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(A.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return Ke(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(CC(t,e))},superRefine(t,e){return this.check(OC(t,e))},overwrite(t){return this.check(Mo(t))},optional(){return st(this)},exactOptional(){return pC(this)},nullable(){return _h(this)},nullish(){return st(_h(this))},nonoptional(t){return wC(this,t)},array(){return Ae(this)},or(t){return ot([this,t])},and(t){return Od(this,t)},transform(t){return sS(this,$S(t))},default(t){return gC(this,t)},prefault(t){return vC(this,t)},catch(t){return SC(this,t)},pipe(t){return sS(this,t)},readonly(){return IC(this)},describe(t){let e=this.clone();return lr.add(e,{description:t}),e},meta(...t){if(t.length===0)return lr.get(this);let e=this.clone();return lr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return A.hide(this,"~standard",{...Hw(this),jsonSchema:{input:Ed(this,"input"),output:Ed(this,"output")}})},set"~standard"(t){A.own(this,"~standard",t)},parse:function t(e,r){return NR(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await DR(this,e,r,{callee:t})},safeParse(t,e){return zR(this,t,e)},async safeParseAsync(t,e){return jR(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){A.own(this,"spa",t)},validate(t,e){return Yl(this,t,e)},validateAsync(t,e){return Ql(this,t,e)},encode:function t(e,r){return MR(this,e,r,{callee:t})},decode:function t(e,r){return UR(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await LR(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await FR(this,e,r,{callee:t})},safeEncode(t,e){return VR(this,t,e)},safeDecode(t,e){return BR(this,t,e)},async safeEncodeAsync(t,e){return HR(this,t,e)},async safeDecodeAsync(t,e){return qR(this,t,e)},toJSONSchema(t){return KP(this,{})(t)},get description(){return lr.get(this)?.description},get _def(){return this._zod.def}}),aS=S("_ZodString",(t,e)=>{ba.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GP(t,r,o,n)},A.derived({format:t=>Jt(t).format??null,minLength:t=>Jt(t).minimum??null,maxLength:t=>Jt(t).maximum??null},{regex(...t){return this.check(dd(...t))},includes(...t){return this.check(md(...t))},startsWith(...t){return this.check(hd(...t))},endsWith(...t){return this.check(gd(...t))},min(...t){return this.check(Ms(...t))},max(...t){return this.check(hu(...t))},length(...t){return this.check(gu(...t))},nonempty(...t){return this.check(Ms(1,...t))},lowercase(t){return this.check(fd(t))},uppercase(t){return this.check(pd(t))},trim(){return this.check(bd())},normalize(...t){return this.check(wd(...t))},toLowerCase(){return this.check(_d())},toUpperCase(){return this.check(Sd())},slugify(){return this.check(xd())}})),Td=S("ZodString",(t,e)=>{ba.init(t,e),aS.init(t,e)},{email(t){return this.check(Wm(cS,t))},url(t){return this.check(ld(Sh,t))},jwt(t){return this.check(mh(ES,t))},emoji(t){return this.check(eh(lS,t))},guid(t){return this.check(Jm(uS,t))},uuid(t){return this.check(Gm(Oi,t))},uuidv4(t){return this.check(Xm(Oi,t))},uuidv6(t){return this.check(Ym(Oi,t))},uuidv7(t){return this.check(Qm(Oi,t))},nanoid(t){return this.check(th(dS,t))},cuid(t){return this.check(rh(fS,t))},cuid2(t){return this.check(nh(pS,t))},ulid(t){return this.check(oh(mS,t))},base64(t){return this.check(dh(_S,t))},base64url(t){return this.check(fh(SS,t))},xid(t){return this.check(ih(hS,t))},ksuid(t){return this.check(sh(gS,t))},ipv4(t){return this.check(ah(yS,t))},ipv6(t){return this.check(ch(vS,t))},cidrv4(t){return this.check(uh(wS,t))},cidrv6(t){return this.check(lh(bS,t))},e164(t){return this.check(ph(xS,t))},datetime(t){return this.check(hh($a,t))},date(t){return this.check(gh(Aa,t))},time(t){return this.check(yh(Ta,t))},duration(t){return this.check(vh(Pa,t))}});function I(t){return v_(Td,t)}var at=S("ZodStringFormat",(t,e)=>{Xe.init(t,e),aS.init(t,e)}),$a=S("ZodISODateTime",(t,e)=>{xP.init(t,e),at.init(t,e)}),Aa=S("ZodISODate",(t,e)=>{EP.init(t,e),at.init(t,e)}),Ta=S("ZodISOTime",(t,e)=>{kP.init(t,e),at.init(t,e)}),Pa=S("ZodISODuration",(t,e)=>{IP.init(t,e),at.init(t,e)}),cS=S("ZodEmail",(t,e)=>{Kw.init(t,e),at.init(t,e)});function iV(t){return Wm(cS,t)}var uS=S("ZodGUID",(t,e)=>{qw.init(t,e),at.init(t,e)});function sV(t){return Jm(uS,t)}var Oi=S("ZodUUID",(t,e)=>{Zw.init(t,e),at.init(t,e)});function aV(t){return Gm(Oi,t)}function cV(t){return Xm(Oi,t)}function uV(t){return Ym(Oi,t)}function lV(t){return Qm(Oi,t)}var Sh=S("ZodURL",(t,e)=>{Xw.init(t,e),at.init(t,e)});function dV(t){return ld(Sh,t)}function fV(t){return ld(Sh,{protocol:Pm,hostname:jT,...A.normalizeParams(t)})}var lS=S("ZodEmoji",(t,e)=>{Yw.init(t,e),at.init(t,e)});function pV(t){return eh(lS,t)}var dS=S("ZodNanoID",(t,e)=>{Qw.init(t,e),at.init(t,e)});function mV(t){return th(dS,t)}var fS=S("ZodCUID",(t,e)=>{eb.init(t,e),at.init(t,e)});function hV(t){return rh(fS,t)}var pS=S("ZodCUID2",(t,e)=>{tb.init(t,e),at.init(t,e)});function gV(t){return nh(pS,t)}var mS=S("ZodULID",(t,e)=>{rb.init(t,e),at.init(t,e)});function yV(t){return oh(mS,t)}var hS=S("ZodXID",(t,e)=>{nb.init(t,e),at.init(t,e)});function vV(t){return ih(hS,t)}var gS=S("ZodKSUID",(t,e)=>{ob.init(t,e),at.init(t,e)});function wV(t){return sh(gS,t)}var yS=S("ZodIPv4",(t,e)=>{ib.init(t,e),at.init(t,e)});function bV(t){return ah(yS,t)}var ZR=S("ZodMAC",(t,e)=>{ab.init(t,e),at.init(t,e)});function _V(t){return w_(ZR,t)}var vS=S("ZodIPv6",(t,e)=>{sb.init(t,e),at.init(t,e)});function SV(t){return ch(vS,t)}var wS=S("ZodCIDRv4",(t,e)=>{cb.init(t,e),at.init(t,e)});function xV(t){return uh(wS,t)}var bS=S("ZodCIDRv6",(t,e)=>{lb.init(t,e),at.init(t,e)});function EV(t){return lh(bS,t)}var _S=S("ZodBase64",(t,e)=>{fb.init(t,e),at.init(t,e)});function kV(t){return dh(_S,t)}var SS=S("ZodBase64URL",(t,e)=>{mb.init(t,e),at.init(t,e)});function IV(t){return fh(SS,t)}var xS=S("ZodE164",(t,e)=>{hb.init(t,e),at.init(t,e)});function $V(t){return ph(xS,t)}var KR=S("ZodCreditCard",(t,e)=>{yb.init(t,e),at.init(t,e)});function AV(t){return b_(KR,t)}var WR=S("ZodIBAN",(t,e)=>{wb.init(t,e),at.init(t,e)});function TV(t){return __(WR,t)}var ES=S("ZodJWT",(t,e)=>{_b.init(t,e),at.init(t,e)});function PV(t){return mh(ES,t)}var wu=S("ZodCustomStringFormat",(t,e)=>{Sb.init(t,e),at.init(t,e)});function RV(t,e,r={}){return xa(wu,t,e,r)}function CV(t){return xa(wu,"hostname",zT,t)}function OV(t){return xa(wu,"hex",XT,t)}function NV(t){return xa(wu,"currency_code",UT,t)}function DV(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Rn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return xa(wu,o,n,e)}var Pd=S("ZodNumber",(t,e)=>{Um.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XP(t,r,o,n),t.isFinite=!0},A.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Jt(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Jt(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Jt(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Jt(t).format??null},{gt(t,e){return this.check(Ri(t,e))},gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},lt(t,e){return this.check(Pi(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},int(t){return this.check(iS(t))},safe(t){return this.check(iS(t))},positive(t){return this.check(Ri(0,t))},nonnegative(t){return this.check(On(0,t))},negative(t){return this.check(Pi(0,t))},nonpositive(t){return this.check(Cn(0,t))},multipleOf(t,e){return this.check(_a(t,e))},step(t,e){return this.check(_a(t,e))},finite(){return this}}));function We(t){return S_(Pd,t)}var bu=S("ZodNumberFormat",(t,e)=>{xb.init(t,e),Pd.init(t,e)});function iS(t){return x_(bu,t)}function zV(t){return E_(bu,t)}function jV(t){return k_(bu,t)}function MV(t){return I_(bu,t)}function UV(t){return $_(bu,t)}var Rd=S("ZodBoolean",(t,e)=>{rd.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YP(t,r,o,n)});function Lt(t){return A_(Rd,t)}var Cd=S("ZodBigInt",(t,e)=>{Lm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QP(t,r,o,n)},A.derived({minValue:t=>Jt(t).minimum??null,maxValue:t=>Jt(t).maximum??null,format:t=>Jt(t).format??null},{gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},gt(t,e){return this.check(Ri(t,e))},lt(t,e){return this.check(Pi(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},positive(t){return this.check(Ri(BigInt(0),t))},negative(t){return this.check(Pi(BigInt(0),t))},nonpositive(t){return this.check(Cn(BigInt(0),t))},nonnegative(t){return this.check(On(BigInt(0),t))},multipleOf(t,e){return this.check(_a(t,e))}}));function LV(t){return T_(Cd,t)}var kS=S("ZodBigIntFormat",(t,e)=>{Eb.init(t,e),Cd.init(t,e)});function FV(t){return P_(kS,t)}function VV(t){return R_(kS,t)}var JR=S("ZodSymbol",(t,e)=>{kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eR(t,r,o,n)});function BV(t){return C_(JR,t)}var GR=S("ZodUndefined",(t,e)=>{Ib.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rR(t,r,o,n)});function HV(t){return O_(GR,t)}var XR=S("ZodNull",(t,e)=>{$b.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tR(t,r,o,n)});function xh(t){return N_(XR,t)}var YR=S("ZodAny",(t,e)=>{Ab.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iR(t,r,o,n)});function qV(){return D_(YR)}var QR=S("ZodUnknown",(t,e)=>{Tb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sR(t,r,o,n)});function ft(){return z_(QR)}var eC=S("ZodNever",(t,e)=>{Pb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oR(t,r,o,n)});function IS(t){return j_(eC,t)}var tC=S("ZodVoid",(t,e)=>{Rb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nR(t,r,o,n)});function ZV(t){return M_(tC,t)}var Eh=S("ZodDate",(t,e)=>{Cb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aR(t,r,o,n),t.min=(r,o)=>t.check(On(r,o)),t.max=(r,o)=>t.check(Cn(r,o))},A.derived({minDate:t=>{let{minimum:e}=Jt(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Jt(t);return e?new Date(e):null}},{}));function KV(t){return U_(Eh,t)}var rC=S("ZodArray",(t,e)=>{vu(),Ob.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wR(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ms(t,e))},nonempty(t){return this.check(Ms(1,t))},max(t,e){return this.check(hu(t,e))},length(t,e){return this.check(gu(t,e))},unwrap(){return this.element}});function Ae(t,e){return qP(rC,t,e)}function WV(t){let e=t._zod.def.shape;return fr(Object.keys(e))}var kh=S("ZodObject",(t,e)=>{vu(),$P.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bR(t,r,o,n),A.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return fr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(A.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ft()}))},loose(){return this.clone(A.mergeDefs(this._zod.def,{catchall:ft()}))},strict(){return this.clone(A.mergeDefs(this._zod.def,{catchall:IS()}))},strip(){return this.clone(A.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return A.extend(this,t)},safeExtend(t){return A.safeExtend(this,t)},merge(t){return A.merge(this,t)},pick(t){return A.pick(this,t)},omit(t){return A.omit(this,t)},partial(...t){return A.partial(_u,this,t[0])},exactPartial(...t){return A.partial(AS,this,t[0],"exactPartial")},required(...t){return A.required(TS,this,t[0])}});function B(t,e){let r={type:"object",shape:t??{},...A.normalizeParams(e)};return new kh(r)}function JV(t,e){return new kh({type:"object",shape:t,catchall:IS(),...A.normalizeParams(e)})}function dr(t,e){return new kh({type:"object",shape:t,catchall:ft(),...A.normalizeParams(e)})}var Ih=S("ZodUnion",(t,e)=>{nd.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eS(t,r,o,n),t.options=e.options});function ot(t,e){return new Ih({type:"union",options:t,...A.normalizeParams(e)})}var nC=S("ZodXor",(t,e)=>{Ih.init(t,e),Db.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eS(t,r,o,n),t.options=e.options});function GV(t,e){return new nC({type:"union",options:t,inclusive:!1,...A.normalizeParams(e)})}var oC=S("ZodDiscriminatedUnion",(t,e)=>{Ih.init(t,e),zb.init(t,e)});function $h(t,e,r){return new oC({type:"union",options:e,discriminator:t,...A.normalizeParams(r)})}var iC=S("ZodIntersection",(t,e)=>{jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_R(t,r,o,n)});function Od(t,e){return new iC({type:"intersection",left:t,right:e})}var sC=S("ZodTuple",(t,e)=>{vu(),Fm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SR(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 _u({type:"optional",innerType:e}))})}});function aC(t,e,r){let o=e instanceof ae,n=o?r:e,i=o?e:null;return new sC({type:"tuple",items:t,rest:i,...A.normalizeParams(n)})}var $d=S("ZodRecord",(t,e)=>{vu(),Mb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function ct(t,e,r){return!e||!e._zod?new $d({type:"record",keyType:I(),valueType:t,...A.normalizeParams(e)}):new $d({type:"record",keyType:t,valueType:e,...A.normalizeParams(r)})}function XV(t,e,r){return new $d({type:"record",keyType:t,valueType:e,...A.normalizeParams(r),partial:!0})}function YV(t,e,r){return new $d({type:"record",keyType:t,valueType:e,mode:"loose",...A.normalizeParams(r)})}var cC=S("ZodMap",(t,e)=>{vu(),Ub.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ci(...r)),t.nonempty=r=>t.check(Ci(1,r)),t.max=(...r)=>t.check(Sa(...r)),t.size=(...r)=>t.check(mu(...r))});function QV(t,e,r){return new cC({type:"map",keyType:t,valueType:e,...A.normalizeParams(r)})}var uC=S("ZodSet",(t,e)=>{vu(),Lb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vR(t,r,o,n),t.min=(...r)=>t.check(Ci(...r)),t.nonempty=r=>t.check(Ci(1,r)),t.max=(...r)=>t.check(Sa(...r)),t.size=(...r)=>t.check(mu(...r))});function eB(t,e){return new uC({type:"set",valueType:t,...A.normalizeParams(e)})}var Ad=S("ZodEnum",(t,e)=>{Fb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(o,n,i)=>cR(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 Ad({...e,checks:[],...A.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Ad({...e,checks:[],...A.normalizeParams(n),entries:i})}});function fr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Ad({type:"enum",entries:r,...A.normalizeParams(e)})}function tB(t,e){return new Ad({type:"enum",entries:t,...A.normalizeParams(e)})}var lC=S("ZodLiteral",(t,e)=>{Vb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uR(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function G(t,e){return new lC({type:"literal",values:Array.isArray(t)?t:[t],...A.normalizeParams(e)})}var dC=S("ZodFile",(t,e)=>{Bb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fR(t,r,o,n),t.min=(r,o)=>t.check(Ci(r,o)),t.max=(r,o)=>t.check(Sa(r,o)),t.mime=(r,o)=>t.check(vd(Array.isArray(r)?r:[r],o))});function rB(t){return Z_(dC,t)}var fC=S("ZodTransform",(t,e)=>{vu(),Hb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gR(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new wa(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(A.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(A.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function $S(t){return new fC({type:"transform",transform:t})}var _u=S("ZodOptional",(t,e)=>{Vm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tS(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function st(t){return new _u({type:"optional",innerType:t})}var AS=S("ZodExactOptional",(t,e)=>{qb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tS(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pC(t){return new AS({type:"optional",innerType:t})}var mC=S("ZodNullable",(t,e)=>{Zb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ER(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function _h(t){return new mC({type:"nullable",innerType:t})}function nB(t){return st(_h(t))}var hC=S("ZodDefault",(t,e)=>{Kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function gC(t,e){return new hC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var yC=S("ZodPrefault",(t,e)=>{Wb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function vC(t,e){return new yC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var TS=S("ZodNonOptional",(t,e)=>{Jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wC(t,e){return new TS({type:"nonoptional",innerType:t,...A.normalizeParams(e)})}var bC=S("ZodSuccess",(t,e)=>{Gb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function oB(t){return new bC({type:"success",innerType:t})}var _C=S("ZodCatch",(t,e)=>{Xb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function SC(t,e){return new _C({type:"catch",innerType:t,catchValue:typeof e=="function"?e:A.constantCatch(e)})}var xC=S("ZodNaN",(t,e)=>{Yb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lR(t,r,o,n)});function iB(t){return L_(xC,t)}var Ah=S("ZodPipe",(t,e)=>{Bm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PR(t,r,o,n),t.in=e.in,t.out=e.out});function sS(t,e){return new Ah({type:"pipe",in:t,out:e})}var Th=S("ZodCodec",(t,e)=>{Ah.init(t,e),od.init(t,e)});function sB(t,e,r){return new Th({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function aB(t){let e=t._zod.def;return new Th({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var EC=S("ZodPreprocess",(t,e)=>{Ah.init(t,e),TP.init(t,e)}),kC=S("ZodReadonly",(t,e)=>{Qb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function IC(t){return new kC({type:"readonly",innerType:t})}var $C=S("ZodTemplateLiteral",(t,e)=>{e_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dR(t,r,o,n)});function cB(t,e){return new $C({type:"template_literal",parts:t,...A.normalizeParams(e)})}var AC=S("ZodLazy",(t,e)=>{id.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OR(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function TC(t){return new AC({type:"lazy",getter:t})}var PC=S("ZodPromise",(t,e)=>{r_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function uB(t){return new PC({type:"promise",innerType:t})}var RC=S("ZodFunction",(t,e)=>{t_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hR(t,r,o,n)});function lB(t){return new RC({type:"function",input:Array.isArray(t?.input)?aC(t?.input):t?.input??Ae(ft()),output:t?.output??ft()})}var Ph=S("ZodCustom",(t,e)=>{n_.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mR(t,r,o,n)});function dB(t){let e=new it({check:"custom"});return e._zod.check=t,e}function PS(t,e){return K_(Ph,t??(()=>!0),e)}function CC(t,e={}){return W_(Ph,t,e)}function OC(t,e){return J_(t,e)}var fB=G_,pB=X_,NC=S("ZodInstanceOf",(t,e)=>{Ph.init(t,e)},{properties(t,e){return this.check(yd(t,e))}});function mB(t,e={}){let r=new NC({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...A.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var hB=(...t)=>Y_({Codec:Th,Boolean:Rd,String:Td},...t);function gB(t){let e=TC(()=>ot([I(t),We(),Lt(),xh(),Ae(e),ct(I(),e)]));return e}function Rh(t,e){return new EC({type:"pipe",in:$S(t),out:e})}var pfe={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 mfe(t){Nt({customError:t})}function hfe(){return Nt().customError}var DC;DC||(DC={});var Su={};vt(Su,{ZodISODate:()=>Aa,ZodISODateTime:()=>$a,ZodISODuration:()=>Pa,ZodISOTime:()=>Ta,date:()=>yfe,datetime:()=>gfe,duration:()=>wfe,time:()=>vfe});function gfe(t){return hh($a,t)}function yfe(t){return gh(Aa,t)}function vfe(t){return yh(Ta,t)}function wfe(t){return vh(Pa,t)}var V={...Nd,...nS,iso:Su},bfe=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 _fe(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 yB(t,e){return t.map((r,o)=>o<e?r:r.optional())}function Sfe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function xfe(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:Sfe(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 Efe(t,e){return V.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function zC(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=zC(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=zC(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 kfe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),Ife=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Ch(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(Ch):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>kfe.has(e)?Ch(r):!Ife.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(Ch))}function vB(t){return t===1?"element":"elements"}function $fe(t,e){return V.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=zC(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 ${vB(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 ${vB(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function wB(t,e){if(t!==!1)return t===void 0||t===!0?V.any():en(t,e)}var Afe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function bB(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return V.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return V.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=xfe(n,e),s=en(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return V.null();if(n.length===0)return V.never();if(n.length===1)return V.literal(n[0]);if(n.every(s=>typeof s=="string"))return V.enum(n);let i=n.map(s=>V.literal(s));return i.length<2?i[0]:V.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return V.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return bB(s,e)});return n.length===0?V.never():n.length===1?n[0]:V.union(n)}if(!r)return V.any();let o;switch(r){case"string":{let n=V.string();if(t.format){let i=t.format;i==="email"?n=n.check(V.email()):i==="uri"||i==="uri-reference"?n=n.check(V.url()):i==="uuid"||i==="guid"?n=n.check(V.uuid()):i==="date-time"?n=n.check(V.iso.datetime({offset:!0})):i==="date"?n=n.check(V.iso.date()):i==="time"?n=n.check(V.regex(Afe)):i==="duration"?n=n.check(V.iso.duration()):i==="hostname"?n=n.check(V.hostname()):i==="ipv4"?n=n.check(V.ipv4()):i==="ipv6"?n=n.check(V.ipv6()):i==="mac"?n=n.check(V.mac()):i==="cidr"?n=n.check(V.cidrv4()):i==="cidr-v6"?n=n.check(V.cidrv6()):i==="base64"?n=n.check(V.base64()):i==="base64url"?n=n.check(V.base64url()):i==="e164"?n=n.check(V.e164()):i==="credit_card"?n=n.check(V.creditCard()):i==="iban"?n=n.check(V.iban()):i==="jwt"?n=n.check(V.jwt()):i==="emoji"?n=n.check(V.emoji()):i==="nanoid"?n=n.check(V.nanoid()):i==="cuid"?n=n.check(V.cuid()):i==="cuid2"?n=n.check(V.cuid2()):i==="ulid"?n=n.check(V.ulid()):i==="xid"?n=n.check(V.xid()):i==="ksuid"&&(n=n.check(V.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?V.number().int():V.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=V.boolean();break}case"null":{o=V.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?en(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=en(p,e);ur(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let h of p){let y=en(d[h],e),w=V.string().regex(new RegExp(h));f.push(V.looseRecord(w,y))}let m=[];if(Object.keys(n).length>0&&m.push(V.object(n).passthrough()),m.push(...f),m.length===0)o=V.object({}).passthrough();else if(m.length===1)o=m[0];else{let h=V.intersection(m[0],m[1]);for(let y=2;y<m.length;y++)h=V.intersection(h,m[y]);o=h}if(t.additionalProperties===!1){let h=Object.keys(n),y=p.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!Yn(b.value))return;let _=[];for(let x of Object.keys(b.value))h.includes(x)||y.some($=>$.test(x))||_.push(x);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=V.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=en(p,e)}o=Efe(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=>en(d,e)),c=yB(a,s),u=Array.isArray(i)?void 0:wB(i,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>en(d,e)),c=yB(a,s),u=wB(t.additionalItems,e),l=V.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(V.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(V.maxLength(t.maxItems)))}else if(i!==void 0){let s=en(i,e),a=V.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=V.array(V.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=$fe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?en(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 en(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r=bB(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=>en(u,e)),c=V.union(a);r=o?V.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>en(u,e)),c=V.xor(a);r=o?V.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:V.any();else{let a=o?r:en(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=V.intersection(a,en(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=V.nullable(r)),t.readOnly===!0&&(r=V.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!Ch(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&&!Ch(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))bfe.has(a)||ur(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function _B(t,e){if(typeof t=="boolean")return t?V.any():V.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=_fe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??lr};return en(r,i)}var SB=Symbol("z.visit/resolving");function Oh(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===SB)return new id({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,SB);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let h=n(u[m]);h!==u[m]&&(d=!0),p[m]=h}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?Ke(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:Ke(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?Ke(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:Ke(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:Ke(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?Ke(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:Ke(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:Ke(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:Ke(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:Ke(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return Ke(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 xB(t){return Oh(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:ot(r.options)}})}function Tfe(t,e){if(!e?.length)return t;let r=t._zod.def;return Ke(t,Xn(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function EB(t){return Tfe(t.out,t.checks)}function Pfe(t){return t.in._zod.traits.has("$ZodTransform")?EB(t):t.in}function kB(t){return Oh(t,{pipe:e=>Pfe(e._zod.def),default:(e,r)=>r?st(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function IB(t){return Oh(t,{pipe:e=>EB(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var jC={};vt(jC,{bigint:()=>Nfe,boolean:()=>Ofe,date:()=>Dfe,number:()=>Cfe,string:()=>Rfe});function Rfe(t){return UP(Td,t)}function Cfe(t){return FP(Pd,t)}function Ofe(t){return VP(Rd,t)}function Nfe(t){return BP(Cd,t)}function Dfe(t){return HP(Eh,t)}var Nh={name:"@tomato414941/foundation",version:"3.2.1",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};var Dd=new TextEncoder,zd=new TextDecoder,$B=new TextDecoder("utf-8",{fatal:!0}),RS=2**32;function tn(...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 MC(t,e,r){if(e<0||e>=RS)throw new RangeError(`value must be >= 0 and <= ${RS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function UC(t){let e=Math.floor(t/RS),r=t%RS,o=new Uint8Array(8);return MC(o,e,0),MC(o,r,4),o}function CS(t){let e=new Uint8Array(4);return MC(e,t),e}var jfe=/[^\x00-\x7f]/;function pr(t){if(typeof t=="string"&&t.length>=128){if(jfe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return Dd.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 AB(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 TB(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 OS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Us=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 xu=class extends Us{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},ut=class extends Us{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ra=class extends Us{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},M=class extends Us{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},xt=class extends Us{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var Dh=class extends Us{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var NS=class extends Us{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var Mfe="The input to be decoded is not correctly encoded.";function Eu(t){try{return TB(typeof t=="string"?t:zd.decode(t),!0)}catch(e){throw new TypeError(Mfe,{cause:e})}}function Tt(t){return AB(typeof t=="string"?Dd.encode(t):t,!0)}function Nn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Bt(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 Ca(...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 eo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function vn(t,e,r){try{return Eu(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function DS(t,e,r){try{return pr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function jd(t,e,r){let o;try{o=JSON.parse($B.decode(Eu(t)))}catch{throw new e(r)}if(!Bt(o))throw new e(r);return o}var zS={__proto__:null,b64:!0},jS={__proto__:null};function zh(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function MS(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Oa(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 ut(`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 US(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function ku(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(!Bt(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var Ufe=t=>t[Symbol.toStringTag],Lfe=(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 Lo(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(Bt(e)){if(s=qC(e),typeof s.kty!="string")throw PB(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(Lfe(t,s,r),s.kty==="oct")return Eu(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!VC(e))throw PB(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${Ufe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Na(e))return e;if(a=e,a.type==="secret")return a.export()}LC||=new WeakMap;let c=e,u=LC.get(c);if(u?.[o])return u[o];if(u||LC.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Ffe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await Ud(t,s)}var LC,Ffe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function FS(t){if(!Na(t))throw new Error("CryptoKey instance expected")}var Na=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},FC=t=>t?.[Symbol.toStringTag]==="KeyObject",VC=t=>Na(t)||FC(t);function RB(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 Ls=(t,...e)=>RB("Key must be ",t,...e);function PB(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(RB(`Key for the ${t} algorithm must be `,e,...o))}var LS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function BC(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Md(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 HC(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw LS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw LS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw LS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw LS(e.length,"algorithm.length");BC(t,r)}function VS(t){return{__proto__:null,...t}}function qC(t){let e=VS(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function BS(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function Ud(t,e,r){if(!t.kty.includes(e.kty))throw new ut('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 Fo(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),HC(t,e,r),t}var Iu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function HS(t,e){let r=t.byteLength<<3;if(r!==e)throw new M(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var Vfe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function CB(t,e){if(e.length<<3!==t.ivBits)throw new M("Invalid Initialization Vector length")}async function OB(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Ls(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 NB(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Bfe(t,e,r,o,n){let[i,s,a]=await OB(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=tn(n,o,c,UC(n.length*8)),l=await NB(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Hfe(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 qfe(t,e,r,o,n,i){let[s,a,c]=await OB(t,e,"decrypt"),u=tn(i,o,r,UC(i.length*8)),l=await NB(a,u,c);try{if(await Hfe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Ra}async function qS(t,e,r,o,n){if(!Na(r)&&!(r instanceof Uint8Array))throw new TypeError(Ls(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?CB(t,o):o=Vfe(t),r instanceof Uint8Array&&HS(r,t.cekBits),t.cbc)return Bfe(t,e,r,o,n);let i=await Fo(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 ZS(t,e,r,o,n,i){if(!Na(e)&&!(e instanceof Uint8Array))throw new TypeError(Ls(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new M("JWE Initialization Vector missing");if(!n)throw new M("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new M("Invalid Authentication Tag length");if(CB(t,o),e instanceof Uint8Array&&HS(e,t.cekBits),t.cbc)return qfe(t,e,r,o,n,i);let s=await Fo(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,tn(r,n)))}catch{throw new Ra}}function jh(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var Zfe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Kfe=[[],["deriveBits"]],JS=[[],[]];function KS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:Zfe,ops:["wrapKey","unwrapKey"]}}function WS(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 ut('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Kfe,ops:[void 0,"deriveBits"]}}function Ld(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:JS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function ZC(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:JS,ops:["deriveBits","deriveBits"]}}var Fs=jh({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:JS,ops:["encrypt","decrypt"]},"RSA-OAEP":KS(1),"RSA-OAEP-256":KS(256),"RSA-OAEP-384":KS(384),"RSA-OAEP-512":KS(512),"ECDH-ES":WS("direct-key-agreement"),"ECDH-ES+A128KW":WS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":WS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":WS("key-agreement-with-key-wrapping"),A128KW:Ld(128),A192KW:Ld(192),A256KW:Ld(256),A128GCMKW:Ld(128,!0),A192GCMKW:Ld(192,!0),A256GCMKW:Ld(256,!0),"PBES2-HS256+A128KW":ZC(),"PBES2-HS384+A192KW":ZC(),"PBES2-HS512+A256KW":ZC()}),Wfe=["encrypt","decrypt"];function Fd(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:JS,ops:Wfe,cekBits:t,ivBits:e?128:96,cbc:e}}var Jfe=jh({A128GCM:Fd(128),A192GCM:Fd(192),A256GCM:Fd(256),"A128CBC-HS256":Fd(256,!0),"A192CBC-HS384":Fd(384,!0),"A256CBC-HS512":Fd(512,!0)});function DB(t,e){throw new ut(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Vo(t){return(typeof t=="string"?Fs[t]:void 0)??DB("alg","Algorithm")}function Bo(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function $u(t){return(typeof t=="string"?Jfe[t]:void 0)??DB("enc","Encryption Algorithm")}function zB(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");BC(t,e)}async function Gfe(t,e,r){let o=await Fo(e,Vo(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 Xfe(t,e,r){let o=await Fo(e,Vo(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 MB(t,e,r){HC(e,Vo(t).subtle,r),Md(t,e)}async function UB(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new M("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new M("PBES2 Count Input must be a positive integer");let n=tn(pr(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 Fo(o,Vo(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KC(t){return tn(CS(t.length),t)}async function Yfe(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 OS("sha256",tn(CS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function LB(t,e,r,o,n=new Uint8Array,i=new Uint8Array){zB(t),zB(e,"deriveBits");let s=tn(KC(pr(r)),KC(n),KC(i),CS(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return Yfe(a,o,s)}function FB(t){FS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new ut("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function GS(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new M(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return vn(r,e,M)}}function VB(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 M('JOSE Header "apu" and "apv" values must be distinct')}}function Qfe(t){if(t===void 0)throw new M("JWE Encrypted Key missing")}function jB(t){if(t!==void 0)throw new M("Encountered unexpected JWE Encrypted Key")}function epe(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 BB(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return jB(o),r;let c=a==="direct-key-agreement";switch(c?jB(o):Qfe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Bt(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new M('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');FB(r);let l=await Ud(t,u),d=GS(n,"apu"),p=GS(n,"apv");VB(d,p);let f=await LB(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return FS(r),MB(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new M('JOSE Header "p2c" (PBES2 Count) missing or invalid');epe(i);let u=i??1e4;if(n.p2c>u)throw new M('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new M('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=vn(n.p2s,"p2s",M);r=await UB(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new M('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new M('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=vn(n.iv,"iv",M),l=vn(n.tag,"tag",M);if(u.byteLength!==12)throw new M("Invalid Initialization Vector length");if(l.byteLength!==16)throw new M("Invalid Authentication Tag length");return ZS($u(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return Xfe(s.slice(-6),r,o)}async function XS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Bo(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Lo(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Iu(e):void 0;l&&HS(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{FB(u);let{apu:f,apv:m}=i;f!==void 0&&Nn(f,'"apu"'),m!==void 0&&Nn(m,'"apv"');let h=f??GS(o,"apu"),y=m??GS(o,"apv");VB(h,y);let w;i.epk!==void 0?w=await Lo(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,y:$,crv:O,kty:H}=await b.exportKey("jwk",_),te=a==="direct-key-agreement",Ie=await LB(u,w,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),h,y),xe={x,crv:O,kty:H};if(H==="EC"&&(xe.y=$),p={epk:xe},f!==void 0&&(p.apu=Tt(f)),m!==void 0&&(p.apv=Tt(m)),te)return[Ie,void 0,p];u=Ie;break}case"RSA-OAEP":{FS(u),MB(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await UB(m,s,f,u),p={p2c:f,p2s:Tt(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await qS($u(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:Tt(m.iv),tag:Tt(m.tag)}}}if(d??=await Gfe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function YS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new ut('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new M('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function HB(t){if(typeof globalThis[t]>"u")throw new ut(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function qB(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 M("Decompressed plaintext exceeded the configured limit")}return tn(...n)}async function ZB(t){return HB("CompressionStream"),qB(new CompressionStream("deflate-raw"),t)}async function KB(t,e){return HB("DecompressionStream"),qB(new DecompressionStream("deflate-raw"),t,e)}function WB(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 M("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new M("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new M("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new M("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new M("JWE AAD incorrect type");if(s!==void 0&&!Bt(s))throw new M("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 JB(t){let e,r;try{let{header:o}=t;if(Bt(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 GB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new M("JWE Encrypted Key incorrect type");if(r!==void 0&&!Bt(r))throw new M("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new M("JOSE Header missing")}function WC(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=jd(e,M,"JWE Protected Header is invalid")),[s,vn(r,"ciphertext",M),o!==void 0?vn(o,"iv",M):void 0,n!==void 0?vn(n,"tag",M):void 0,DS((e??"")+(i!==void 0?`.${i}`:""),"aad",M)]}function QS(t){return[t&&zh("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&zh("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function JC(t,e,r,o=WC(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Ca(n,u,l))throw new M("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,h,y,w]=e,{encrypted_key:b}=t;Oa(M,jS,h,n,p),YS(p,n);let{alg:_,enc:x}=p;if(typeof _!="string"||!_)throw new M("missing JWE Algorithm (alg) in JWE Header");let $=Fs[_];if(b===""&&(!$||!Bo($)))throw new M("JWE Encrypted Key incorrect type");let O=$?.mode==="integrated-encryption";if(!O&&(typeof x!="string"||!x))throw new M("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(_)||!f&&_.startsWith("PBES2"))throw new xu('"alg" (Algorithm) Header Parameter value not allowed');let H;if(O){if(x!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new M("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new M("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(x))throw new xu('"enc" (Encryption Algorithm) Header Parameter value not allowed');H=$u(x)}let te;if(b!==void 0)try{te=vn(b,"encrypted_key",M)}catch($e){if(!$||!Bo($))throw $e;te=new Uint8Array}let Ie=!1;typeof r=="function"&&(r=await r(n,t),Ie=!0);let xe=$??Vo(_);Bo(xe)&&te===void 0&&(te=new Uint8Array);let rt=await Lo(xe.mode==="direct-encryption"?H:xe,r,"decrypt"),Ve;if(xe.mode==="integrated-encryption")Ve=await xe.decrypt(rt,te,i,c,n,p);else{let $e=H,J;try{J=await BB(xe,$e,rt,te,p,y),Bo(xe)&&J instanceof Uint8Array&&J.byteLength<<3!==$e.cekBits&&(J=Iu($e))}catch($t){if($t instanceof TypeError||$t instanceof M||$t instanceof ut)throw $t;J=Iu($e)}Ve=await ZS($e,J,i,s,a,c)}if(p.zip==="DEF"){let $e=w??25e4;if($e===0)throw new ut('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if($e!==1/0&&(!Number.isSafeInteger($e)||$e<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");Ve=await KB(Ve,$e).catch(J=>{throw J instanceof M?J:new M("Failed to decompress plaintext",{cause:J})})}return{plaintext:Ve,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:vn(d,"aad",M)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ie&&{key:rt}}}async function XB(t,e,r){if(t instanceof Uint8Array&&(t=zd.decode(t)),typeof t!="string")throw new M("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 M("Invalid Compact JWE");return JC({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Mh(t,e,r){return XB(t,QS(r),e)}async function GC(t,e,r){if(!Bt(t))throw new M("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new M("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Bt))throw new M("JWE Recipients missing or incorrect type");if(!n.length)throw new M("JWE Recipients has no members");let i,s,a;try{i=QS(r),s=WB(t),a=WC(s)}catch{throw new Ra}let c=n.map(u=>JB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Fs[l]:void 0;if(d&&!Bo(d))throw new M(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return GB(l),await JC(l,i,e,a)}catch{}throw new Ra}function ex(t,e,r){if(!Ca(t,e,r))throw new M("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function XC(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new M("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&&Nn(s,"JWE Additional Authenticated Data"),a!==void 0&&Nn(a,"JWE Content Encryption Key"),c!==void 0&&Nn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=ku(M,o)[0],t[1]=o),n!==void 0&&(n=ku(M,n)[0],t[2]=n),!r&&i!==void 0&&(i=ku(M,i)[0],t[3]=i),u!==void 0&&!Bt(u))throw new TypeError("JWE Key Management Parameters must be an object");ex(o,n,i);let d={...o,...n,...i};MS(M,o),Oa(M,jS,l,o,d),YS(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new M('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Fs[p];if(m?.mode==="integrated-encryption"){if(f!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,$u(f),m]}async function YC(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,m]=t,h=a,y=c,w=i??Vo(o.alg),b,_,x;w.mode==="integrated-encryption"?x=await Lo(w,r,"encrypt"):[x,b,_]=await XS(w,n,r,o,d,f),_&&(m?y=y?{...y,..._}:_:h=h?{...h,..._}:_,ex(h,y,u));let $=h?Tt(JSON.stringify(h)):"",O=l?.byteLength?Tt(l):void 0,H=pr(O?`${$}.${O}`:$),te=s;o.zip==="DEF"&&(te=await ZB(te).catch($e=>{throw new M("Failed to compress plaintext",{cause:$e})}));let Ie,xe,rt;w.mode==="integrated-encryption"?[b,Ie]=await w.encrypt(x,te,H,h,o,f):{ciphertext:Ie,tag:xe,iv:rt}=await qS(n,te,x,p,H);let Ve={ciphertext:Tt(Ie)};return rt&&(Ve.iv=Tt(rt)),xe&&(Ve.tag=Tt(xe)),b?.byteLength&&(Ve.encrypted_key=Tt(b)),O&&(Ve.aad=O),h&&(Ve.protected=$),u&&(Ve.unprotected=u),y&&(Ve.header=y),Ve}async function YB(t,e,r){return YC(t,XC(t,r),e)}function QB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var QC=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return eo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return eo(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}},Uh=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new QC(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return eo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return eo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new M("at least one recipient must be added");Nn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[h,y,w,b]=m.state,_=[this.#e,o,h,n,this.#o,void 0,void 0,y,b,e],x=XC(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,x,w]);let[{alg:$,enc:O},,H]=x;if(e&&H&&!Bo(H))throw new M(`"${$}" alg may only have a single recipient`);if(!r)r=O;else if(r!==O)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Vo(m[0].alg);let[s,a,c]=i[0],u=e?Iu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await YC(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[h,[y,w,b],_]=i[m],x=h[2],[,$,O]=await XS(b,w,_,y,u,h[7]),H={encrypted_key:Tt($)};if(x||O){let te={...x,...O};O&&ex(h[1],te,h[3]),H.header=te}f.recipients.push(H)}return f}};var Lh=[["verify"],["sign"]];function eO(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Lh}}function Vd(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:Lh,minRsaBits:2048}}function tO(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Lh}}function eH(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Lh}}function rO(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Lh}}var nO=jh({HS256:eO(256),HS384:eO(384),HS512:eO(512),RS256:Vd(256),RS384:Vd(384),RS512:Vd(512),PS256:Vd(256,32),PS384:Vd(384,48),PS512:Vd(512,64),ES256:tO("P-256",256),ES384:tO("P-384",384),ES512:tO("P-521",512),EdDSA:eH(),Ed25519:eH(),"ML-DSA-44":rO(44),"ML-DSA-65":rO(65),"ML-DSA-87":rO(87)});function tx(t){let e=typeof t=="string"?nO[t]:void 0;if(!e)throw new ut(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function tH(t){return[t&&zh("algorithms",t.algorithms),t?.crit]}function tpe(t){return t===void 0?{}:jd(t,xt,"JWS Protected Header is invalid")}function rpe(t){try{return pr(t)}catch{throw new xt("JWS Compact Serialization payload must use only ASCII characters")}}async function npe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??tpe(i);if(!Ca(c,s))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=US(c,Oa(xt,zS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new xu('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new xt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let m=tx(d),h=tn(i!==void 0?pr(i):new Uint8Array,pr("."),typeof p=="string"?e[2]??=DS(p,"payload",xt):p),y=vn(t.signature,"signature",xt),w=await Lo(m,r,"verify"),b=await Fo(w,m.subtle,"verify");m.minRsaBits&&Md(m.alg,b);let _=!1;try{_=await crypto.subtle.verify(m.signing,b,y,h)}catch{}if(!_)throw new NS;let x={payload:typeof p=="string"?vn(p,"payload",xt):p};return i!==void 0&&(x.protectedHeader=c),s!==void 0&&(x.unprotectedHeader=s),f?[{...x,key:w},l]:[x,l]}async function rH(t,e,r){if(t instanceof Uint8Array&&(t=zd.decode(t)),typeof t!="string")throw new xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new xt("Invalid Compact JWS");return npe({payload:n,protected:o,signature:i},e,r,rpe)}async function oO(t,e,r){let[o]=await rH(t,tH(r),e);return o}var Bd=class{#e;constructor(e){Nn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return eo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return eo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return eo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return eo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return QB(await YB([...this.#e],e,r))}};async function ope(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=ku(xt,n);n=w[0],a=Tt(w[1])}if(i!==void 0&&(i=ku(xt,i)[0]),!n&&!i)throw new xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Ca(n,i))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};MS(xt,n);let u=US(n,Oa(xt,zS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=tx(l),p="",f=o,m;if(u){let w=t[4];w?(p=w[0]??=Tt(o),f=w[1]??=pr(p)):(p=Tt(o),m=Dd.encode(`${a}.${p}`))}m??=tn(pr(a),pr("."),f);let h=await Fo(await Lo(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&Md(d.alg,h);let y={signature:Tt(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:p};return n&&(y.protected=a),i&&(y.header=i),[y,u]}async function nH(t,e,r,o,n){let[i]=await ope([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Fh=class{#e;#t;constructor(e){Nn(e,"payload"),this.#e=e}setProtectedHeader(e){return eo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return nH(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var iO='"alg" (Algorithm)';function sO(t='JWK "alg" (Algorithm) Parameter'){throw new ut(`Invalid or unsupported ${t} value`)}function Vh(t,e){return(typeof t=="string"?nO[t]??Fs[t]:void 0)??sO(e)}async function Da(t){if(FC(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Tt(t)};if(!Na(t))throw new TypeError(Ls(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 Vs=(t,e)=>{if(typeof t!="string"||!t)throw new Dh(`${e} missing or invalid`)};async function aO(t,e){let r;if(Bt(t)){if(r=VS(t),typeof r.kty!="string")throw new TypeError(Ls(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(VC(t))r=VS(await Da(t));else throw new TypeError(Ls(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":Vs(r.alg,'"alg" (Algorithm) Parameter'),Vs(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Vs(r.crv,'"crv" (Curve) Parameter'),Vs(r.x,'"x" (X Coordinate) Parameter'),Vs(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Vs(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Vs(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Vs(r.e,'"e" (Exponent) Parameter'),Vs(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 Dh('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new ut('"kty" (Key Type) Parameter missing or unsupported')}let n=pr(JSON.stringify(o));return Tt(await OS(e,n))}async function to(t,e,r){if(!Bt(t))throw new TypeError("JWK must be an object");let o=qC(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 Eu(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 Ud(Vh(e),o,n)}case"RSA":case"EC":case"OKP":return Ud(Vh(e),o,n);default:throw new ut('Unsupported "kty" (Key Type) Parameter value')}}function cO(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 jd(e,TypeError,r)}function ipe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new ut("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Bh(t,e){let r=BS(e?.extractable),o=Vh(t,iO);o.secret&&sO(iO);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new ut("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 ut(`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:ipe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}typeof window<"u"&&g.config({jitless:!0});var k=g.uuid(),le=g.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Be=g.iso.datetime(),ro=g.json(),Au=g.record(g.string(),ro),iH=g.enum(["ja","en"]),sH=g.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var aH=g.enum(["variable","connection","service","method","app","object","environment","function"]),Nr=g.object({kty:g.literal("EC"),crv:g.literal("P-256"),x:g.string().min(40).max(50),y:g.string().min(40).max(50)}).strict(),spe=g.object({alg:g.literal("dir"),enc:g.literal("A256GCM"),sub:k}).strict(),ox=g.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 spe.safeParse(cO(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ho=g.object({protected:g.string().max(2048),iv:g.string().max(64),ciphertext:g.string().max(2e6),tag:g.string().max(64),aad:g.string().max(2048).optional(),recipients:g.array(g.object({encrypted_key:g.string().max(2048),header:g.object({kid:k,epk:Nr.optional(),alg:g.string().optional()}).passthrough()})).min(1).max(100)}).strict(),H2e=g.object({id:k,name:le,publicKey:Nr}),Hd=g.object({id:k,name:le,owner:g.object({id:k,name:le}).nullable(),createdAt:Be,permissions:g.array(sH),createKinds:g.array(aH),publicKey:Nr.nullable()}),cH=g.object({id:k,kind:g.enum(["passkey","email","key"]),name:g.string(),createdAt:Be,lastUsedAt:Be.nullable(),expiresAt:Be.nullable(),canOpen:g.boolean()}),uH=g.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ape=g.object({subjectId:k,relation:uH,objectId:k}).strict(),q2e=ape.extend({objectType:g.enum(["principal",...aH.options]),subjectName:le,objectName:le,createdAt:Be}),Z2e=g.object({error:g.object({code:g.string(),message:g.string(),details:ro.optional()})}),K2e=g.object({ok:g.literal(!0)}),lH=g.object({name:g.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:g.string(),secret:g.boolean().optional(),required:g.boolean().optional(),placeholder:g.string().optional(),note:g.string().optional(),pattern:g.string().optional()}),dH=g.record(g.string().regex(/^[A-Z_][A-Z0-9_]*$/),g.string()),cpe=g.object({values:g.array(g.object({id:g.string(),name:g.string(),description:g.string().optional()})).optional(),default:g.array(g.string()).default([]),separator:g.string().default(" "),docs:g.url().optional()}),rx=g.string().min(1).max(4096),oH=g.union([g.string(),g.array(g.string()).min(1)]),fH=g.object({grantType:g.enum(["authorization_code","client_credentials"]).optional(),issuer:g.url().optional(),authorizeUrl:rx.optional(),tokenUrl:rx,identity:g.object({url:rx.optional(),from:g.enum(["token","app"]).optional(),method:g.enum(["GET","POST"]).default("GET"),id:oH.default("/id"),name:oH.default("/name"),headers:g.record(g.string(),g.string()).default({})}).optional(),revoke:g.object({url:rx,style:g.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:g.enum(["body","basic","none"]).optional()}).optional(),clientAuth:g.enum(["body","basic","none"]).default("body"),pkce:g.boolean().default(!0),tokenFormat:g.enum(["form","json"]).default("form"),okPointer:g.string().optional(),authorizeParams:g.record(g.string(),g.string()).default({}),tokenParams:g.record(g.string(),g.string()).default({}),defaults:g.record(g.string(),g.string()).default({}),scopes:cpe.default({default:[],separator:" "}),fields:g.array(lH).default([]),outputs:dH.default({ACCESS_TOKEN:"/accessToken"}),adapter:g.enum(["google","github","ebay","openrouter","cloudflare","slack"]).optional(),keep:g.array(g.string()).default([]),hint:g.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),pH=g.object({fields:g.array(lH).min(1),outputs:dH,console:g.url().optional(),instructions:g.string().optional(),hint:g.string().optional()}),lO=g.enum(["oauth","token","role"]),mH=g.object({kind:g.literal("aws"),hint:g.string().optional()}),dO={name:le,docs:g.url().optional(),console:g.url().optional()},hH=g.object({...dO,kind:g.literal("oauth"),config:fH}).strict(),gH=g.object({...dO,kind:g.literal("token"),config:pH}).strict(),yH=g.object({...dO,kind:g.literal("role"),config:mH}).strict(),Tu=g.discriminatedUnion("kind",[hH,gH,yH]),uO={id:g.string().min(1),builtin:g.boolean(),availability:g.enum(["ready","app-required","unavailable"])},fO=g.discriminatedUnion("kind",[hH.extend(uO),gH.extend(uO),yH.extend(uO)]),pO=g.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),ix=g.object({name:le,logo:g.string().regex(/^[a-z0-9-]+$/).optional(),api:g.url().optional(),docs:g.url().optional(),console:g.url().optional()}).strict(),upe=ix.extend({auth:g.object({oauth:fH.optional(),token:pH.optional(),role:mH.optional()}).strict()}).strict(),lpe=ix.extend({methods:g.record(pO,g.string().min(1))}).strict(),dpe=ix.extend({methods:g.record(pO,g.union([g.string().min(1),Tu]))}).strict(),vH=g.union([dpe,upe]),W2e=ix.extend({id:g.string(),builtin:g.boolean(),methods:g.record(pO,fO)}),wH=g.object({id:k,output:g.string().min(1).max(100).optional()}).strict(),mO=g.object({name:g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:wH,format:g.enum(["text","file","json"]).default("text"),pointer:g.string().optional()}).strict(),fpe=g.object({pointer:g.string().max(500),parts:g.array(g.union([g.string().max(8192),wH])).min(1).max(32)}).strict(),Pu=g.object({url:g.string().max(4096),method:g.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:g.record(g.string(),g.string().max(8192)).default({}),body:g.string().max(1e6).optional(),json:ro.optional(),form:g.record(g.string(),g.string()).optional(),bindings:g.array(fpe).max(32).default([])}).strict(),Hh=g.object({description:g.string().max(2e3).default(""),request:Pu,parameters:g.array(g.object({name:g.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:g.string().max(100),required:g.boolean().default(!0),default:g.string().optional()})).max(32).default([]),save:g.record(g.string(),le).default({}),outputOwnerId:k.optional()}).strict(),za={id:k,ownerId:k,name:le,createdAt:Be,updatedAt:Be,version:g.number().int().positive(),permissions:g.array(sH)},ppe=g.enum(["starting","running","stopping","stopped","failed"]),mpe=g.object({state:g.enum(["pending","failed","complete"]),error:g.string().nullable()}),hpe=g.object({idleSeconds:g.number().int().min(60).max(86400).default(3600),maxSeconds:g.number().int().min(60).max(86400).default(3600)}).strict(),bH=g.object({image:g.string().min(1).max(300).optional(),size:g.enum(["small","medium","large"]).default("small"),lifetime:hpe.default({idleSeconds:3600,maxSeconds:3600})}).strict(),hO={recipients:g.array(k).default([]),executors:g.array(k).default([]),custodyRevision:g.number().int().positive().nullable().default(null)},gpe=g.object({...za,kind:g.literal("variable"),data:g.object({...hO,bytes:g.number().int().nonnegative()})}),ype=g.object({...za,kind:g.literal("connection"),data:g.object({...hO,methodId:g.string(),methodName:g.string(),methodKind:lO,services:g.array(g.object({id:g.string(),name:le})).default([]),account:g.string(),accountId:g.string().nullable().default(null),accountVerified:g.boolean().default(!1),scopes:g.array(g.string()),scopesStatus:g.enum(["unknown","requested","reported"]).default("unknown"),outputs:g.array(g.string()),state:g.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:k.nullable(),generation:k.optional(),authorizationDigest:g.string().optional()})}),vpe=g.object({...za,kind:g.literal("service"),data:lpe}),wpe=g.object({...za,kind:g.literal("method"),data:Tu}),bpe=g.object({...za,kind:g.literal("app"),data:g.object({...hO,methodId:g.string(),clientId:g.string(),fields:g.record(g.string(),g.string()).default({}),generation:k.optional()})}),_pe=g.object({...za,kind:g.literal("object"),data:g.object({size:g.number().int().nonnegative(),contentType:g.string()})}),Spe=g.object({...za,kind:g.literal("environment"),data:bH.extend({executorId:k.optional(),operatorId:k.optional(),driver:g.enum(["attached","managed"]).optional(),capabilities:g.array(g.string()).optional(),isolation:g.enum(["process","container"]).optional(),manifestDigest:g.string().optional(),processes:g.object({workingDirectory:g.string()}).optional(),awsPrincipal:g.string().optional(),state:ppe,deletion:mpe.optional(),startedAt:Be.nullable(),stoppedAt:Be.nullable(),lastActiveAt:Be,error:g.string().nullable()})}),xpe=g.object({...za,kind:g.literal("function"),data:Hh}),no=g.discriminatedUnion("kind",[gpe,ype,vpe,wpe,bpe,_pe,Spe,xpe]),J2e=g.discriminatedUnion("kind",[g.object({kind:g.literal("service"),name:le,definition:vH}).strict(),g.object({kind:g.literal("method"),name:le,definition:Tu}).strict(),g.object({kind:g.literal("environment"),name:le.optional(),options:bH}).strict(),g.object({kind:g.literal("function"),name:le,definition:Hh}).strict()]),G2e=g.object({version:g.number().int().positive(),name:le.optional(),definition:g.union([vH,Tu,Hh]).optional()}).strict(),sx=g.object({command:g.array(g.string().max(8192)).min(1).max(100),stdin:g.string().max(1e6).optional(),timeoutSeconds:g.number().int().min(1).max(3600).default(60),inputs:g.array(mO).max(32).default([])}).strict(),_H=g.object({method:g.enum(["GET","POST","PUT","PATCH","DELETE","CONNECT"]),path:g.string().startsWith("/api/").max(2048),body:ro.optional(),inputs:g.array(g.object({pointer:g.string(),label:g.string().min(1).max(100),secret:g.boolean().default(!1),multiline:g.boolean().default(!1),site:g.url().optional()})).max(16).default([])}).strict(),Epe=g.object({ja:g.string(),en:g.string()}).strict(),SH=g.object({ownerId:g.union([k,g.literal("$approver")]),methodId:g.string().min(1).max(200),connectionId:k.optional(),environmentId:k.optional(),name:le.optional()}).strict(),xH=g.object({to:k.optional(),message:g.string().max(1e3).default(""),operations:g.array(_H).min(1).max(8),expiresInMinutes:g.number().int().min(1).max(1440).default(30)}).strict(),nx=g.object({id:k,name:le}),kpe=g.discriminatedUnion("kind",[g.object({kind:g.literal("line"),subject:nx,relation:uH,object:nx}),g.object({kind:g.literal("transfer"),item:nx,to:nx})]),ja=g.object({id:k,from:Hd.pick({id:!0,name:!0}),to:Hd.pick({id:!0,name:!0}).nullable(),message:g.string(),proposal:kpe.nullable(),operations:g.array(_H.extend({title:Epe})),state:g.enum(["pending","running","approved","declined","cancelled","expired"]),results:g.array(ro.nullable()),createdAt:Be,expiresAt:Be,url:g.url(),code:g.string().optional(),continueUrl:g.url().nullable(),returnUrl:g.url().nullable(),refreshUrl:g.url().nullable(),canRespond:g.boolean()}),X2e=g.object({id:k,name:le,publicKey:Nr,state:g.enum(["pending","approving","approved"]),principalId:k.nullable(),createdAt:Be,expiresAt:Be}),Y2e=g.object({available:g.boolean(),required:g.boolean(),active:g.boolean(),payer:Hd.pick({id:!0,name:!0}).nullable()}),Q2e=g.object({storageBytes:g.number().nonnegative(),storageLimit:g.number().positive(),computeSeconds:g.number().nonnegative(),computeLimit:g.number().positive(),month:g.string()}),e6e=g.object({id:g.string(),actorId:k.nullable(),action:g.string(),targetId:k.nullable(),createdAt:Be,details:Au}),t6e=g.object({returnUrl:g.url().optional(),refreshUrl:g.url().optional()}).strict(),Ma=t=>g.object({items:g.array(t),next:g.string().nullable().default(null)}),r6e=g.object({id:k}),n6e=g.object({owner:k}),Ipe=g.object({limit:g.coerce.number().int().min(1).max(200).default(100),after:g.string().optional()}),o6e=Ipe.extend({object:k.optional(),subject:k.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var $pe=new TextEncoder,Ape=new TextDecoder,qh="ECDH-ES+A256KW",gO="A256GCM",lt=t=>$pe.encode(t),Ru=t=>Ape.decode(t);function Ua(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 EH(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function ax(){let t=await Bh(qh,{crv:"P-256",extractable:!0});return{publicKey:Nr.parse(await Da(t.publicKey)),privateKey:await Da(t.privateKey)}}async function Cu(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 Uh(t).setProtectedHeader({enc:gO}).setAdditionalAuthenticatedData(lt(r));for(let n of e)o.addRecipient(await to(n.publicKey,qh)).setUnprotectedHeader({alg:qh,kid:n.id});return Ho.parse(await o.encrypt())}async function Ni(t,e,r,o){if(t.aad!==Ua(lt(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 to(e,qh);return(await GC({...t,recipients:[n]},i,{keyManagementAlgorithms:[qh],contentEncryptionAlgorithms:[gO]})).plaintext}async function Tpe(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:lt("Foundation"),info:lt("passkey encryption key")},e,256))}async function kH(t,e,r){let o=await Mh(t,await Tpe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[gO]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Ru(o.plaintext))}var mr=g.string().regex(/^[A-Za-z0-9_-]{43}$/),Dn=g.string().min(100).max(4e6),IH=Nr.extend({d:g.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Zh=g.object({encryption:IH,signing:IH}).strict(),hr=g.object({id:k,principalId:k,generation:g.number().int().positive(),previous:mr.nullable(),encryption:Nr,signing:Nr}).strict();function R(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,R).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)+":"+R(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function qd(t){return aO(Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function Ne(t){return Ua(new Uint8Array(await crypto.subtle.digest("SHA-256",lt(R(t)))))}async function Ou(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",lt(R(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function ux(){let[t,e]=await Promise.all([ax(),Bh("ES256",{crv:"P-256",extractable:!0})]),r=await Da(e.privateKey);return Zh.parse({encryption:t.privateKey,signing:r})}function cx(t){return Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function lx(t,e){return hr.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:cx(e.encryption),signing:cx(e.signing)})}async function wn(t,e,r){let o=e instanceof CryptoKey?e:await to(e,"ES256");return new Fh(lt(R(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function oo(t,e,r,o){if(R(await yO(e,r,o))!==R(t))throw new Error("The signature does not authorize this content.")}async function yO(t,e,r){let o=await oO(t,await to(Nr.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(R(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Di=g.object({binding:hr,signature:Dn}).strict();async function Kh(t,e){if(await La(t),await qd(e.encryption)!==await qd(t.encryption)||await qd(e.signing)!==await qd(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await wn(t,e.signing,"key-binding")}}async function La(t){let e=hr.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await qd(e.encryption)===await qd(e.signing))throw new Error("Use separate encryption and signing keys.");await to(e.encryption,"ECDH-ES+A256KW"),await to(e.signing,"ES256")}async function vO(t){let{binding:e,signature:r}=Di.parse(t);return await La(e),await oo(e,r,e.signing,"key-binding"),e}var Zd=g.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."),Me={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632"},Ppe=g.enum([Me.value,Me.tokenSet,Me.clientCredential]),pe={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"},dx=g.enum([pe.http,pe.command,pe.function,pe.connect,pe.refresh,pe.revoke]);var Rpe={[Me.value]:[pe.http,pe.command,pe.function],[Me.tokenSet]:[pe.http,pe.command,pe.function,pe.refresh,pe.revoke],[Me.clientCredential]:[pe.connect,pe.refresh,pe.revoke]},wO=t=>Rpe[t],bO=t=>t===Me.tokenSet,Cpe=g.object({actor:hr,executor:hr,operations:g.array(dx).min(1).max(6),functionDigests:g.array(mr).max(100).default([]),origins:g.array(Zd).max(100).default([]),callerProgram:g.boolean().default(!1),expiresAt:Be}).strict(),zi=g.object({format:g.literal(2),origin:Zd,id:k,ownerId:k,contentType:Ppe,revision:g.number().int().positive(),authorities:g.array(hr).min(1).max(100),readers:g.array(hr).min(1).max(100),grants:g.array(Cpe).max(100),observers:g.array(k).max(100).optional(),producers:g.array(g.object({executor:hr,runId:k,expiresAt:Be,materialRevision:g.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),$H=g.object({ownerId:k,authorities:g.array(hr).min(1).max(100)}).strict(),AH=g.object({origin:Zd,id:k,revision:g.number().int().positive(),from:$H,to:$H,policyDigest:mr,previous:mr.nullable(),signerId:k}).strict(),Ope=AH.extend({signature:Dn}),_O=g.array(Ope).max(16),Wh=g.object({policy:zi,authorityId:k,signature:Dn,lineage:_O.optional()}).strict(),io=g.object({policy:zi,authorityId:k,authorization:Dn,lineage:_O.optional(),materialRevision:g.number().int().positive(),updatedAt:Be,creationRunId:k.nullable(),metadata:Au,sealed:Ho,signerId:k,signature:Dn}).strict(),Nu=t=>({ownerId:t.ownerId,authorities:t.authorities});async function TH(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||R(r.to)!==R(o.from))||o.previous!==(r?await Ne(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 oo(i,n,s.signing,"authority-handoff"),r=o}if(r&&R(r.to)!==R(Nu(t)))throw new Error("Use the authorities approved by the latest handoff.")}function SO(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 PH(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=R(Nu(t));return r===R(Nu(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&R(o.from)===r)}async function RH(t,e,r,o){let n=[...t?.lineage??[]];if(t&&R(Nu(t.policy))!==R(Nu(e))){if(await qo(t),!t.policy.authorities.some(s=>R(s)===R(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=AH.parse({origin:e.origin,id:e.id,revision:e.revision,from:Nu(t.policy),to:Nu(e),policyDigest:await Ne(e),previous:n.length?await Ne(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await wn(i,o.signing,"authority-handoff")})}return n.length?{lineage:_O.parse(n)}:{}}async function fx(t){let e=zi.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>[n.actor,n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await La(n);let i=R(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=>!wO(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if(n.operations.some(i=>i===pe.http||i===pe.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(pe.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function px(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Kd(t,e){return R({purpose:"resource",policyDigest:await Ne(t),materialRevision:e})}async function xO(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await fx(e),c=await RH(s,a,o,n);if(!a.authorities.some(p=>R(p)===R(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Cu(t,px(a).map(p=>({id:p.id,publicKey:p.encryption})),await Kd(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await wn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===Me.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=io.parse({...l,signature:await wn(l,n.signing,"resource")});return await qo(d),d}async function qo(t){let e=io.parse(t),{signature:r,...o}=e;await fx(e.policy),await TH(e.policy,e.lineage);let n=SO(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await Ne(e.policy))throw new Error("The handoff approves a different access policy.");await oo(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&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor??(bO(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(pe.refresh)&&Date.parse(u.expiresAt)>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 oo(o,r,s.signing,"resource");let a=px(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(R(a)!==R(c)||e.sealed.aad!==Ua(lt(await Kd(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function CH(t,e,r,o,n=t.metadata){let i=await qo(t);if(!bO(i.policy.contentType)||!(i.policy.authorities.some(p=>R(p)===R(r))||i.policy.grants.some(p=>R(p.executor)===R(r)&&p.operations.includes(pe.refresh)&&Date.parse(p.expiresAt)>Date.now())))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 Cu(e,px(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await Kd(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 wn(l,o.signing,"resource")};return await qo(d),d}async function mx(t,e,r,o){let n=await fx(t);if(!n.authorities.some(s=>R(s)===R(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await RH(o,n,e,r),authorityId:e.id,signature:await wn(n,r.signing,"access-policy")};return await Wd(i),i}async function Wd(t){let e=Wh.parse(t);await fx(e.policy),await TH(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await Ne(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 oo(e.policy,e.signature,o.signing,"access-policy"),e}async function hx(t,e,r,o,n,i){let s=await Wd(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&R(p.executor)===R(o)&&Date.parse(p.expiresAt)>Date.now());if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let u=await Cu(t,px(a).map(p=>({id:p.id,publicKey:p.encryption})),await Kd(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 wn(l,n.signing,"resource")};return await qo(d),d}async function EO(t,e,r){let o=await qo(t);if(!o.policy.readers.some(n=>R(n)===R(e)))throw new Error("This identity cannot reveal the content.");return Ni(o.sealed,r,e.id,await Kd(o.policy,o.materialRevision))}var Npe=g.object({id:k,policyDigest:mr,materialRevision:g.number().int().positive(),authorizationDigest:mr.optional()}).strict();async function kO(t,e){return e.id===t.policy.id&&e.policyDigest===await Ne(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||bO(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var gx=g.object({format:g.literal(2),id:k,origin:Zd,ownerId:k,approval:g.object({id:k,index:g.number().int().min(0).max(7)}).strict().optional(),actor:hr,environmentId:k,executor:hr,environmentDigest:mr,operation:dx,functionDigest:mr.nullable(),operationDigest:mr,sources:g.array(Npe).max(100),resultRecipients:g.array(hr).min(1).max(100),createdAt:Be,expiresAt:Be}).strict(),yx=g.object({intent:gx,signature:Dn,sealed:Ho}).strict();async function Du(t,e){return R({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await Ne(t)})}async function OH(t,e,r){if(gx.parse(t),await Ne(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Cu(lt(R(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Du(t,"input"))};return yx.parse({...o,signature:await wn(o,r.signing,"run")})}async function Dpe(t,e=Date.now()){let r=yx.parse(t),{signature:o,...n}=r;await oo(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Ua(lt(await Du(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function NH(t,e,r){let o=await Dpe(t);if(R(o.intent.executor)!==R(e))throw new Error("This operation belongs to another executor.");let n=await Ni(o.sealed,r.encryption,e.id,await Du(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(R(s)!==i||await Ne(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function zu(t,e,r={}){let o=await qo(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await kO(o,i))throw new Error("The input changed after this execution was authorized.");if(R(e.actor)===R(e.executor)&&n.readers.some(c=>R(c)===R(e.actor)))return o;if(!n.grants.filter(c=>R(c.actor)===R(e.actor)&&R(c.executor)===R(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>e.operation===pe.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==pe.command&&e.operation!==pe.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function Fa(t,e,r,o={}){return await zu(t,e,o),Ni(t.sealed,r.encryption,e.executor.id,await Kd(t.policy,t.materialRevision))}var zpe=g.object({email:g.boolean(),environments:g.boolean(),objects:g.boolean(),payments:g.boolean()}),vx=g.object({principal:Hd.nullable(),credentialId:k.nullable(),wrappedKey:ox.nullable(),requestId:k.nullable(),server:g.object({name:le}),features:zpe,principals:g.array(Hd)}),_6e=g.object({email:g.email().max(254),returnTo:g.string().max(2048).optional(),locale:iH.default("ja"),principalId:k.optional()}).strict(),S6e=g.object({intent:g.enum(["register","authenticate"]),name:le.optional(),principalId:k.optional(),returnTo:g.string().max(2048).optional()}).strict(),x6e=g.object({challengeId:k,credential:g.json(),publicKey:Nr.optional(),existingPublicKey:Nr.optional(),wrappedKey:ox.optional()}).strict();var jpe=g.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/[\w+=,.@/-]{1,200}$/),zH=g.object({format:g.literal(3),id:k,origin:Zd,ownerId:k,name:le,executor:hr,operatorId:k,driver:g.enum(["attached","managed"]),capabilities:g.array(dx).min(1).max(6),isolation:g.enum(["process","container"]),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:jpe.optional(),revision:g.number().int().positive()}).strict(),IO=g.object({manifest:zH,signature:Dn}).strict();async function $O(t,e){let r=zH.parse(t),o={manifest:r,signature:await wn(r,e.signing,"environment")};return await Jd(o),o}async function Jd(t){let e=IO.parse(t),{manifest:r}=e;if(await La(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(pe.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(pe.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await oo(r,e.signature,r.executor.signing,"environment"),e}async function wx(t,e){let{manifest:r}=await Jd(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await Ne(r)||R(e.executor)!==R(r.executor)||!r.capabilities.includes(e.operation))throw new Error("This environment does not authorize the requested execution.")}var Mpe=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),jH=g.object({ok:g.boolean(),result:ro.nullable(),error:g.object({code:g.string().max(100),message:g.string().max(1e3)}).nullable()}).strict(),Gh=g.object({id:k,intentDigest:mr,executorId:k,state:g.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:Be,sealed:Ho,signature:Dn}).strict(),Jh=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Gd(t,e,r,o){let n=jH.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=lt(R(n));if(i.byteLength>14e5)throw new Jh;let s=await Cu(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Du(t,"result")),a={id:t.id,intentDigest:await Ne(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Gh.parse({...a,signature:await wn(a,o.signing,"receipt")})}async function Upe(t,e){let r=Gh.parse(t),{signature:o,...n}=r;if(await oo(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await Ne(e)||r.executorId!==e.executor.id||r.sealed.aad!==Ua(lt(await Du(e,"result")))||R(r.sealed.recipients.map(i=>i.header.kid).sort())!==R(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function MH(t,e,r,o){await Upe(t,e);let n=await Ni(t.sealed,o.encryption,r,await Du(e,"result")),i=jH.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 Lpe=g.enum(["http","command","function","connect","refresh","revoke"]),zn=g.object({id:k,ownerId:k,actorId:k,environmentId:k,kind:Lpe,state:Mpe,intent:gx,requestSignature:Dn,receipt:Gh.nullable(),error:g.string().nullable(),createdAt:Be,startedAt:Be.nullable(),finishedAt:Be.nullable()}).strict(),DH=g.object({name:le,approval:Wh}).strict(),Xd=g.discriminatedUnion("kind",[g.object({kind:g.literal("http"),request:Pu,save:g.record(g.string(),DH).default({})}).strict(),g.object({kind:g.literal("command"),...sx.shape}).strict(),g.object({kind:g.literal("function"),definition:Hh,arguments:g.record(g.string(),g.string()).default({}),outputs:g.record(g.string(),DH).default({})}).strict(),g.object({kind:g.enum(["connect","refresh","revoke"]),input:ro}).strict()]);var Va=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Bs=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=g.object({error:g.object({code:g.string(),message:g.string()})}).parse(await n.json())}catch{throw new Va("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new Va(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await(await this.response(e,r)).json();return o?o.parse(n):n}async session(){return this.json("/api/session",{},vx)}};import{chmod as Fpe,lstat as Vpe,mkdir as Bpe,open as AO,readFile as LH,rename as Hpe,rm as qpe}from"node:fs/promises";import{dirname as Zpe,join as TO,resolve as Kpe}from"node:path";import{homedir as Wpe}from"node:os";import{randomUUID as Jpe}from"node:crypto";var PO=g.object({origin:g.url(),principalId:g.uuid(),token:g.string().min(20),keys:Zh.nullable(),binding:hr.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),FH=g.object({current:g.uuid(),identities:g.array(PO).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Hs(){return TO(process.env.XDG_CONFIG_HOME||TO(Wpe(),".config"),"foundation","identity.json")}function Ba(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 bx(t){let e;try{let n=Hs(),i=await Vpe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await Fpe(n,384);let s=FH.parse(JSON.parse(await LH(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=Ba(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Ba(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return PO.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==Ba(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Xh(t){let e=Hs(),r;try{r=FH.parse(JSON.parse(await LH(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=PO.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Yd(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
129
129
  `,!!r)}async function UH(t){if(process.platform==="win32")return;let e=await AO(t,"r");try{await e.sync()}finally{await e.close()}}async function Yd(t,e,r){let o=Kpe(t),n=Zpe(o);if(await Bpe(n,{recursive:!0,mode:448}),!r){let s=await AO(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await UH(n);return}let i=TO(n,".foundation-"+Jpe());try{let s=await AO(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await Hpe(i,o),await UH(n)}finally{await qpe(i,{force:!0})}}import{spawn as Qpe}from"node:child_process";import{chmod as eme,mkdtemp as tme,rm as rme,writeFile as nme}from"node:fs/promises";import{tmpdir as ome}from"node:os";import{join as ZH}from"node:path";import{StringDecoder as ime}from"node:string_decoder";import{spawn as VH}from"node:child_process";import{mkdir as BH,mkdtemp as Gpe,rm as Xpe,writeFile as HH}from"node:fs/promises";import{tmpdir as Ype}from"node:os";import{join as Yh}from"node:path";import{StringDecoder as qH}from"node:string_decoder";function Qd(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}}var Qh=class{constructor(e){this.options=e;if(e.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(e.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(e,r){r.throwIfAborted();let o=await Gpe(Yh(Ype(),"foundation-job-")),n=Yh(o,"files"),i="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},c=!1;try{await BH(n,{mode:448});let u={...e.environment};for(let[d,p]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(d))throw new Error("Use valid file variable names.");await HH(Yh(n,d),Buffer.from(p,"base64"),{mode:384,flag:"wx"}),u[d]=s?"/run/foundation/"+d:Yh(n,d)}let l=e.command;if(s){if(Object.entries(u).some(([f,m])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(f)||m.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let d=Object.entries(u).filter(([,f])=>/[\r\n]/.test(f)),p=Yh(o,"environment");await HH(p,Object.entries(u).filter(([,f])=>!/[\r\n]/.test(f)).map(([f,m])=>f+"="+m).join(`
130
- `),{mode:384,flag:"wx"}),this.options.workspace&&await BH(this.options.workspace,{recursive:!0,mode:448}),l=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",p,...d.flatMap(([f,m])=>["--env",f+"="+m]),...this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(d=>{let p=VH(l[0],l.slice(1),{env:Qd(s?{}:u),cwd:s?this.options.cwd:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),f={stdout:new qH("utf8"),stderr:new qH("utf8")},m=0,h=!1,y=(x,$)=>{let O=Math.max(0,1e6-m);$.length>O&&(a.truncated=!0);let H=$.subarray(0,O);m+=H.length,a[x]+=f[x].write(H)};p.stdout.on("data",x=>y("stdout",x)),p.stderr.on("data",x=>y("stderr",x)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let w=()=>{c=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},b=setTimeout(()=>{a.timedOut=!0,w()},e.timeoutSeconds*1e3);b.unref();let _=()=>{h||(h=!0,clearTimeout(b),r.removeEventListener("abort",w),a.stdout+=f.stdout.end(),a.stderr+=f.stderr.end(),d())};r.addEventListener("abort",w,{once:!0}),r.aborted&&w(),p.once("error",()=>{a.exitCode=127,a.stderr="The command could not be started.",_()}),p.once("close",(x,$)=>{a.exitCode=x,a.signal=$,_()})}),a}finally{s&&c&&await new Promise(u=>{let l=VH("docker",["rm","-f",i],{env:Qd(),stdio:"ignore"});l.once("close",()=>u()),l.once("error",()=>u()),setTimeout(()=>{l.kill("SIGKILL"),u()},1e4).unref()}),await Xpe(o,{recursive:!0,force:!0})}}};function sme(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 _x=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 ime("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 KH(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await tme(ZH(ome(),"foundation-"));await eme(r,448);try{let o=Qd(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=ZH(r,i);await nme(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=Qpe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=sme(n),u=new _x(c,m=>process.stdout.write(m)),l=new _x(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,h)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(m??(h==="SIGINT"?130:h==="SIGTERM"?143:1))})})}finally{await rme(r,{recursive:!0,force:!0})}}import{dirname as EAe,join as T4}from"node:path";var Sx=g.record(g.string().max(100),g.string().max(16384)),Ha=g.object({format:g.literal(1),methodId:g.string().min(1),generation:k,clientId:g.string().max(1e3),clientSecret:g.string().max(16384).optional(),fields:Sx}).strict();function ju(t){return t.kind==="oauth"&&t.config.adapter!=="openrouter"}var ame=g.object({accessToken:g.string().min(1).max(16384),refreshToken:g.string().min(1).max(16384).optional(),expiresAt:g.number().nullable(),refreshExpiresAt:g.number().optional(),scopes:g.array(g.string()),requestedScopes:g.array(g.string()).optional(),account:g.string(),accountName:g.string(),accountVerified:g.boolean().optional(),scopesStatus:g.enum(["unknown","requested","reported"]).optional(),extra:Sx,facts:Au}).strict(),qs=g.object({format:g.literal(1),methodId:g.string().min(1),method:Tu,generation:k,appId:k.nullable(),appGeneration:k.nullable(),state:g.literal("reconnect").optional(),oauth:ame.optional(),fields:Sx.optional(),role:g.object({arn:g.string().regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),externalId:g.string().min(16).max(1e3),region:g.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/)}).strict().optional()}).strict().superRefine((t,e)=>{(t.method.kind==="oauth"&&(!t.oauth||ju(t.method)&&(!t.appId||!t.appGeneration))||t.method.kind==="token"&&!t.fields||t.method.kind==="role"&&!t.role)&&e.addIssue({code:"custom",message:"Supply the material required by this connection method."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."})}),oFe=g.object({methodId:g.string().min(1).max(200),clientId:g.string().max(1e3),generation:k}).strict(),cme=g.object({methodId:g.string().min(1).max(200),methodKind:lO,generation:k,authorizationDigest:mr,appId:k.nullable(),accountId:g.string().max(2e3).nullable(),accountVerified:g.boolean(),scopes:g.array(g.string().max(1e3)).max(200),scopesStatus:g.enum(["unknown","requested","reported"]),outputs:g.array(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:g.enum(["ready","reconnect"])}).strict();async function Mu(t){let e=t.method.kind==="role"?["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION"]:Object.keys(t.method.config.outputs),r=await Ne({generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:t.oauth?.account??t.role?.arn??null,accountVerified:t.oauth?.accountVerified??!1,scopes:[...t.oauth?.scopes??[]].sort(),role:t.role??null,...t.state?{state:t.state}:{}});return cme.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:r,appId:t.appId,accountId:t.role?.arn??(t.oauth?.accountVerified?t.oauth.account:null),accountVerified:!!(t.role||t.oauth?.accountVerified),scopes:t.oauth?.scopes??[],scopesStatus:t.oauth?.scopesStatus??"unknown",outputs:e,state:t.state??"ready"})}var WH=g.object({methodName:le,account:g.string().max(2e3)}).strict();function xx(t){return{methodName:t.method.name,account:t.oauth?.accountName??t.role?.arn??t.method.name}}var ume=g.object({action:g.literal("start"),flowId:k,name:le,methodId:g.string().min(1),method:Tu,appId:k.nullable(),fields:Sx.default({}),scopes:g.array(g.string().max(1e3)).max(200).default([]),redirectUri:g.url().optional(),role:qs.shape.role}).strict(),Ex=g.discriminatedUnion("action",[ume,g.object({action:g.literal("exchange"),flowId:k,parameters:g.string().max(16384)}).strict(),g.object({action:g.literal("commit"),flowId:k,authorizationDigest:mr,approval:Wh}).strict(),g.object({action:g.literal("refresh"),id:k}).strict(),g.object({action:g.literal("revoke"),id:k}).strict()]);var JH=Di.extend({name:le}),GH=g.object({id:k,index:g.number().int().min(0).max(7),input:SH.extend({ownerId:k})}).strict(),fFe=g.object({bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Di,token:g.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),XH=g.object({id:k,executorId:k,ownerId:k,name:le,origin:g.url(),bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),pFe=Di.extend({previousSignature:Dn.optional()}).strict(),mFe=g.object({name:le,content:io,labels:WH.optional(),version:g.number().int().positive().optional()}).strict(),YH=g.object({content:io,version:g.number().int().positive()}).strict(),QH=g.object({id:k,reason:g.enum(["grantExpired"])}).strict(),hFe=g.record(k,g.object({version:g.number().int().positive(),content:io}).strict()),gFe=g.object({id:k,name:le,version:g.number().int().positive(),content:io,policy:zi}).strict(),eq=g.object({registration:IO,stoppedAt:g.iso.datetime().nullable(),heartbeatAt:g.iso.datetime().nullable()}).strict(),tq=g.object({lease:k,request:yx,sources:g.array(io).max(100)}).strict().nullable(),lme=g.object({lease:k}).strict(),yFe=lme.extend({receipt:Gh}).strict(),eg=g.object({id:k,resource_id:k,executor_id:k,expected_revision:g.number().int().positive(),state:g.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:g.string().regex(/^\d+$/),result:io.nullable()}),vFe=g.object({id:k,resourceId:k,expectedRevision:g.number().int().positive()}).strict(),dme=g.object({fence:g.string().regex(/^\d+$/)}).strict(),wFe=dme.extend({content:io}).strict(),bFe=g.object({id:k,runId:k,stateDigest:mr,expiresAt:Be}).strict(),kx=g.object({id:k,runId:k,context:g.string(),sealed:Ho.nullable(),expiresAt:Be,receivedAt:Be.nullable()}).strict(),rq=(t,e)=>"oauth-callback:"+t+":"+e;var Ks=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"}},fme=class extends Ks{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"}},pme=class extends Ks{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},mme=class extends Ks{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"}},hme=class extends Ks{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"}},gme=class extends Ks{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},yme=class extends Ks{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"}},vme=class extends Ks{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"}},$x=class extends Ks{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},RO=class extends $x{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"}},wme=class extends $x{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"}},bme=class extends $x{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"}},nq=class extends $x{constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},_me=class extends Ks{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"}},Sme=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},xme=class extends Sme{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"}},Eme=["","+",".","/",";","?","&","#"],lq={"":{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}},kme=new TextEncoder,oq="0123456789ABCDEF",iq=t=>Za(Dr(48,57),Dr(65,70),Dr(97,102))(t.charCodeAt(0)),ng=(t,e)=>t[e]==="%"&&e+2<t.length&&iq(t[e+1])&&iq(t[e+2]);function CO(t,e){let r=t[e];return r==null?0:Za(dq,fq,Uu("_"))(r)?1:ng(t,e)?3:0}function Ime(t,e){if(ng(t,e))return 3;let{char:r,size:o}=og(t,e);return Ame(r)?o:0}function og(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var zO=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&ng(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=og(e,o);r+=Za(pq,s=>t&&$me(s))(n)?n:mq(n),o+=i}return r};function ef(t){let e="";for(let r=0;r<t.length;){if(ng(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=og(t,r);e+=pq(o)?o:mq(o),r+=n}return e}function tg(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(ng(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=og(t,n);r+=i,n+=s}return r}var dq=t=>Za(Dr(65,90),Dr(97,122))(t.charCodeAt(0)),fq=t=>Dr(48,57)(t.charCodeAt(0)),pq=t=>Za(dq,fq,e=>"-._~".includes(e))(t),$me=t=>":/?#[]@!$&'()*+,;=".includes(t),Ame=t=>Tme(t.codePointAt(0)),Tme=t=>t!=null&&Za(Uu(33),Dr(35,36),Uu(38),Dr(40,59),Uu(61),Dr(63,91),Uu(93),Uu(95),Dr(97,122),Uu(126),Pme,Rme)(t);function Pme(t){if(t<65536)return Za(Dr(160,55295),Dr(63744,64975),Dr(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var Rme=t=>Za(Dr(57344,63743),Dr(983040,1048573),Dr(1048576,1114109))(t),mq=t=>Array.from(kme.encode(t)).map(e=>`%${oq[e>>4]}${oq[e&15]}`).join(""),Dr=(t,e)=>r=>t<=r&&r<=e,Uu=t=>e=>t===e,Za=(...t)=>e=>t.some(r=>r(e));function hq(t,e,r){return t.map(o=>o.kind==="literal"?o.text:Cme(o.vars,o.operator,e,r)).join("")}function Cme(t,e,r,o){let n=lq[e],i=t.flatMap(s=>Ome(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function Ome(t,e,r,o){if(e==null)return[];if(Fme(e)){let n=jme(e,r.allowReserved);return n.length<1?[]:sq(t,"list",o)?Dme(t,n,r):[]}if(Lme(e)){let n=Mme(e,r.allowReserved);return n.length<1?[]:sq(t,"associative",o)?zme(t,n,r):[]}return Nme(t,e,r)}function Nme(t,e,r){let o=String(e),n=t.prefix==null?o:tg(o,t.prefix),i=zO(r.allowReserved)(n);return r.named?[rg(ef(t.name),i,r)]:[i]}function Dme(t,e,r){let o=ef(t.name);if(t.explode)return r.named?e.map(i=>rg(o,i,r)):[...e];let n=e.join(",");return r.named?[rg(o,n,r)]:[n]}function zme(t,e,r){if(t.explode)return e.map(([n,i])=>rg(n,i,r));let o=e.flat(1).join(",");return r.named?[rg(ef(t.name),o,r)]:[o]}var rg=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,jme=(t,e)=>t.filter(r=>r!=null).map(String).map(zO(e)),Mme=(t,e)=>Object.entries(t).map(([r,o])=>[r,Ume(o)]).filter(([,r])=>r!=null).map(r=>r.map(zO(e)));function Ume(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 Lme=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Fme=t=>Array.isArray(t);function sq(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new xme(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function Vme(t,e,r){return OO(t,e,r,0,0,{})}function OO(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=hhe(i);return hq(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?OO(t,e,r,o+1,n+s.text.length,i):null;for(let a of Bme(t,e,o,n)){let c=e.slice(n,a);for(let u of qme(s.vars,s.operator,c)){let l=jO(i,u);if(l==null)continue;let d=OO(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*Bme(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*Hme(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*Hme(t,e){for(let r=t;r>=e;r--)yield r}function*qme(t,e,r){if(r===""){yield*Zme(t,e);return}let o=lq[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?the(t,o,n):Kme(t,o,n)}var Zme=(t,e)=>(e===""||e==="+")&&t.length===1?[qa(t[0],"")]:[{}],Kme=(t,e,r)=>NO(t,e,MO(r,e.sep),0,0);function*NO(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of Wme(i,e,r,n))for(let a of NO(t,e,r,o+1,s.index)){let c=jO(s.bindings,a);c!=null&&(yield c)}yield*NO(t,e,r,o+1,n)}function*Wme(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 Jme(t,e,s))yield{bindings:a,index:o+i}}}function*Jme(t,e,r){let o=gq(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*Gme(t,e,r)),yield*o}function*Gme(t,e,r){let o=yq(r,e.allowReserved);if(o==null)return;let n=Xme(r,e);n!=null&&(yield qa(t,n)),yield qa(t,o)}var Xme=(t,e)=>Yme(t.join(e.sep),e);function Yme(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=Qme(t,i,e.sep),a=Zs(t.slice(o,n),e.allowReserved),c=Zs(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 Qme(t,e,r){for(let o=e;o<t.length;o++)if(ehe(t,o,r))return o;return t.length}var ehe=(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*gq(t,e,r){let o=Zs(r,e.allowReserved);if(o==null)return;let n=qa(t,o);if(t.prefix!=null){yield n;return}let i=MO(r,",");if(i.length<2){yield n;return}let s=yq(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?lhe(i,e.allowReserved):null;a!=null&&(yield qa(t,a)),yield qa(t,s),yield n}var the=(t,e,r)=>DO(t,e,MO(r,e.sep).map(uhe),0,0);function*DO(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of rhe(i,e,r,n,t))for(let a of DO(t,e,r,o+1,s.index)){let c=jO(s.bindings,a);c!=null&&(yield c)}yield*DO(t,e,r,o+1,n)}function*rhe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*ohe(t,e,r,o,n);return}yield*nhe(t,e,r,o)}}function*nhe(t,e,r,o){let n=r[o];if(n.name===ef(t.name))for(let i of gq(t,e,n.value))yield{bindings:i,index:o+1}}function*ohe(t,e,r,o,n){yield*ihe(t,e,r,o),yield*ahe(t,e,r,o,n)}function*ihe(t,e,r,o){let n=[...she(ef(t.name),e,r,o)];n.length>0&&(yield{bindings:qa(t,n),index:o+n.length})}function*she(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Zs(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*ahe(t,e,r,o,n){let i=[...che(e,r,o,new Set(n.map(s=>ef(s.name))))];i.length>0&&(yield{bindings:qa(t,Object.fromEntries(i)),index:o+i.length})}function*che(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=Zs(i.name,t.allowReserved),a=Zs(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function uhe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function lhe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Zs(t[o],e),i=Zs(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function yq(t,e){let r=[];for(let o of t){let n=Zs(o,e);if(n==null)return null;r.push(n)}return r}function Zs(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var qa=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function jO(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=dhe(i,n);if(s==null)return null;r[o]=s}return r}var dhe=(t,e)=>Ix(t)||Ix(e)?fhe(t,e):phe(t.value,e.value)?t:null;function fhe(t,e){let r=aq(t.value),o=aq(e.value);if(r==null||o==null)return null;let n=Ix(t),i=Ix(e);if(!n&&!i)return null;if(n&&!i)return tg(o,t.prefix)===r?e:null;if(!n&&i)return tg(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?tg(o,s)===r?e:null:tg(r,a)===o?t:null}var Ix=t=>t.prefix!=null,aq=t=>typeof t=="string"?t:null;function phe(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):cq(t)?cq(e)&&mhe(Object.entries(t),Object.entries(e)):t===e}var mhe=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),cq=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hhe=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),MO=(t,e)=>e===""?[t]:t.split(e),ghe=["=",",","!","@","|"];function yhe(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new gme(e,r));let n=t[0];if(_he(n))return o(new yme(e,r+1,n));if(!uq(n)&&CO(t,0)<1)return o(new vme(e,r+1,n));let i=uq(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:vhe(t,e,r+1,s)}}function vhe(t,e,r,o){if(o>=t.length)throw new RO(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new nq(e,r+i):new RO(e,r+i);let s=i,a=whe(t,i);if(a===s)throw new RO(e,r+i);let c=t.slice(s,a);i=a;let u=bhe(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new _me(e,r+i,t[i]):new wme(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 nq(e,r+i-1)}return n}function whe(t,e){let r=e,o=!0;for(;r<t.length;){let n=CO(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||CO(t,r+1)<1)break;r++,o=!0}return r}function bhe(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&&She(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new bme(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function uq(t){return Eme.includes(t)&&t!==""}function _he(t){return ghe.includes(t)}function She(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function xhe(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 fme(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new mme(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let p=t.slice(i+1,l);try{o.push(yhe(p,t,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new pme(t,i)),n(s),i++;continue}let a=Ime(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=og(t,i);r(new hme(t,i,c)),n(c),i+=u}return o}var Ax=class vq{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=Ahe(r),this.#e=Ehe(xhe(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new vq(e,r)}get tokens(){return this.#e}expand=e=>hq(this.#e,e,this.#t);match=e=>Vme(this.#e,e,this.#t);toString=()=>this.uriTemplate},Ehe=t=>Object.freeze(t.map(khe)),khe=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(Ihe))}),Ihe=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),$he=()=>{},Ahe=({strict:t,report:e})=>(e??=$he,t??=!0,e=t?The(e):e,{strict:t,report:e}),The=t=>e=>{throw t(e),e};function Tx(t,e){let r={};if(Object.keys(e).some(a=>!t.parameters.some(c=>c.name===a)))throw new Error("Use the parameters this function declares.");for(let a of t.parameters){let c=e[a.name]??a.default??"";if(a.required&&!c)throw new Error("Complete the required function parameters.");if(c.length>8192)throw new Error("The function argument is too long.");r[a.name]=c}let o=a=>typeof a=="string"?a.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(c,u)=>{if(!Object.hasOwn(r,u))throw new Error("Declare every function parameter.");return r[u]}):Array.isArray(a)?a.map(o):a&&typeof a=="object"?Object.fromEntries(Object.entries(a).map(([c,u])=>[c,o(u)])):a,n=new Ax(t.request.url).expand(r),i=Pu.parse({...o(t.request),url:n,bindings:t.request.bindings}),s=new URL(t.request.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(n).origin!==s.origin)throw new Error("The function must have a fixed destination host.");return i}var Px=class extends Error{constructor(r,o){super(o);this.code=r}code},UO=class extends Error{constructor(r){super("The execution request is saved locally. Check execution "+r+" before starting another operation.");this.id=r}id},Rx=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;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||R(r)!==R(e))throw new Px("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+k.parse(e)+"/binding",{},Di);return await vO(r),{...r,fingerprint:await Ou(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new Px("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+k.parse(e)+"/registration",{},eq);if(await Jd(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/"+k.parse(e)+"/bound-recipients",{},Ma(JH));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await vO(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/resources/"+k.parse(e)+"/custody",{},YH);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await qo(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=SO(o);await this.trusted(n);let i=await this.trust.checkpoint(r),s=i&&zi.safeParse(i.policy).success?i:null;if(s){if(o.policy.revision<s.policy.revision||o.materialRevision<s.materialRevision||o.policy.revision===s.policy.revision&&R(o.policy)!==R(s.policy)||o.materialRevision===s.materialRevision&&await Ne(o)!==s.digest)throw new Error("The encrypted content is older than this device has already observed.");if(o.policy.revision>s.policy.revision&&!PH(s.policy,o))throw new Error("An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return EO((await this.read(e)).content,this.binding,this.keys.encryption)}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=>R(c)===R(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=>c.actor.id!==this.binding.id&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...wO(r)],origins:[],functionDigests:[],callerProgram:r!==Me.clientCredential,expiresAt:s});return zi.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&R(o)===R({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await xO(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:s,...i?{version:i.version}:{}}},no);return await this.trust.rememberContent(s),a}async pass(e,r,o,n){let i=await xO(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}},g.union([no,ja]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Ma(QH))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},no),a=await EO(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}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===Me.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Ma(no));s=d.items.find(p=>p.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,Me.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await mx(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=await this.environment(r),s=Xd.parse(o),a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=s.kind==="http"?s.request:s.kind==="function"?Tx(s.definition,s.arguments):null;if(s.kind==="http"||s.kind==="function"){let m=s.kind==="function"?s.definition.save:n.save??{};if(s.kind==="function"&&Object.keys(m).length&&s.definition.outputOwnerId!==e)throw new Error("Run this function for its approved output owner.");let h=Object.fromEntries(await Promise.all(Object.entries(m).map(async([y,w])=>[y,await this.output(e,w,a,i,c)])));s.kind==="http"?s.save=h:s.outputs=h}let l=s.kind==="command"?s.inputs.map(m=>m.source.id):u?u.bindings.flatMap(m=>m.parts.flatMap(h=>typeof h=="string"?[]:[h.id])):[],d=await this.sourceContents([...l,...n.sourceIds??[]]),p={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:i.manifest.executor,environmentDigest:await Ne(i.manifest),operation:pe[s.kind],operationDigest:await Ne(s),...n.approval?{approval:n.approval}:{},functionDigest:s.kind==="function"?await Ne(s.definition):null,sources:await Promise.all(d.map(async m=>({id:m.policy.id,materialRevision:m.materialRevision,policyDigest:await Ne(m.policy),...m.policy.contentType===Me.tokenSet&&typeof m.metadata.authorizationDigest=="string"?{authorizationDigest:m.metadata.authorizationDigest}:{}}))),resultRecipients:[this.binding],createdAt:new Date().toISOString(),expiresAt:c};await wx(i,p);let f=m=>m.policy.contentType===Me.clientCredential;for(let m of d)await zu(m,f(m)&&p.operation!==pe.connect&&p.operation!==pe.revoke?{...p,operation:pe.refresh}:p,f(m)?{}:{destination:u?.url});return OH(p,s,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/executions",{method:"POST",body:e},zn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new UO(e.intent.id)}}async resume(e){let r=await this.trust.run(k.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(R(r.intent.actor)!==R(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");return this.submitPrepared(r)}async result(e){if(R(e.intent.actor)!==R(this.binding)||e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another requester.");let r=await yO(e.requestSignature,this.binding.signing,"run");if(R(r.intent)!==R(e.intent))throw new Error("The result belongs to a different signed request.");return await this.trusted(e.intent.executor),e.receipt?MH(e.receipt,e.intent,this.binding.id,this.keys):null}};import{lstat as Phe,mkdir as Rhe,readFile as Che,readdir as Ohe}from"node:fs/promises";import{join as wq}from"node:path";var bq=g.string().regex(/^(run|process|oauth|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Lu=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return R({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:bq.parse(e)})}async read(e){let r=this.context(e),o=wq(this.directory,e+".json");try{let n=await Phe(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=g.string().max(32e6).parse(JSON.parse(await Che(o,"utf8"))),s=await Mh(i,await to(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(Ru(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await oo({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 write(e,r){let o=this.context(e),n={context:o,value:r},i=await wn(n,this.privateKeys.signing,"journal"),s=lt(R({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new Bd(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await to(this.binding.encryption,"ECDH-ES+A256KW"));await Rhe(this.directory,{recursive:!0,mode:448}),await Yd(wq(this.directory,e+".json"),R(a),!0)}async keys(e){let r;try{r=await Ohe(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=>bq.parse(o.name.slice(0,-5)))}};var Cx=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await La(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await Ne(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&R(r)!==R(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var Ct=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function U(t,e,r,o){throw new Ct(t,e,r,o)}var Ox=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 Ct(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},tq)}renew(e,r){return this.api.json("/api/executions/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}dispatch(e,r){return this.api.json("/api/executions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/executions/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},zn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},g.object({id:k}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},kx),capture:(r,o,n)=>this.capture(r,o,n),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},eg),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},eg),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},io),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}},eg),state:r=>e.json("/api/connections/"+r+"/operation",{},eg.nullable())}}};var Sne=St(Vq(),1);import{randomBytes as _ne,randomUUID as S$}from"node:crypto";function sg(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 Zo(t,e){for(let r of sg(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function WO(t,e,r){let o=sg(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function nf(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 ag(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}import{createHash as tye}from"node:crypto";var JO;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(JO="oauth4webapi/v3.8.8");function fg(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 Mi="ERR_INVALID_ARG_VALUE",Ui="ERR_INVALID_ARG_TYPE";function Ht(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var oN=Symbol(),oge=Symbol(),ige=Symbol(),iN=Symbol();var cg=Symbol();var sge=new TextEncoder,age=new TextDecoder;function GO(t){return typeof t=="string"?sge.encode(t):age.decode(t)}var XO;Uint8Array.prototype.toBase64?XO=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):XO=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 YO;Uint8Array.fromBase64?YO=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Ht("The input to be decoded is not correctly encoded.",Mi,e)}}:YO=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 Ht("The input to be decoded is not correctly encoded.",Mi,e)}};function QO(t){return typeof t=="string"?YO(t):XO(t)}var of=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Dge,Error.captureStackTrace?.(this,this.constructor)}},ug=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 he(t,e,r){return new ug(t,{code:e,cause:r})}function cge(t){return t.toLowerCase().replace(/^application\//,"")}function lg(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function sN(t){fg(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(JO&&!e.has("user-agent")&&e.set("user-agent",JO),e.has("authorization"))throw Ht('"options.headers" must not include the "authorization" header name',Mi);return e}function uge(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Ht('"options.signal" must return or be an instance of AbortSignal',Ui);return e}}function Bx(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Ht(`${r} must be a number`,Ui,n);if(t>0)return;if(e){if(t!==0)throw Ht(`${r} must be a non-negative number`,Mi,n);return}throw Ht(`${r} must be a positive number`,Mi,n)}catch(i){throw o?he(i.message,o,n):i}}function yr(t,e,r,o){try{if(typeof t!="string")throw Ht(`${e} must be a string`,Ui,o);if(t.length===0)throw Ht(`${e} must not be empty`,Mi,o)}catch(n){throw r?he(n.message,r,o):n}}function qq(t){dge(t,"application/json")}function lge(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 he(r,jge,t)}function dge(t,e){if(Xq(t)!==e)throw lge(t,e)}async function Zq(t){return yr(t,"codeVerifier"),QO(await crypto.subtle.digest("SHA-256",GO(t)))}function aN(t){let e=t?.[oge];return typeof e=="number"&&Number.isFinite(e)?e:0}function cN(t){let e=t?.[ige];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Kq(){return Math.floor(Date.now()/1e3)}function Wa(t){if(typeof t!="object"||t===null)throw Ht('"as" must be an object',Ui);yr(t.issuer,'"as.issuer"')}function Ja(t){if(typeof t!="object"||t===null)throw Ht('"client" must be an object',Ui);yr(t.client_id,'"client.client_id"')}function Bq(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 Wq(t){return yr(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function Jq(t){return yr(t,'"clientSecret"'),(e,r,o,n)=>{let i=Bq(r.client_id),s=Bq(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function Gq(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var fge=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function pge(t,e){if(e&&t.protocol!=="https:")throw he("only requests to HTTPS are allowed",Uge,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw he("only HTTP and HTTPS requests are allowed",Lge,t)}function Hq(t,e,r,o){let n;if(typeof t!="string"||!(n=fge(t)))throw he(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?Fge:Vge,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return pge(n,o),n}function uN(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Hq(t.mtls_endpoint_aliases[e],e,r,o):Hq(t[e],e,r,o)}var eN=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Nge,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)}},dg=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=zge,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)}},tN=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Oge,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Hx="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",mge="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",hge='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',gge="("+Hx+")\\s*=\\s*"+hge,yge="("+Hx+")\\s*=\\s*("+Hx+")",vge=new RegExp("^[,\\s]*("+Hx+")"),wge=new RegExp("^[,\\s]*"+gge+"[,\\s]*(.*)"),bge=new RegExp("^[,\\s]*"+yge+"[,\\s]*(.*)"),_ge=new RegExp("^("+mge+")(?:$|[,\\s])(.*)");function Sge(t){if(!fg(t,Response))throw Ht('"response" must be an instance of Response',Ui);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(vge),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(wge)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(bge)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(_ge)){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 xge(t){if(t.status>399&&t.status<500){Kx(t),qq(t);try{let e=await t.clone().json();if(lg(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function lN(t,e,r){if(t.status!==e){kge(t);let o;throw(o=await xge(t))?(await t.body?.cancel(),new eN("server responded with an error in the response body",{cause:o,response:t})):he(`"response" is not a conform ${r} response (unexpected HTTP status code)`,Mge,t)}}function Ege(t){if(!pN.has(t))throw Ht('"options.DPoP" is not a valid DPoPHandle',Mi)}function Xq(t){return t.headers.get("content-type")?.split(";")[0]}async function dN(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?.[iN]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:uge(o,s?.signal)})}async function fN(t,e,r,o,n,i){let s=uN(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[oN]!==!0);n.set("grant_type",o);let a=sN(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(Ege(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await dN(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Yq(t,e,r,o,n){Wa(t),Ja(e),yr(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),fN(t,e,r,"refresh_token",i,n)}var Qq=new WeakMap,eZ=new WeakMap;function tZ(t){if(!t.id_token)return;let e=Qq.get(t);if(!e)throw Ht('"ref" was already garbage collected or did not resolve from the proper sources',Mi);return e}async function Wx(t,e,r,o,n,i){if(Wa(t),Ja(e),!fg(r,Response))throw Ht('"response" must be an instance of Response',Ui);await lN(r,200,"Token Endpoint"),Kx(r);let s=await _Z(r);if(yr(s.access_token,'"response" body "access_token" property',Ge,{body:s}),yr(s.token_type,'"response" body "token_type" property',Ge,{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;Bx(a,!0,'"response" body "expires_in" property',Ge,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&yr(s.refresh_token,'"response" body "refresh_token" property',Ge,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw he('"response" body "scope" property must be a string',Ge,{body:s});if(s.id_token!==void 0){yr(s.id_token,'"response" body "id_token" property',Ge,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Bx(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await Age(t,e,s.id_token,a,n);Pge(e,c),Tge(c),eZ.set(r,u),Qq.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 of("unsupported `token_type` value",{cause:{body:s}});return s}function kge(t){let e;if(e=Sge(t))throw new tN("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function rZ(t,e,r,o){return Wx(t,e,r,void 0,o?.[cg],o?.recognizedTokenTypes)}function nZ(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw he('unexpected JWT "aud" (audience) claim value',sf,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw he('unexpected JWT "aud" (audience) claim value',sf,{expected:t,claims:e.claims,claim:"aud"});return e}function oZ(t,e){let r=t[Zge]?.(e)??t.issuer;if(e.claims.iss!==r)throw he('unexpected JWT "iss" (issuer) claim value',sf,{expected:r,claims:e.claims,claim:"iss"});return e}var pN=new WeakSet;function Ige(t){return pN.add(t),t}var mN=Symbol();async function iZ(t,e,r,o,n,i,s){if(Wa(t),Ja(e),!pN.has(o))throw Ht('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Mi);yr(n,'"redirectUri"');let a=Vu(o,"code");if(!a)throw he('no authorization code in "callbackParameters"',Ge);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==mN&&(yr(i,'"codeVerifier"'),c.set("code_verifier",i)),fN(t,e,r,"authorization_code",c,s)}var sZ={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 aZ(t,e){for(let r of t)if(e.claims[r]===void 0)throw he(`JWT "${r}" (${sZ[r]}) claim missing`,Ge,{claims:e.claims});return e}function $ge(t,e){if(typeof e.claims[t]!="string")throw he(`unexpected JWT "${t}" (${sZ[t]}) claim type`,Ge,{claims:e.claims});return e}function Age(t,e,r,o,n){return vZ(r,wZ.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),aN(e),cN(e),n).then(aZ.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(oZ.bind(void 0,t)).then(nZ.bind(void 0,e.client_id)).then($ge.bind(void 0,"sub"))}function cZ(t,e){if(e===Zx)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?Zx:(Bx(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function Tge(t){t.auth_time!==void 0&&Bx(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Ge,{claims:t})}function uZ(t,e,r){if(r===Zx)return;let o=Kq()+aN(t),n=cN(t);if(e.auth_time+r<o-n)throw he("too much time has elapsed since the last End-User authentication",nN,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function lZ(t,e){let r=e===qx?void 0:e;if(t.nonce!==r)throw he('unexpected ID Token "nonce" claim value',sf,{expected:r,claims:t,claim:"nonce"})}function Pge(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw he('ID Token "aud" (audience) claim includes additional untrusted audiences',sf,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw he('unexpected ID Token "azp" (authorized party) claim value',sf,{expected:t.client_id,claims:e,claim:"azp"})}}var qx=Symbol(),Zx=Symbol();async function dZ(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?Rge(t,e,r,o.expectedNonce,o.maxAge,o[cg],o.recognizedTokenTypes):Cge(t,e,r,o?.maxAge,o?.[cg],o?.recognizedTokenTypes)}async function Rge(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=qx;break;case qx:break;default:yr(o,'"expectedNonce" argument'),a.push("nonce")}n=cZ(e,n),n!==Zx&&a.push("auth_time");let c=await Wx(t,e,r,a,i,s);yr(c.id_token,'"response" body "id_token" property',Ge,{body:c});let u=tZ(c);return uZ(e,u,n),lZ(u,o),c}async function Cge(t,e,r,o,n,i){let s=await Wx(t,e,r,void 0,n,i),a=tZ(s);return a&&(uZ(e,a,cZ(e,o)),lZ(a,qx)),s}var Oge="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Nge="OAUTH_RESPONSE_BODY_ERROR",Dge="OAUTH_UNSUPPORTED_OPERATION",zge="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var rN="OAUTH_PARSE_ERROR",Ge="OAUTH_INVALID_RESPONSE";var jge="OAUTH_RESPONSE_IS_NOT_JSON",Mge="OAUTH_RESPONSE_IS_NOT_CONFORM",Uge="OAUTH_HTTP_REQUEST_FORBIDDEN",Lge="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",nN="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",sf="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var Fge="OAUTH_MISSING_SERVER_METADATA",Vge="OAUTH_INVALID_SERVER_METADATA";function Bge(t,e){if(typeof e.header.typ!="string"||cge(e.header.typ)!==t)throw he('unexpected JWT "typ" header parameter value',Ge,{header:e.header});return e}async function fZ(t,e,r,o,n){return Wa(t),Ja(e),fN(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function pZ(t,e,r,o){return Wx(t,e,r,void 0,o?.[cg],o?.recognizedTokenTypes)}async function mZ(t,e,r,o,n){Wa(t),Ja(e),yr(o,'"token"');let i=uN(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[oN]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=sN(n?.headers);return a.delete("accept"),dN(t,e,r,i,s,a,n)}async function hZ(t){if(!fg(t,Response))throw Ht('"response" must be an instance of Response',Ui);await lN(t,200,"Revocation Endpoint")}function Kx(t){if(t.bodyUsed)throw Ht('"response" body has been used already',Mi)}async function gZ(t,e,r,o,n){Wa(t),Ja(e),yr(o,'"token"');let i=uN(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[oN]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=sN(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),dN(t,e,r,i,s,a,n)}async function yZ(t,e,r,o){if(Wa(t),Ja(e),!fg(r,Response))throw Ht('"response" must be an instance of Response',Ui);await lN(r,200,"Introspection Endpoint");let n;if(Xq(r)==="application/token-introspection+jwt"){Kx(r);let{claims:i,jwt:s}=await vZ(await r.text(),wZ.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),aN(e),cN(e),o?.[cg]).then(Bge.bind(void 0,"token-introspection+jwt")).then(aZ.bind(void 0,["aud","iat","iss"])).then(oZ.bind(void 0,t)).then(nZ.bind(void 0,e.client_id));if(eZ.set(r,s),!lg(i.token_introspection))throw he('JWT "token_introspection" claim must be a JSON object',Ge,{claims:i});n=i.token_introspection}else Kx(r),n=await _Z(r);if(typeof n.active!="boolean")throw he('"response" body "active" property must be a boolean',Ge,{body:n});return n}async function vZ(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 of("JWE decryption is not configured",{cause:t});if(a!==3)throw he("Invalid JWT",Ge,t);let c;try{c=JSON.parse(GO(QO(i)))}catch(d){throw he("failed to parse JWT Header body as base64url encoded JSON",rN,d)}if(!lg(c))throw he("JWT Header must be a top level object",Ge,t);if(e(c),c.crit!==void 0)throw new of('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(GO(QO(s)))}catch(d){throw he("failed to parse JWT Payload body as base64url encoded JSON",rN,d)}if(!lg(u))throw he("JWT Payload must be a top level object",Ge,t);let l=Kq()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw he('unexpected JWT "exp" (expiration time) claim type',Ge,{claims:u});if(u.exp<=l-o)throw he('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',nN,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw he('unexpected JWT "iat" (issued at) claim type',Ge,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw he('unexpected JWT "iss" (issuer) claim type',Ge,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw he('unexpected JWT "nbf" (not before) claim type',Ge,{claims:u});if(u.nbf>l+o)throw he('unexpected JWT "nbf" (not before) claim value',nN,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw he('unexpected JWT "aud" (audience) claim type',Ge,{claims:u});return{header:c,claims:u,jwt:t}}function wZ(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw he('unexpected JWT "alg" header parameter',Ge,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw he('unexpected JWT "alg" header parameter',Ge,{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 he('unexpected JWT "alg" header parameter',Ge,{header:o,expected:r,reason:"default value"});return}throw he('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Vu(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw he(`"${e}" parameter must be provided only once`,Ge);return r}var Hge=Symbol(),qge=Symbol();function bZ(t,e,r,o){if(Wa(t),Ja(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Ht('"parameters" must be an instance of URLSearchParams, or URL',Ui);if(Vu(r,"response"))throw he('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Ge,{parameters:r});let n=Vu(r,"iss"),i=Vu(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw he('response parameter "iss" (issuer) missing',Ge,{parameters:r});if(n&&n!==t.issuer)throw he('unexpected "iss" (issuer) response parameter value',Ge,{expected:t.issuer,parameters:r});switch(o){case void 0:case qge:if(i!==void 0)throw he('unexpected "state" response parameter encountered',Ge,{expected:void 0,parameters:r});break;case Hge:break;default:if(yr(o,'"expectedState" argument'),i!==o)throw he(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Ge,{expected:o,parameters:r})}if(Vu(r,"error"))throw new dg("authorization response from the server is an error",{cause:r});let a=Vu(r,"id_token"),c=Vu(r,"token");if(a!==void 0||c!==void 0)throw new of("implicit and hybrid flows are not supported");return Ige(new URLSearchParams(r))}async function _Z(t,e=qq){let r;try{r=await t.json()}catch(o){throw e(t),he('failed to parse "response" body as JSON',rN,o)}if(!lg(r))throw he('"response" body must be a top level object',Ge,{body:r});return r}var Zge=Symbol();import{lookup as Wge}from"node:dns/promises";import{isIP as EZ}from"node:net";import{request as Jge}from"node:https";import{brotliDecompressSync as Gge,gunzipSync as Xge,inflateSync as Yge}from"node:zlib";var Gx=St(xZ(),1),Qge=Gx.default.IPv6.parseCIDR("2000::/3"),eye=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function kZ(t){if(!EZ(t)||t.includes("%"))return!1;let e=Gx.default.parse(t);return eye.has(e.range())&&(!(e instanceof Gx.default.IPv6)||e.match(Qge))}function af(t,e){let r;try{r=new URL(t)}catch{U(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)&&U(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||EZ(o)&&!kZ(o))&&U(400,"private_destination","Choose a public HTTPS destination."),r}var Xx=class{constructor(e){this.origin=e}origin;async send(e){let r=af(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&U(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))&&U(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await Wge(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!kZ(u.address)))&&U(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:(f,m,h)=>{m.all?h(null,[a]):h(null,a.address,a.family)}},p=Jge(r,d,f=>{let m=[],h=0;f.on("data",y=>{h+=y.length,h>n?f.destroy(new Ct(413,"body_limit","The response body is too large.")):m.push(y)}),f.on("error",l),f.on("end",()=>{try{let y=Buffer.concat(m),w=f.headers["content-encoding"];if(w&&w!=="identity"){let _=w==="gzip"?Xge:w==="deflate"?Yge:w==="br"?Gge:null;if(!_)throw new Ct(502,"invalid_response","The service returned an unsupported response.");y=_(y,{maxOutputLength:n})}let b={};for(let[_,x]of Object.entries(f.headers))x!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(_)&&(b[_]=Array.isArray(x)?x.join(", "):x);u({status:f.statusCode??502,headers:b,body:new Uint8Array(y)})}catch(y){l(y)}})});p.on("error",l),p.end(e.body)})}catch(s){if(s instanceof Ct)throw s;e.signal?.aborted&&U(409,"cancelled","The operation was cancelled."),U(502,"service_unavailable","The service could not be reached. Try again.")}}};function pg(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{U(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&U(502,"invalid_response","The service returned an invalid response."),e}var IZ=t=>tye("sha256").update(t).digest("hex");function cf(t,e){try{return af(new Ax(t).expand(e)).href}catch{U(400,"invalid_service_url","Check the service URL and its required fields.")}}var hN=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],gN=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&U(502,"invalid_response","The service returned an invalid expiry."),e},$Z=(t,e)=>{let r=new URL(t);return r.hostname.endsWith(".myshopify.com")&&(typeof e=="string"?r.pathname===e:e.test(r.pathname))},AZ=Object.assign(Object.create(null),{dpop:()=>U(502,"invalid_response","The service returned an unsupported token.")}),rye=Object.assign(Object.create(null),AZ,{"user access token":()=>{}}),Yx=class{constructor(e){this.transport=e}transport;async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&U(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(cf(e.authorizeUrl,r.fields)),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:e.adapter==="ebay"?r.fields.ruName:i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await Zq(n),c.code_challenge_method="S256"),e.adapter==="openrouter"&&(delete c.response_type,delete c.client_id,delete c.redirect_uri,c.callback_url=i,c.key_label="Foundation");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(cf(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,r.fields)).origin,token_endpoint:cf(e.tokenUrl,r.fields)};return e.issuer&&af(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?Gq():(e.clientSecret||U(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?Jq(e.clientSecret):Wq(e.clientSecret))}options(e="form"){return{[iN]:async(r,{body:o,headers:n,method:i,signal:s})=>{let a=await this.transport.send({url:r,method:i,headers:e==="json"?{...n,"content-type":"application/json"}:n,body:e==="json"?JSON.stringify(Object.fromEntries(o)):o.toString(),signal:s});return new Response([204,205,304].includes(a.status)?null:new Uint8Array(a.body),{status:a.status,headers:a.headers})}}}async json(e){return pg({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&Zo(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&U(409,"reconnect_required","Reconnect this service to renew access."),r===429&&U(503,"service_rate_limit","The service is busy. Try again later."),U(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&U(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,c.hostname.endsWith(".myshopify.com")&&c.pathname==="/admin/oauth/access_token"&&u.token_type===void 0&&(u.token_type="bearer"),c.hostname==="api.notion.com"&&c.pathname==="/v1/oauth/token"&&u.refresh_token===null&&delete u.refresh_token,u.expires_in!==void 0&&(u.expires_in=gN(u.expires_in));try{let d=await(n?rZ:e.grantType==="client_credentials"?pZ:dZ)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:e.adapter==="ebay"?rye:AZ});return{...i,...d}}catch(l){if(l instanceof Ct)throw l;U(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=e.adapter==="openrouter"?r.key:r.access_token;(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&U(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+gN(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&U(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?hN(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()+gN(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"&&U(400,"wrong_grant","This connection exchanges application credentials directly.");let u;if(e.adapter==="openrouter"){let p=o.parameters;(p.getAll("state").length!==1||p.get("state")!==o.state||p.getAll("code").length!==1||!p.get("code"))&&U(400,"invalid_state","Start the connection again.");let f=await this.transport.send({url:cf(e.tokenUrl,r.fields),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:p.get("code"),code_verifier:n,code_challenge_method:"S256"})});u=this.checkResponse(e,f.status,pg(f))}else{let{server:p,client:f}=this.configuration(e,r),m;try{let h=bZ(p,f,o.parameters,o.state);m=await iZ(p,f,this.authentication(r,e.clientAuth),h,e.adapter==="ebay"?r.fields.ruName:i,e.pkce?n:mN,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(h){throw(h instanceof ug||h instanceof dg)&&U(400,"invalid_state","Start the connection again."),h}u=await this.tokenResponse(e,r,m)}let l=this.token(e,u,s,a);await c?.(l,u);let d=await this.inspect(e,r,l,u);return a&&d.account!==a.account&&e.adapter!=="openrouter"&&U(409,"account_changed","Reconnect using the same service account."),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&U(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=$Z(s.token_endpoint,"/admin/oauth/access_token"),u=await fZ(s,a,this.authentication(r,e.clientAuth),{...e.tokenParams,...o.length&&!c?{scope:o.join(e.scopes.separator)}:{}},this.options(e.tokenFormat)),l=await this.tokenResponse(e,r,u),d={...this.token(e,l,o,n,!!n),requestedScopes:o};await i?.(d,l);let p=await this.inspect(e,r,d,l);return n&&p.account!==n.account&&U(409,"account_changed","Reconnect using the same service account."),p}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return this.clientCredentials(e,r,o.requestedScopes??e.scopes.default,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&U(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await Yq(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e.tokenFormat),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(e.identity?.url||e.adapter==="ebay"||e.adapter==="openrouter")&&(i=await this.inspect(e,r,i)),i.account!==o.account&&U(409,"account_changed","Reconnect using the same service account."),i}async inspect(e,r,o,n){let i=n??{};if(e.adapter==="ebay"){let{server:u,client:l}=this.configuration(e,r),d=await gZ({...u,introspection_endpoint:u.token_endpoint+"/introspect"},l,this.authentication(r,"basic"),o.accessToken,{...this.options(),additionalParameters:{token_type_hint:"access_token"}});try{i=await yZ(u,l,Response.json(await this.json(d),{status:d.status}))}catch{U(409,"reconnect_required","Reconnect this service to renew access.")}return(i.active!==!0||i.client_id!==r.clientId||typeof i.sub!="string"||!i.sub||typeof i.exp!="number"||i.exp*1e3<=Date.now())&&U(409,"reconnect_required","Reconnect this service to renew access."),{...o,account:i.sub,accountName:typeof i.username=="string"?i.username:i.sub,scopes:hN(i.scope),scopesStatus:"reported",accountVerified:!0,expiresAt:Math.min(o.expiresAt??1/0,i.exp*1e3)}}if(e.adapter==="openrouter"){let u=await this.transport.send({url:"https://openrouter.ai/api/v1/key",headers:{authorization:"Bearer "+o.accessToken}});i=pg(u),(u.status!==200||!i.data||typeof i.data!="object")&&U(409,"reconnect_required","Reconnect this service to renew access.");let l=i.data;return{...o,account:IZ(o.accessToken),accountName:typeof l.label=="string"?l.label:"OpenRouter",facts:l}}if(e.identity?.url){let u=cf(e.identity.url,{...r.fields,...o.extra,accessToken:o.accessToken,refreshToken:o.refreshToken??""}),l=e.grantType==="client_credentials"&&$Z(u,/^\/admin\/api\/[^/]+\/graphql\.json$/),d=await this.transport.send({url:u,method:e.identity.method,headers:l?{...e.identity.headers,"content-type":"application/json","X-Shopify-Access-Token":o.accessToken}:{...e.identity.headers,authorization:"Bearer "+o.accessToken},...l?{body:JSON.stringify({query:"{ shop { id name myshopifyDomain } }"})}:{}});i=pg(d),(d.status===401||d.status===403)&&U(409,"reconnect_required","Reconnect this service to renew access."),d.status>=400&&U(502,"invalid_response","The service account could not be verified."),l&&((Array.isArray(i.errors)?i.errors.length:i.errors)||Zo(i,"/data/shop/myshopifyDomain")!==r.fields.shop+".myshopify.com")&&U(502,"invalid_response","The Shopify store could not be verified."),e.adapter==="github"&&d.headers["x-oauth-scopes"]!==void 0&&(o.scopes=hN(d.headers["x-oauth-scopes"].replaceAll(","," ")),o.scopesStatus="reported"),e.adapter==="google"&&i.email_verified!==!0&&U(502,"invalid_response","The service account could not be verified.")}else e.identity?.from==="app"&&(i=r.fields);let s=u=>{for(let l of Array.isArray(u)?u:[u]){let d=Zo(i,l);if(typeof d=="string"&&d||typeof d=="number")return String(d)}return""},a=e.identity?.id,c=a?Array.isArray(a)?a.map(u=>s(u)).filter(Boolean).join(":"):s(a):o.account||r.fields.domain||r.fields.shop||IZ(o.accessToken);return(!c||c.length>1e3)&&U(502,"invalid_response","The service account could not be verified."),{...o,account:c,accountName:e.identity&&s(e.identity.name)||c,accountVerified:!!(e.identity?.url||e.identity?.from==="token"&&n)}}async revoke(e,r,o){e.revoke||U(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=cf(e.revoke.url,{...r.fields,clientId:r.clientId,accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:u,client:l}=this.configuration(e,r),d=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),p=await mZ({...u,revocation_endpoint:n},l,d,o.refreshToken??o.accessToken,this.options());try{await hZ(p)}catch{U(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:(s==="basic"||e.revoke.style==="github")&&(i.authorization="Basic "+Buffer.from(r.clientId+":"+(r.clientSecret??"")).toString("base64"));let a;e.revoke.style==="github"&&(i["content-type"]="application/json",a=JSON.stringify({access_token:o.accessToken})),(await this.transport.send({url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i,...a?{body:a}:{}})).status>=300&&U(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...r.fields,...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,nf(Zo(n,s))]))}};function Gs(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Qx(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(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=lt(nf(Zo(JSON.parse(Gs(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Gs(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}}function nye(t,e){return t.policy.contentType===Me.value?e.output===void 0:t.policy.contentType===Me.tokenSet&&e.output!==void 0}var Li=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},e0=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Gd(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Gd(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await Ne(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let p=await Gd(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:p,delivered:!1}),await this.broker.finish(r.lease,p),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(p=>{p.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let p=await NH(r.request,this.binding,this.keys);await wx(this.environment,p.intent);let f=Xd.parse(p.operation);if(pe[f.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await this.preflight(f,o,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.execute(f,o,r.sources,c);d=await Gd(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(p){if(p instanceof Li)throw p;p instanceof Jh&&(p=new Ct(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let f=l&&(c.aborted||!(p instanceof Ct)||["service_unavailable","connection_uncertain","lease_lost"].includes(p.code));d=await Gd(o,f?"uncertain":"failed",{ok:!1,result:null,error:p instanceof Ct?{code:p.code,message:p.message}:{code:f?"execution_uncertain":"invalid_execution",message:f?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){return e.kind==="http"?e.request:e.kind==="function"?Tx(e.definition,e.arguments):null}async preflight(e,r,o){if(new Set(o.map(s=>s.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let s of o){await qo(s);let a=r.sources.find(u=>u.id===s.policy.id);if(!a||!await kO(s,a))throw new Error("An execution input changed.");let c=await this.journal.read("checkpoint_"+s.policy.id);if(c&&(s.policy.revision<c.policy||s.materialRevision<c.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write("checkpoint_"+s.policy.id,{policy:s.policy.revision,material:s.materialRevision})}if(e.kind==="function"&&await Ne(e.definition)!==r.functionDigest)throw new Error("Run the exact function authorized by this intent.");let n=this.request(e);if(n){if(af(n.url,r.origin),[n.body,n.json,n.form].filter(a=>a!==void 0).length>1)throw new Error("Choose one request body format.");for(let a of n.bindings){let c=sg(a.pointer);if(!c.length||!["headers","body","json","form"].includes(c[0])||c[0]==="body"&&c.length!==1||["headers","form"].includes(c[0])&&c.length!==2)throw new Error("Bind credentials to request headers or the body.");WO(structuredClone(n),a.pointer,"validation")}let s=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};if(e.kind==="function"&&(Object.keys(s).length!==Object.keys(e.definition.save).length||Object.entries(e.definition.save).some(([a,c])=>s[a]?.name!==c)))throw new Error("Use the output destinations declared by this function.");for(let[a,c]of Object.entries(s)){if(sg(a),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let u=await Wd(c.approval);if(R(u.policy.authorities.find(l=>l.id===u.authorityId))!==R(r.actor)||u.policy.origin!==r.origin||u.policy.contentType!==Me.value||u.policy.ownerId!==r.ownerId||e.kind==="function"&&e.definition.outputOwnerId!==u.policy.ownerId||!u.policy.producers.some(l=>l.runId===r.id&&R(l.executor)===R(this.binding)&&Date.parse(l.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}}let i=e.kind==="command"?e.inputs.map(s=>s.source):n?n.bindings.flatMap(s=>s.parts.filter(a=>typeof a!="string")):[];for(let s of i){let a=o.find(c=>c.policy.id===s.id);if(!a||!nye(a,s))throw new Error("Use the input named in the signed request.");await zu(a,r,{...n?{destination:n.url}:{}}),await Fa(a,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async execute(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=[],a=new Map,c=async f=>{let m=o.find(y=>y.policy.id===f.id);if(m.policy.contentType===Me.value)return Fa(m,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");a.has(f.id)||a.set(f.id,this.extension.outputs(m,r,o,n,i?.url));let h=await a.get(f.id);if(!f.output||!Object.hasOwn(h,f.output))throw new Error("Choose an available connection output.");return lt(h[f.output])};if(e.kind==="command"){let f=await Qx(e.inputs,c),m=await this.commands.execute({command:e.command,timeoutSeconds:e.timeoutSeconds,...e.stdin===void 0?{}:{stdin:e.stdin},environment:f.environment,files:f.files},n);return{...m,stdout:ag(m.stdout,f.sensitive),stderr:ag(m.stderr,f.sensitive)}}let u=structuredClone(i);for(let f of u.bindings){let m="";for(let h of f.parts)if(typeof h=="string")m+=h;else{let y=Gs(await c(h));s.push(y,Buffer.from(y).toString("base64"),Buffer.from(y).toString("base64url")),m+=y}WO(u,f.pointer,m)}let l=u.body;u.json!==void 0&&(l=JSON.stringify(u.json),u.headers["content-type"]="application/json"),u.form!==void 0&&(l=new URLSearchParams(u.form).toString(),u.headers["content-type"]="application/x-www-form-urlencoded");let d=await this.transport.send({url:u.url,method:u.method,headers:u.headers,...l===void 0?{}:{body:l},signal:n}),p=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};if(Object.keys(p).length){if(d.status>=400)throw new Ct(502,"service_response","The service returned an unsuccessful response.");let f={};for(let[m,h]of Object.entries(p)){let y=d.body;if(m!==""){let b=Zo(JSON.parse(Gs(y)),m);if(b===void 0)throw new Ct(400,"invalid_pointer","The response value was not found.");y=lt(typeof b=="string"?b:JSON.stringify(b))}let w=await hx(y,h.approval,r.id,this.binding,this.keys,{bytes:y.length});f[h.name]=(await this.broker.capture(h.name,w)).id}return{status:d.status,saved:f}}return{status:d.status,headers:Object.fromEntries(Object.entries(d.headers).map(([f,m])=>[f,ag(m,s)])),body:ag(Gs(d.body),s)}}};var ua=St(wne(),1);import{randomUUID as SAe}from"node:crypto";function xAe(t){let e=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(t);return e?`arn:${e[1]}:iam::${e[2]}:role/${e[3]}`:/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/.+$/.test(t)?t:null}async function bne(t=3e3){let e=new ua.STSClient({region:process.env.AWS_REGION||"us-east-1"});try{let r=await e.send(new ua.GetCallerIdentityCommand({}),{abortSignal:AbortSignal.timeout(t)});return r.Arn?xAe(r.Arn):null}catch{return null}finally{e.destroy()}}var _$=class{async obtain(e,r,o){let n=new ua.STSClient({region:o});try{let s=(await n.send(new ua.AssumeRoleCommand({RoleArn:e,RoleSessionName:"foundation-"+SAe().slice(0,8),ExternalId:r,DurationSeconds:3600}))).Credentials;(!s?.AccessKeyId||!s.SecretAccessKey||!s.SessionToken)&&U(502,"invalid_response","AWS did not return credentials.");let a=new ua.STSClient({region:o,credentials:{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken}});try{(await a.send(new ua.GetCallerIdentityCommand({}))).Account!==e.split(":")[4]&&U(502,"account_changed","The AWS account could not be verified.")}finally{a.destroy()}return{AWS_ACCESS_KEY_ID:s.AccessKeyId,AWS_SECRET_ACCESS_KEY:s.SecretAccessKey,AWS_SESSION_TOKEN:s.SessionToken,AWS_DEFAULT_REGION:o}}catch(i){if(i instanceof Ct)throw i;U(502,"role_denied","Check the IAM role and its trust policy for this executor.")}finally{n.destroy()}}};function A4(t,e){if(t.kind==="role")return{};let r=t.config.fields,o={...t.kind==="oauth"?t.config.defaults:{},...e};for(let n of r)n.required!==!1&&!o[n.name]&&U(400,"missing_field","Complete the required service fields."),o[n.name]?.includes("\0")&&U(400,"invalid_field","Check the service fields."),n.pattern&&(n.pattern.length>200||!(0,Sne.default)(n.pattern))&&U(400,"invalid_pattern","Use a simple field validation pattern."),n.pattern&&o[n.name]&&!new RegExp(n.pattern,"u").test(o[n.name].slice(0,1e3))&&U(400,"invalid_field","Check the service fields.");return Object.keys(e).some(n=>!r.some(i=>i.name===n))&&U(400,"invalid_field","Remove unrecognized service fields."),o}var Cp=class{constructor(e,r,o,n,i,s=new _$){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.roles=s}binding;keys;broker;journal;transport;roles;active=new Set;oauth(e){return new Yx({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||U(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=qs.parse(JSON.parse(Gs(await Fa(e,r,this.keys,{destination:o}))));return(await Mu(n)).authorizationDigest!==e.metadata.authorizationDigest&&U(409,"connection_changed","Approve the current service account and permissions before using this connection."),n.state==="reconnect"&&r.operation!==pe.revoke&&U(409,"reconnect_required","Reconnect this service before using it."),n}async app(e,r,o,n){let i=this.source(e,Me.clientCredential,n),s=Ha.parse(JSON.parse(Gs(await Fa(i,o,this.keys))));return s.methodId!==r&&U(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(!ju(e.method))return Ha.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===pe.revoke?pe.revoke:pe.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&U(409,"app_changed","Reconnect this service with the current application."),i}async flow(e,r){let o=await this.journal.read("oauth_"+e);return(!o||o.expiresAt<=Date.now()||R(o.actor)!==R(r.actor)||o.ownerId!==r.ownerId)&&U(409,"connection_expired","Start the connection again."),o}async validate(e,r,o){let n=Ex.parse(e),i=pe[n.action==="refresh"||n.action==="revoke"?n.action:"connect"];if(r.operation!==i&&U(400,"wrong_operation","Use the approved connection operation."),n.action==="start")if(n.method.kind==="oauth"){if(ju(n.method)&&!n.appId&&U(400,"app_required","Choose an OAuth application."),n.method.config.grantType!=="client_credentials"){n.redirectUri||U(400,"invalid_redirect","Choose a callback URL.");let a=new URL(n.redirectUri);(a.username||a.password||a.hash||a.search||!(n.redirectUri===r.origin+"/oauth/callback"||a.protocol==="http:"&&["127.0.0.1","[::1]"].includes(a.hostname)))&&U(400,"invalid_redirect","Use the Foundation callback or a callback on this computer.")}let s=n.appId?await this.app(n.appId,n.methodId,r,o):Ha.parse({format:1,methodId:n.methodId,generation:n.flowId,clientId:"",fields:{}});A4(n.method,s.fields),ju(n.method)&&n.method.config.clientAuth!=="none"&&!s.clientSecret&&U(409,"app_required","Add a client secret to this OAuth application.")}else n.method.kind==="token"?A4(n.method,n.fields):n.role||U(400,"role_required","Choose a role trusted for this executor.");else if(n.action==="commit"){let s=await this.flow(n.flowId,r),a=await Wd(n.approval);(!s.material||n.authorizationDigest!==(await Mu(s.material)).authorizationDigest||a.policy.contentType!==Me.tokenSet||a.policy.ownerId!==r.ownerId||a.policy.origin!==r.origin||R(a.policy.authorities.find(c=>c.id===a.authorityId))!==R(r.actor)||!a.policy.producers.some(c=>c.runId===r.id&&R(c.executor)===R(this.binding)&&Date.parse(c.expiresAt)>Date.now()))&&U(403,"approval_required","Review the connection and approve its recipients before saving.")}else if(n.action==="exchange"){let s=await this.flow(n.flowId,r);if(s.app&&s.input.appId){let a=await this.app(s.input.appId,s.input.methodId,r,o);R(a)!==R(s.app)&&U(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,Me.tokenSet,o),a=await this.material(s,r);a.method.kind==="oauth"&&await this.connectionApp(a,r,o)}}async execute(e,r,o,n){let i=Ex.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&U(409,"connection_busy","Another operation is updating this connection."),this.active.add(s);try{if(n.throwIfAborted(),i.action==="start")return await this.start(i,r,o,n);if(i.action==="exchange")return await this.exchange(i,r,n);if(i.action==="commit")return await this.commit(i,r);let a=this.source(i.id,Me.tokenSet,o),c=await this.material(a,r);if(i.action==="refresh"){let u=c.method.kind==="oauth"?await this.refresh(a,c,r,o,n):c;return{kind:"refreshed",id:a.policy.id,...await Mu(u)}}return c.method.kind!=="oauth"&&U(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await this.oauth(n).revoke(c.method.config,await this.connectionApp(c,r,o),c.oauth),{kind:"revoked",id:a.policy.id}}finally{this.active.delete(s)}}async review(e,r){return{kind:"review",flowId:e,name:r.input.name,metadata:{...await Mu(r.material),...xx(r.material)}}}async start(e,r,o,n){let i="oauth_"+e.flowId;await this.journal.read(i)&&U(409,"flow_exists","Use a new connection request.");let s={actor:r.actor,ownerId:r.ownerId,input:e,app:e.method.kind!=="oauth"?null:e.appId?await this.app(e.appId,e.methodId,r,o):Ha.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}}),state:_ne(32).toString("base64url"),verifier:_ne(32).toString("base64url"),expiresAt:Math.min(Date.now()+6e5,Date.parse(r.expiresAt)),phase:e.method.kind==="oauth"?"authorize":"review"};if(e.method.kind!=="oauth"&&(e.method.kind==="role"&&await this.roles.obtain(e.role.arn,e.role.externalId,e.role.region),s.material=qs.parse({format:1,methodId:e.methodId,method:e.method,generation:S$(),appId:null,appGeneration:null,...e.method.kind==="role"?{role:e.role}:{fields:A4(e.method,e.fields)}})),await this.journal.write(i,s),e.method.kind!=="oauth")return this.review(e.flowId,s);let a=[...new Set([...e.method.config.scopes.default,...e.scopes])];if(e.method.config.grantType==="client_credentials"){s.phase="exchanging",await this.journal.write(i,s);let c=await this.oauth(n).clientCredentials(e.method.config,s.app,a,void 0,async(u,l)=>{s.checkpoint={token:u,response:l},s.phase="received",await this.journal.write(i,s)});return s.material=qs.parse({format:1,methodId:e.methodId,method:e.method,generation:S$(),appId:e.appId,appGeneration:s.app.generation,oauth:c}),s.phase="review",await this.journal.write(i,s),this.review(e.flowId,s)}return e.redirectUri===r.origin+"/oauth/callback"&&await this.broker.relay?.({id:e.flowId,runId:r.id,stateDigest:await Ne(s.state),expiresAt:new Date(s.expiresAt).toISOString()}),{kind:"authorize",flowId:e.flowId,url:await this.oauth().authorize(e.method.config,s.app,s.state,s.verifier,e.redirectUri,a)}}async exchange(e,r,o){let n=await this.flow(e.flowId,r),i="oauth_"+e.flowId;if(n.phase==="review")return this.review(e.flowId,n);(n.input.method.kind!=="oauth"||!n.app||!["authorize","received"].includes(n.phase))&&U(409,"connection_uncertain","Check the connection before authorizing it again.");let s=this.oauth(o),a=n.input.method.config,c=new URLSearchParams(e.parameters);(c.getAll("state").length!==1||c.get("state")!==n.state)&&U(400,"invalid_state","Start the connection again.");let u;return n.phase==="received"?u=await s.inspect(a,n.app,n.checkpoint.token,n.checkpoint.response):(n.phase="exchanging",await this.journal.write(i,n),u=await s.exchange(a,n.app,{parameters:c,state:n.state},n.verifier,n.input.redirectUri,[...new Set([...a.scopes.default,...n.input.scopes])],void 0,async(l,d)=>{n.checkpoint={token:l,response:d},n.phase="received",await this.journal.write(i,n)})),n.material=qs.parse({format:1,methodId:n.input.methodId,method:n.input.method,generation:S$(),appId:n.input.appId,appGeneration:n.input.appId?n.app.generation:null,oauth:u}),n.phase="review",await this.journal.write(i,n),this.review(e.flowId,n)}async commit(e,r){let o=await this.flow(e.flowId,r),n="oauth_"+e.flowId;if(o.phase==="committed")return{kind:"connected",id:o.content.policy.id};["review","committing"].includes(o.phase)||U(409,"approval_required","Review this connection before saving."),o.content?(R(o.content.policy)!==R(e.approval.policy)||o.content.creationRunId!==r.id)&&U(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await hx(lt(R(o.material)),e.approval,r.id,this.binding,this.keys,await Mu(o.material)),o.phase="committing",await this.journal.write(n,o));let i;try{i=await this.broker.capture(o.input.name,o.content,xx(o.material))}catch(s){throw s instanceof Ct&&s.status<500?s:new Li}return o.phase="committed",await this.journal.write(n,o),{kind:"connected",id:i.id}}async recover(e,r){let o=Ex.parse(e);if(o.action!=="commit")return null;let n="oauth_"+o.flowId,i=await this.journal.read(n);if(!i?.content||i.ownerId!==r.ownerId||R(i.actor)!==R(r.actor)||i.content.creationRunId!==r.id||R(i.content.policy)!==R(o.approval.policy)||!["committing","committed"].includes(i.phase))return null;try{await this.broker.capture(i.input.name,i.content,xx(i.material))}catch(s){if(s instanceof Ct&&s.status<500)return null;throw new Li}return i.phase="committed",await this.journal.write(n,i),{kind:"connected",id:i.content.policy.id}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);if(s.method.kind==="token")return Object.fromEntries(Object.entries(s.method.config.outputs).map(([a,c])=>[a,nf(Zo(s.fields,c))]));if(s.method.kind==="role")return this.roles.obtain(s.role.arn,s.role.externalId,s.role.region);if(await this.broker.state(e.policy.id)&&U(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),s.method.kind!=="oauth")throw new Error("Use an OAuth connection.");return this.oauth(n).outputs(s.method.config,await this.connectionApp(s,r,o),s.oauth)}async refreshed(e,r){let o=qs.parse({...e.material,oauth:r}),n=await Mu(o);return n.authorizationDigest!==e.previous.metadata.authorizationDigest&&U(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=o,e.content=await CH(e.previous,lt(R(o)),this.binding,this.keys,n),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),o}async refresh(e,r,o,n,i,s){if(r.method.kind!=="oauth"||r.oauth.expiresAt===null||r.oauth.expiresAt>=Date.now()+6e4)return r;try{await zu(e,{...o,operation:pe.refresh},{destination:s})}catch{U(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let a=await this.connectionApp(r,o,n),c=S$(),u=await this.broker.prepare(c,e.policy.id,e.materialRevision),l={operation:u,previous:e,material:r,app:a,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+c,l);try{i.throwIfAborted(),l.phase="dispatched",await this.journal.write("refresh_"+c,l),await this.broker.dispatch(c,u.fence),i.throwIfAborted();let d=await this.oauth(i).refresh(r.method.config,a,r.oauth,async(p,f)=>{l.checkpoint={token:p,response:f},l.phase="received",await this.journal.write("refresh_"+c,l)});return await this.refreshed(l,d)}catch(d){if(l.phase==="prepared"?await this.broker.abort(c,u.fence):await this.broker.uncertain(c,u.fence).catch(()=>{}),d instanceof Ct&&["connection_review","reconnect_required","account_changed"].includes(d.code))throw d;U(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("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&&o.material.method.kind==="oauth"){let i=await this.oauth().inspect(o.material.method.config,o.app,o.checkpoint.token,o.checkpoint.response);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}};function Hr(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=T4(EAe(Hs()),"custody",r.id),i=new Lu(T4(n,"client"),o,r,e),s=new Rx(t,o,r,e,new Cx(i)),a=new Ox(t),c=new Xx(o),u=new Cp(r,e,a.connections(),new Lu(T4(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 xne(t,e){let{custody:r,keys:o,binding:n,connections:i}=Hr(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 Ne(n),operation:pe.command,functionDigest:null,operationDigest:await Ne(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await Ne(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===Me.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Qx(e,async u=>{let l=s.find(p=>p.policy.id===u.id);if(l.policy.contentType===Me.value)return Fa(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 lt(d[u.output])})}import{mkdir as $Ae}from"node:fs/promises";import{join as O4}from"node:path";import{setTimeout as AAe}from"node:timers/promises";import{spawn as kAe}from"node:child_process";import{constants as P4}from"node:fs";import{open as Ene,rm as IAe}from"node:fs/promises";async function kne(t){if(process.platform!=="linux"){let r=await Ene(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await IAe(t,{force:!0})}}let e=await Ene(t,P4.O_CREAT|P4.O_WRONLY|P4.O_NOFOLLOW,384);try{let r=kAe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var R4=g.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),C4=R4.max(4096).startsWith("/"),Ine=g.object({command:g.array(R4.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:C4.optional(),environment:g.record(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),R4.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:g.string().max(1e6).default(""),timeoutSeconds:g.number().int().min(1).max(3600).default(60)}).strict(),$pt=Ine.extend({id:k.optional()}),$ne=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),Ane=g.object({exitCode:g.number().int().nullable(),signal:g.string().max(32).nullable(),stdout:g.string().max(1e6),stderr:g.string().max(1e6),timedOut:g.boolean(),truncated:g.boolean()}).strict(),Apt=g.object({state:$ne.exclude(["queued","running"]),result:Ane.nullable(),error:g.string().max(100).nullable()}).strict(),x$=Ine.extend({id:k,environmentId:k,ownerId:k,actorId:k,workingDirectory:C4,state:$ne,result:Ane.nullable(),error:g.string().nullable(),createdAt:Be,startedAt:Be.nullable(),finishedAt:Be.nullable()}).strict(),Tpt=x$.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),Ppt=g.object({workingDirectory:C4}).strict(),Tne=g.object({lease:k,process:x$}).strict().nullable();var E$=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},Tne)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},x$)}},k$=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Li}return!0}};async function I$(t,e){let{directory:r,keys:o,binding:n,broker:i,transport:s}=Hr(t),a=k.parse(e.id??crypto.randomUUID()),c=O4(r,"executors",a);await $Ae(c,{recursive:!0,mode:448});let u=await kne(O4(c,"process.lock")),l=new AbortController,d=()=>l.abort();process.on("SIGINT",d),process.on("SIGTERM",d);try{let p=new Lu(c,t.identity.origin,n,o),f=await p.read("environment_"+a),m=await bne();if(f){if(await Jd(f),f.manifest.ownerId!==e.ownerId||R(f.manifest.executor)!==R(n))throw new Error("Use the owner and identity originally registered for this executor.");if((f.manifest.awsPrincipal??null)!==m){let{awsPrincipal:_,...x}=f.manifest;f=await $O({...x,...m?{awsPrincipal:m}:{},revision:x.revision+1},o),await p.write("environment_"+a,f)}}else f=await $O({format:3,id:a,origin:t.identity.origin,ownerId:e.ownerId,name:e.name,executor:n,operatorId:n.principalId,driver:e.managed?"managed":"attached",capabilities:Object.values(pe),isolation:e.isolation,...e.image?{commandImage:e.image}:{},...m?{awsPrincipal:m}:{},revision:1},o),await p.write("environment_"+a,f);await t.json("/api/environments/"+a+"/registration",{method:"PUT",body:f}),process.stdout.write(JSON.stringify({environmentId:a,identityId:n.principalId,fingerprint:await Ou(n),isolation:f.manifest.isolation,...f.manifest.awsPrincipal?{awsPrincipal:f.manifest.awsPrincipal}:{},...f.manifest.isolation==="process"?{notice:"Only allow trusted code on this host."}:{}})+`
130
+ `),{mode:384,flag:"wx"}),this.options.workspace&&await BH(this.options.workspace,{recursive:!0,mode:448}),l=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",p,...d.flatMap(([f,m])=>["--env",f+"="+m]),...this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(d=>{let p=VH(l[0],l.slice(1),{env:Qd(s?{}:u),cwd:s?this.options.cwd:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),f={stdout:new qH("utf8"),stderr:new qH("utf8")},m=0,h=!1,y=(x,$)=>{let O=Math.max(0,1e6-m);$.length>O&&(a.truncated=!0);let H=$.subarray(0,O);m+=H.length,a[x]+=f[x].write(H)};p.stdout.on("data",x=>y("stdout",x)),p.stderr.on("data",x=>y("stderr",x)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let w=()=>{c=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},b=setTimeout(()=>{a.timedOut=!0,w()},e.timeoutSeconds*1e3);b.unref();let _=()=>{h||(h=!0,clearTimeout(b),r.removeEventListener("abort",w),a.stdout+=f.stdout.end(),a.stderr+=f.stderr.end(),d())};r.addEventListener("abort",w,{once:!0}),r.aborted&&w(),p.once("error",()=>{a.exitCode=127,a.stderr="The command could not be started.",_()}),p.once("close",(x,$)=>{a.exitCode=x,a.signal=$,_()})}),a}finally{s&&c&&await new Promise(u=>{let l=VH("docker",["rm","-f",i],{env:Qd(),stdio:"ignore"});l.once("close",()=>u()),l.once("error",()=>u()),setTimeout(()=>{l.kill("SIGKILL"),u()},1e4).unref()}),await Xpe(o,{recursive:!0,force:!0})}}};function sme(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 _x=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 ime("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 KH(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await tme(ZH(ome(),"foundation-"));await eme(r,448);try{let o=Qd(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=ZH(r,i);await nme(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=Qpe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=sme(n),u=new _x(c,m=>process.stdout.write(m)),l=new _x(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,h)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(m??(h==="SIGINT"?130:h==="SIGTERM"?143:1))})})}finally{await rme(r,{recursive:!0,force:!0})}}import{dirname as EAe,join as T4}from"node:path";var Sx=g.record(g.string().max(100),g.string().max(16384)),Ha=g.object({format:g.literal(1),methodId:g.string().min(1),generation:k,clientId:g.string().max(1e3),clientSecret:g.string().max(16384).optional(),fields:Sx}).strict();function ju(t){return t.kind==="oauth"&&t.config.adapter!=="openrouter"}var ame=g.object({accessToken:g.string().min(1).max(16384),refreshToken:g.string().min(1).max(16384).optional(),expiresAt:g.number().nullable(),refreshExpiresAt:g.number().optional(),scopes:g.array(g.string()),requestedScopes:g.array(g.string()).optional(),account:g.string(),accountName:g.string(),accountVerified:g.boolean().optional(),scopesStatus:g.enum(["unknown","requested","reported"]).optional(),extra:Sx,facts:Au}).strict(),qs=g.object({format:g.literal(1),methodId:g.string().min(1),method:Tu,generation:k,appId:k.nullable(),appGeneration:k.nullable(),state:g.literal("reconnect").optional(),oauth:ame.optional(),fields:Sx.optional(),role:g.object({arn:g.string().regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),externalId:g.string().min(16).max(1e3),region:g.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/)}).strict().optional()}).strict().superRefine((t,e)=>{(t.method.kind==="oauth"&&(!t.oauth||ju(t.method)&&(!t.appId||!t.appGeneration))||t.method.kind==="token"&&!t.fields||t.method.kind==="role"&&!t.role)&&e.addIssue({code:"custom",message:"Supply the material required by this connection method."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."})}),oFe=g.object({methodId:g.string().min(1).max(200),clientId:g.string().max(1e3),generation:k}).strict(),cme=g.object({methodId:g.string().min(1).max(200),methodKind:lO,generation:k,authorizationDigest:mr,appId:k.nullable(),accountId:g.string().max(2e3).nullable(),accountVerified:g.boolean(),scopes:g.array(g.string().max(1e3)).max(200),scopesStatus:g.enum(["unknown","requested","reported"]),outputs:g.array(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:g.enum(["ready","reconnect"])}).strict();async function Mu(t){let e=t.method.kind==="role"?["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION"]:Object.keys(t.method.config.outputs),r=await Ne({generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:t.oauth?.account??t.role?.arn??null,accountVerified:t.oauth?.accountVerified??!1,scopes:[...t.oauth?.scopes??[]].sort(),role:t.role??null,...t.state?{state:t.state}:{}});return cme.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:r,appId:t.appId,accountId:t.role?.arn??(t.oauth?.accountVerified?t.oauth.account:null),accountVerified:!!(t.role||t.oauth?.accountVerified),scopes:t.oauth?.scopes??[],scopesStatus:t.oauth?.scopesStatus??"unknown",outputs:e,state:t.state??"ready"})}var WH=g.object({methodName:le,account:g.string().max(2e3)}).strict();function xx(t){return{methodName:t.method.name,account:t.oauth?.accountName??t.role?.arn??t.method.name}}var ume=g.object({action:g.literal("start"),flowId:k,name:le,methodId:g.string().min(1),method:Tu,appId:k.nullable(),fields:Sx.default({}),scopes:g.array(g.string().max(1e3)).max(200).default([]),redirectUri:g.url().optional(),role:qs.shape.role}).strict(),Ex=g.discriminatedUnion("action",[ume,g.object({action:g.literal("exchange"),flowId:k,parameters:g.string().max(16384)}).strict(),g.object({action:g.literal("commit"),flowId:k,authorizationDigest:mr,approval:Wh}).strict(),g.object({action:g.literal("refresh"),id:k}).strict(),g.object({action:g.literal("revoke"),id:k}).strict()]);var JH=Di.extend({name:le}),GH=g.object({id:k,index:g.number().int().min(0).max(7),input:SH.extend({ownerId:k})}).strict(),fFe=g.object({bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Di,token:g.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),XH=g.object({id:k,executorId:k,ownerId:k,name:le,origin:g.url(),bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),pFe=Di.extend({previousSignature:Dn.optional()}).strict(),mFe=g.object({name:le,content:io,labels:WH.optional(),version:g.number().int().positive().optional()}).strict(),YH=g.object({content:io,version:g.number().int().positive()}).strict(),QH=g.object({id:k,reason:g.enum(["grantExpired"])}).strict(),hFe=g.record(k,g.object({version:g.number().int().positive(),content:io}).strict()),gFe=g.object({id:k,name:le,version:g.number().int().positive(),content:io,policy:zi}).strict(),eq=g.object({registration:IO,stoppedAt:g.iso.datetime().nullable(),heartbeatAt:g.iso.datetime().nullable()}).strict(),tq=g.object({lease:k,request:yx,sources:g.array(io).max(100)}).strict().nullable(),lme=g.object({lease:k}).strict(),yFe=lme.extend({receipt:Gh}).strict(),eg=g.object({id:k,resource_id:k,executor_id:k,expected_revision:g.number().int().positive(),state:g.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:g.string().regex(/^\d+$/),result:io.nullable()}),vFe=g.object({id:k,resourceId:k,expectedRevision:g.number().int().positive()}).strict(),dme=g.object({fence:g.string().regex(/^\d+$/)}).strict(),wFe=dme.extend({content:io}).strict(),bFe=g.object({id:k,runId:k,stateDigest:mr,expiresAt:Be}).strict(),kx=g.object({id:k,runId:k,context:g.string(),sealed:Ho.nullable(),expiresAt:Be,receivedAt:Be.nullable()}).strict(),rq=(t,e)=>"oauth-callback:"+t+":"+e;var Ks=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"}},fme=class extends Ks{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"}},pme=class extends Ks{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},mme=class extends Ks{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"}},hme=class extends Ks{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"}},gme=class extends Ks{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},yme=class extends Ks{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"}},vme=class extends Ks{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"}},$x=class extends Ks{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},RO=class extends $x{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"}},wme=class extends $x{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"}},bme=class extends $x{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"}},nq=class extends $x{constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},_me=class extends Ks{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"}},Sme=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},xme=class extends Sme{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"}},Eme=["","+",".","/",";","?","&","#"],lq={"":{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}},kme=new TextEncoder,oq="0123456789ABCDEF",iq=t=>Za(Dr(48,57),Dr(65,70),Dr(97,102))(t.charCodeAt(0)),ng=(t,e)=>t[e]==="%"&&e+2<t.length&&iq(t[e+1])&&iq(t[e+2]);function CO(t,e){let r=t[e];return r==null?0:Za(dq,fq,Uu("_"))(r)?1:ng(t,e)?3:0}function Ime(t,e){if(ng(t,e))return 3;let{char:r,size:o}=og(t,e);return Ame(r)?o:0}function og(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var zO=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&ng(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=og(e,o);r+=Za(pq,s=>t&&$me(s))(n)?n:mq(n),o+=i}return r};function ef(t){let e="";for(let r=0;r<t.length;){if(ng(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=og(t,r);e+=pq(o)?o:mq(o),r+=n}return e}function tg(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(ng(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=og(t,n);r+=i,n+=s}return r}var dq=t=>Za(Dr(65,90),Dr(97,122))(t.charCodeAt(0)),fq=t=>Dr(48,57)(t.charCodeAt(0)),pq=t=>Za(dq,fq,e=>"-._~".includes(e))(t),$me=t=>":/?#[]@!$&'()*+,;=".includes(t),Ame=t=>Tme(t.codePointAt(0)),Tme=t=>t!=null&&Za(Uu(33),Dr(35,36),Uu(38),Dr(40,59),Uu(61),Dr(63,91),Uu(93),Uu(95),Dr(97,122),Uu(126),Pme,Rme)(t);function Pme(t){if(t<65536)return Za(Dr(160,55295),Dr(63744,64975),Dr(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var Rme=t=>Za(Dr(57344,63743),Dr(983040,1048573),Dr(1048576,1114109))(t),mq=t=>Array.from(kme.encode(t)).map(e=>`%${oq[e>>4]}${oq[e&15]}`).join(""),Dr=(t,e)=>r=>t<=r&&r<=e,Uu=t=>e=>t===e,Za=(...t)=>e=>t.some(r=>r(e));function hq(t,e,r){return t.map(o=>o.kind==="literal"?o.text:Cme(o.vars,o.operator,e,r)).join("")}function Cme(t,e,r,o){let n=lq[e],i=t.flatMap(s=>Ome(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function Ome(t,e,r,o){if(e==null)return[];if(Fme(e)){let n=jme(e,r.allowReserved);return n.length<1?[]:sq(t,"list",o)?Dme(t,n,r):[]}if(Lme(e)){let n=Mme(e,r.allowReserved);return n.length<1?[]:sq(t,"associative",o)?zme(t,n,r):[]}return Nme(t,e,r)}function Nme(t,e,r){let o=String(e),n=t.prefix==null?o:tg(o,t.prefix),i=zO(r.allowReserved)(n);return r.named?[rg(ef(t.name),i,r)]:[i]}function Dme(t,e,r){let o=ef(t.name);if(t.explode)return r.named?e.map(i=>rg(o,i,r)):[...e];let n=e.join(",");return r.named?[rg(o,n,r)]:[n]}function zme(t,e,r){if(t.explode)return e.map(([n,i])=>rg(n,i,r));let o=e.flat(1).join(",");return r.named?[rg(ef(t.name),o,r)]:[o]}var rg=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,jme=(t,e)=>t.filter(r=>r!=null).map(String).map(zO(e)),Mme=(t,e)=>Object.entries(t).map(([r,o])=>[r,Ume(o)]).filter(([,r])=>r!=null).map(r=>r.map(zO(e)));function Ume(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 Lme=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Fme=t=>Array.isArray(t);function sq(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new xme(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function Vme(t,e,r){return OO(t,e,r,0,0,{})}function OO(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=hhe(i);return hq(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?OO(t,e,r,o+1,n+s.text.length,i):null;for(let a of Bme(t,e,o,n)){let c=e.slice(n,a);for(let u of qme(s.vars,s.operator,c)){let l=jO(i,u);if(l==null)continue;let d=OO(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*Bme(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*Hme(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*Hme(t,e){for(let r=t;r>=e;r--)yield r}function*qme(t,e,r){if(r===""){yield*Zme(t,e);return}let o=lq[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?the(t,o,n):Kme(t,o,n)}var Zme=(t,e)=>(e===""||e==="+")&&t.length===1?[qa(t[0],"")]:[{}],Kme=(t,e,r)=>NO(t,e,MO(r,e.sep),0,0);function*NO(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of Wme(i,e,r,n))for(let a of NO(t,e,r,o+1,s.index)){let c=jO(s.bindings,a);c!=null&&(yield c)}yield*NO(t,e,r,o+1,n)}function*Wme(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 Jme(t,e,s))yield{bindings:a,index:o+i}}}function*Jme(t,e,r){let o=gq(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*Gme(t,e,r)),yield*o}function*Gme(t,e,r){let o=yq(r,e.allowReserved);if(o==null)return;let n=Xme(r,e);n!=null&&(yield qa(t,n)),yield qa(t,o)}var Xme=(t,e)=>Yme(t.join(e.sep),e);function Yme(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=Qme(t,i,e.sep),a=Zs(t.slice(o,n),e.allowReserved),c=Zs(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 Qme(t,e,r){for(let o=e;o<t.length;o++)if(ehe(t,o,r))return o;return t.length}var ehe=(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*gq(t,e,r){let o=Zs(r,e.allowReserved);if(o==null)return;let n=qa(t,o);if(t.prefix!=null){yield n;return}let i=MO(r,",");if(i.length<2){yield n;return}let s=yq(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?lhe(i,e.allowReserved):null;a!=null&&(yield qa(t,a)),yield qa(t,s),yield n}var the=(t,e,r)=>DO(t,e,MO(r,e.sep).map(uhe),0,0);function*DO(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of rhe(i,e,r,n,t))for(let a of DO(t,e,r,o+1,s.index)){let c=jO(s.bindings,a);c!=null&&(yield c)}yield*DO(t,e,r,o+1,n)}function*rhe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*ohe(t,e,r,o,n);return}yield*nhe(t,e,r,o)}}function*nhe(t,e,r,o){let n=r[o];if(n.name===ef(t.name))for(let i of gq(t,e,n.value))yield{bindings:i,index:o+1}}function*ohe(t,e,r,o,n){yield*ihe(t,e,r,o),yield*ahe(t,e,r,o,n)}function*ihe(t,e,r,o){let n=[...she(ef(t.name),e,r,o)];n.length>0&&(yield{bindings:qa(t,n),index:o+n.length})}function*she(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Zs(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*ahe(t,e,r,o,n){let i=[...che(e,r,o,new Set(n.map(s=>ef(s.name))))];i.length>0&&(yield{bindings:qa(t,Object.fromEntries(i)),index:o+i.length})}function*che(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=Zs(i.name,t.allowReserved),a=Zs(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function uhe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function lhe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Zs(t[o],e),i=Zs(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function yq(t,e){let r=[];for(let o of t){let n=Zs(o,e);if(n==null)return null;r.push(n)}return r}function Zs(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var qa=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function jO(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=dhe(i,n);if(s==null)return null;r[o]=s}return r}var dhe=(t,e)=>Ix(t)||Ix(e)?fhe(t,e):phe(t.value,e.value)?t:null;function fhe(t,e){let r=aq(t.value),o=aq(e.value);if(r==null||o==null)return null;let n=Ix(t),i=Ix(e);if(!n&&!i)return null;if(n&&!i)return tg(o,t.prefix)===r?e:null;if(!n&&i)return tg(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?tg(o,s)===r?e:null:tg(r,a)===o?t:null}var Ix=t=>t.prefix!=null,aq=t=>typeof t=="string"?t:null;function phe(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):cq(t)?cq(e)&&mhe(Object.entries(t),Object.entries(e)):t===e}var mhe=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),cq=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hhe=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),MO=(t,e)=>e===""?[t]:t.split(e),ghe=["=",",","!","@","|"];function yhe(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new gme(e,r));let n=t[0];if(_he(n))return o(new yme(e,r+1,n));if(!uq(n)&&CO(t,0)<1)return o(new vme(e,r+1,n));let i=uq(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:vhe(t,e,r+1,s)}}function vhe(t,e,r,o){if(o>=t.length)throw new RO(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new nq(e,r+i):new RO(e,r+i);let s=i,a=whe(t,i);if(a===s)throw new RO(e,r+i);let c=t.slice(s,a);i=a;let u=bhe(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new _me(e,r+i,t[i]):new wme(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 nq(e,r+i-1)}return n}function whe(t,e){let r=e,o=!0;for(;r<t.length;){let n=CO(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||CO(t,r+1)<1)break;r++,o=!0}return r}function bhe(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&&She(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new bme(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function uq(t){return Eme.includes(t)&&t!==""}function _he(t){return ghe.includes(t)}function She(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function xhe(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 fme(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new mme(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let p=t.slice(i+1,l);try{o.push(yhe(p,t,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new pme(t,i)),n(s),i++;continue}let a=Ime(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=og(t,i);r(new hme(t,i,c)),n(c),i+=u}return o}var Ax=class vq{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=Ahe(r),this.#e=Ehe(xhe(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new vq(e,r)}get tokens(){return this.#e}expand=e=>hq(this.#e,e,this.#t);match=e=>Vme(this.#e,e,this.#t);toString=()=>this.uriTemplate},Ehe=t=>Object.freeze(t.map(khe)),khe=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(Ihe))}),Ihe=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),$he=()=>{},Ahe=({strict:t,report:e})=>(e??=$he,t??=!0,e=t?The(e):e,{strict:t,report:e}),The=t=>e=>{throw t(e),e};function Tx(t,e){let r={};if(Object.keys(e).some(a=>!t.parameters.some(c=>c.name===a)))throw new Error("Use the parameters this function declares.");for(let a of t.parameters){let c=e[a.name]??a.default??"";if(a.required&&!c)throw new Error("Complete the required function parameters.");if(c.length>8192)throw new Error("The function argument is too long.");r[a.name]=c}let o=a=>typeof a=="string"?a.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(c,u)=>{if(!Object.hasOwn(r,u))throw new Error("Declare every function parameter.");return r[u]}):Array.isArray(a)?a.map(o):a&&typeof a=="object"?Object.fromEntries(Object.entries(a).map(([c,u])=>[c,o(u)])):a,n=new Ax(t.request.url).expand(r),i=Pu.parse({...o(t.request),url:n,bindings:t.request.bindings}),s=new URL(t.request.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(n).origin!==s.origin)throw new Error("The function must have a fixed destination host.");return i}var Px=class extends Error{constructor(r,o){super(o);this.code=r}code},UO=class extends Error{constructor(r){super("The execution request is saved locally. Check execution "+r+" before starting another operation.");this.id=r}id},Rx=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;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||R(r)!==R(e))throw new Px("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+k.parse(e)+"/binding",{},Di);return await vO(r),{...r,fingerprint:await Ou(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new Px("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+k.parse(e)+"/registration",{},eq);if(await Jd(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/"+k.parse(e)+"/bound-recipients",{},Ma(JH));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await vO(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/resources/"+k.parse(e)+"/custody",{},YH);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await qo(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=SO(o);await this.trusted(n);let i=await this.trust.checkpoint(r),s=i&&zi.safeParse(i.policy).success?i:null;if(s){if(o.policy.revision<s.policy.revision||o.materialRevision<s.materialRevision||o.policy.revision===s.policy.revision&&R(o.policy)!==R(s.policy)||o.materialRevision===s.materialRevision&&await Ne(o)!==s.digest)throw new Error("The encrypted content is older than this device has already observed.");if(o.policy.revision>s.policy.revision&&!PH(s.policy,o))throw new Error("An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return EO((await this.read(e)).content,this.binding,this.keys.encryption)}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=>R(c)===R(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=>c.actor.id!==this.binding.id&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...wO(r)],origins:[],functionDigests:[],callerProgram:r!==Me.clientCredential,expiresAt:s});return zi.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&R(o)===R({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await xO(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:s,...i?{version:i.version}:{}}},no);return await this.trust.rememberContent(s),a}async pass(e,r,o,n){let i=await xO(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}},g.union([no,ja]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Ma(QH))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},no),a=await EO(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}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===Me.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Ma(no));s=d.items.find(p=>p.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,Me.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await mx(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=await this.environment(r),s=Xd.parse(o),a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=s.kind==="http"?s.request:s.kind==="function"?Tx(s.definition,s.arguments):null;if(s.kind==="http"||s.kind==="function"){let m=s.kind==="function"?s.definition.save:n.save??{};if(s.kind==="function"&&Object.keys(m).length&&s.definition.outputOwnerId!==e)throw new Error("Run this function for its approved output owner.");let h=Object.fromEntries(await Promise.all(Object.entries(m).map(async([y,w])=>[y,await this.output(e,w,a,i,c)])));s.kind==="http"?s.save=h:s.outputs=h}let l=s.kind==="command"?s.inputs.map(m=>m.source.id):u?u.bindings.flatMap(m=>m.parts.flatMap(h=>typeof h=="string"?[]:[h.id])):[],d=await this.sourceContents([...l,...n.sourceIds??[]]),p={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:i.manifest.executor,environmentDigest:await Ne(i.manifest),operation:pe[s.kind],operationDigest:await Ne(s),...n.approval?{approval:n.approval}:{},functionDigest:s.kind==="function"?await Ne(s.definition):null,sources:await Promise.all(d.map(async m=>({id:m.policy.id,materialRevision:m.materialRevision,policyDigest:await Ne(m.policy),...m.policy.contentType===Me.tokenSet&&typeof m.metadata.authorizationDigest=="string"?{authorizationDigest:m.metadata.authorizationDigest}:{}}))),resultRecipients:[this.binding],createdAt:new Date().toISOString(),expiresAt:c};await wx(i,p);let f=m=>m.policy.contentType===Me.clientCredential;for(let m of d)await zu(m,f(m)&&p.operation!==pe.connect&&p.operation!==pe.revoke?{...p,operation:pe.refresh}:p,f(m)?{}:{destination:u?.url});return OH(p,s,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/executions",{method:"POST",body:e},zn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new UO(e.intent.id)}}async resume(e){let r=await this.trust.run(k.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(R(r.intent.actor)!==R(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");return this.submitPrepared(r)}async result(e){if(R(e.intent.actor)!==R(this.binding)||e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another requester.");let r=await yO(e.requestSignature,this.binding.signing,"run");if(R(r.intent)!==R(e.intent))throw new Error("The result belongs to a different signed request.");return await this.trusted(e.intent.executor),e.receipt?MH(e.receipt,e.intent,this.binding.id,this.keys):null}};import{lstat as Phe,mkdir as Rhe,readFile as Che,readdir as Ohe}from"node:fs/promises";import{join as wq}from"node:path";var bq=g.string().regex(/^(run|process|oauth|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Lu=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return R({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:bq.parse(e)})}async read(e){let r=this.context(e),o=wq(this.directory,e+".json");try{let n=await Phe(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=g.string().max(32e6).parse(JSON.parse(await Che(o,"utf8"))),s=await Mh(i,await to(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(Ru(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await oo({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 write(e,r){let o=this.context(e),n={context:o,value:r},i=await wn(n,this.privateKeys.signing,"journal"),s=lt(R({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new Bd(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await to(this.binding.encryption,"ECDH-ES+A256KW"));await Rhe(this.directory,{recursive:!0,mode:448}),await Yd(wq(this.directory,e+".json"),R(a),!0)}async keys(e){let r;try{r=await Ohe(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=>bq.parse(o.name.slice(0,-5)))}};var Cx=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await La(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await Ne(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&R(r)!==R(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var Ct=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function U(t,e,r,o){throw new Ct(t,e,r,o)}var Ox=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 Ct(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},tq)}renew(e,r){return this.api.json("/api/executions/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}dispatch(e,r){return this.api.json("/api/executions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/executions/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},zn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},g.object({id:k}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},kx),capture:(r,o,n)=>this.capture(r,o,n),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},eg),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},eg),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},io),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}},eg),state:r=>e.json("/api/connections/"+r+"/operation",{},eg.nullable())}}};var Sne=St(Vq(),1);import{randomBytes as _ne,randomUUID as S$}from"node:crypto";function sg(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 Zo(t,e){for(let r of sg(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function WO(t,e,r){let o=sg(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function nf(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 ag(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}import{createHash as tye}from"node:crypto";var JO;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(JO="oauth4webapi/v3.8.8");function fg(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 Mi="ERR_INVALID_ARG_VALUE",Ui="ERR_INVALID_ARG_TYPE";function Ht(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var oN=Symbol(),oge=Symbol(),ige=Symbol(),iN=Symbol();var cg=Symbol();var sge=new TextEncoder,age=new TextDecoder;function GO(t){return typeof t=="string"?sge.encode(t):age.decode(t)}var XO;Uint8Array.prototype.toBase64?XO=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):XO=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 YO;Uint8Array.fromBase64?YO=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Ht("The input to be decoded is not correctly encoded.",Mi,e)}}:YO=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 Ht("The input to be decoded is not correctly encoded.",Mi,e)}};function QO(t){return typeof t=="string"?YO(t):XO(t)}var of=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Dge,Error.captureStackTrace?.(this,this.constructor)}},ug=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 he(t,e,r){return new ug(t,{code:e,cause:r})}function cge(t){return t.toLowerCase().replace(/^application\//,"")}function lg(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function sN(t){fg(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(JO&&!e.has("user-agent")&&e.set("user-agent",JO),e.has("authorization"))throw Ht('"options.headers" must not include the "authorization" header name',Mi);return e}function uge(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Ht('"options.signal" must return or be an instance of AbortSignal',Ui);return e}}function Bx(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Ht(`${r} must be a number`,Ui,n);if(t>0)return;if(e){if(t!==0)throw Ht(`${r} must be a non-negative number`,Mi,n);return}throw Ht(`${r} must be a positive number`,Mi,n)}catch(i){throw o?he(i.message,o,n):i}}function yr(t,e,r,o){try{if(typeof t!="string")throw Ht(`${e} must be a string`,Ui,o);if(t.length===0)throw Ht(`${e} must not be empty`,Mi,o)}catch(n){throw r?he(n.message,r,o):n}}function qq(t){dge(t,"application/json")}function lge(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 he(r,jge,t)}function dge(t,e){if(Xq(t)!==e)throw lge(t,e)}async function Zq(t){return yr(t,"codeVerifier"),QO(await crypto.subtle.digest("SHA-256",GO(t)))}function aN(t){let e=t?.[oge];return typeof e=="number"&&Number.isFinite(e)?e:0}function cN(t){let e=t?.[ige];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Kq(){return Math.floor(Date.now()/1e3)}function Wa(t){if(typeof t!="object"||t===null)throw Ht('"as" must be an object',Ui);yr(t.issuer,'"as.issuer"')}function Ja(t){if(typeof t!="object"||t===null)throw Ht('"client" must be an object',Ui);yr(t.client_id,'"client.client_id"')}function Bq(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 Wq(t){return yr(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function Jq(t){return yr(t,'"clientSecret"'),(e,r,o,n)=>{let i=Bq(r.client_id),s=Bq(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function Gq(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var fge=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function pge(t,e){if(e&&t.protocol!=="https:")throw he("only requests to HTTPS are allowed",Uge,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw he("only HTTP and HTTPS requests are allowed",Lge,t)}function Hq(t,e,r,o){let n;if(typeof t!="string"||!(n=fge(t)))throw he(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?Fge:Vge,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return pge(n,o),n}function uN(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Hq(t.mtls_endpoint_aliases[e],e,r,o):Hq(t[e],e,r,o)}var eN=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Nge,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)}},dg=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=zge,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)}},tN=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Oge,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Hx="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",mge="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",hge='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',gge="("+Hx+")\\s*=\\s*"+hge,yge="("+Hx+")\\s*=\\s*("+Hx+")",vge=new RegExp("^[,\\s]*("+Hx+")"),wge=new RegExp("^[,\\s]*"+gge+"[,\\s]*(.*)"),bge=new RegExp("^[,\\s]*"+yge+"[,\\s]*(.*)"),_ge=new RegExp("^("+mge+")(?:$|[,\\s])(.*)");function Sge(t){if(!fg(t,Response))throw Ht('"response" must be an instance of Response',Ui);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(vge),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(wge)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(bge)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(_ge)){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 xge(t){if(t.status>399&&t.status<500){Kx(t),qq(t);try{let e=await t.clone().json();if(lg(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function lN(t,e,r){if(t.status!==e){kge(t);let o;throw(o=await xge(t))?(await t.body?.cancel(),new eN("server responded with an error in the response body",{cause:o,response:t})):he(`"response" is not a conform ${r} response (unexpected HTTP status code)`,Mge,t)}}function Ege(t){if(!pN.has(t))throw Ht('"options.DPoP" is not a valid DPoPHandle',Mi)}function Xq(t){return t.headers.get("content-type")?.split(";")[0]}async function dN(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?.[iN]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:uge(o,s?.signal)})}async function fN(t,e,r,o,n,i){let s=uN(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[oN]!==!0);n.set("grant_type",o);let a=sN(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(Ege(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await dN(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Yq(t,e,r,o,n){Wa(t),Ja(e),yr(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),fN(t,e,r,"refresh_token",i,n)}var Qq=new WeakMap,eZ=new WeakMap;function tZ(t){if(!t.id_token)return;let e=Qq.get(t);if(!e)throw Ht('"ref" was already garbage collected or did not resolve from the proper sources',Mi);return e}async function Wx(t,e,r,o,n,i){if(Wa(t),Ja(e),!fg(r,Response))throw Ht('"response" must be an instance of Response',Ui);await lN(r,200,"Token Endpoint"),Kx(r);let s=await _Z(r);if(yr(s.access_token,'"response" body "access_token" property',Ge,{body:s}),yr(s.token_type,'"response" body "token_type" property',Ge,{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;Bx(a,!0,'"response" body "expires_in" property',Ge,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&yr(s.refresh_token,'"response" body "refresh_token" property',Ge,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw he('"response" body "scope" property must be a string',Ge,{body:s});if(s.id_token!==void 0){yr(s.id_token,'"response" body "id_token" property',Ge,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Bx(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await Age(t,e,s.id_token,a,n);Pge(e,c),Tge(c),eZ.set(r,u),Qq.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 of("unsupported `token_type` value",{cause:{body:s}});return s}function kge(t){let e;if(e=Sge(t))throw new tN("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function rZ(t,e,r,o){return Wx(t,e,r,void 0,o?.[cg],o?.recognizedTokenTypes)}function nZ(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw he('unexpected JWT "aud" (audience) claim value',sf,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw he('unexpected JWT "aud" (audience) claim value',sf,{expected:t,claims:e.claims,claim:"aud"});return e}function oZ(t,e){let r=t[Zge]?.(e)??t.issuer;if(e.claims.iss!==r)throw he('unexpected JWT "iss" (issuer) claim value',sf,{expected:r,claims:e.claims,claim:"iss"});return e}var pN=new WeakSet;function Ige(t){return pN.add(t),t}var mN=Symbol();async function iZ(t,e,r,o,n,i,s){if(Wa(t),Ja(e),!pN.has(o))throw Ht('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Mi);yr(n,'"redirectUri"');let a=Vu(o,"code");if(!a)throw he('no authorization code in "callbackParameters"',Ge);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==mN&&(yr(i,'"codeVerifier"'),c.set("code_verifier",i)),fN(t,e,r,"authorization_code",c,s)}var sZ={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 aZ(t,e){for(let r of t)if(e.claims[r]===void 0)throw he(`JWT "${r}" (${sZ[r]}) claim missing`,Ge,{claims:e.claims});return e}function $ge(t,e){if(typeof e.claims[t]!="string")throw he(`unexpected JWT "${t}" (${sZ[t]}) claim type`,Ge,{claims:e.claims});return e}function Age(t,e,r,o,n){return vZ(r,wZ.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),aN(e),cN(e),n).then(aZ.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(oZ.bind(void 0,t)).then(nZ.bind(void 0,e.client_id)).then($ge.bind(void 0,"sub"))}function cZ(t,e){if(e===Zx)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?Zx:(Bx(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function Tge(t){t.auth_time!==void 0&&Bx(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Ge,{claims:t})}function uZ(t,e,r){if(r===Zx)return;let o=Kq()+aN(t),n=cN(t);if(e.auth_time+r<o-n)throw he("too much time has elapsed since the last End-User authentication",nN,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function lZ(t,e){let r=e===qx?void 0:e;if(t.nonce!==r)throw he('unexpected ID Token "nonce" claim value',sf,{expected:r,claims:t,claim:"nonce"})}function Pge(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw he('ID Token "aud" (audience) claim includes additional untrusted audiences',sf,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw he('unexpected ID Token "azp" (authorized party) claim value',sf,{expected:t.client_id,claims:e,claim:"azp"})}}var qx=Symbol(),Zx=Symbol();async function dZ(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?Rge(t,e,r,o.expectedNonce,o.maxAge,o[cg],o.recognizedTokenTypes):Cge(t,e,r,o?.maxAge,o?.[cg],o?.recognizedTokenTypes)}async function Rge(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=qx;break;case qx:break;default:yr(o,'"expectedNonce" argument'),a.push("nonce")}n=cZ(e,n),n!==Zx&&a.push("auth_time");let c=await Wx(t,e,r,a,i,s);yr(c.id_token,'"response" body "id_token" property',Ge,{body:c});let u=tZ(c);return uZ(e,u,n),lZ(u,o),c}async function Cge(t,e,r,o,n,i){let s=await Wx(t,e,r,void 0,n,i),a=tZ(s);return a&&(uZ(e,a,cZ(e,o)),lZ(a,qx)),s}var Oge="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Nge="OAUTH_RESPONSE_BODY_ERROR",Dge="OAUTH_UNSUPPORTED_OPERATION",zge="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var rN="OAUTH_PARSE_ERROR",Ge="OAUTH_INVALID_RESPONSE";var jge="OAUTH_RESPONSE_IS_NOT_JSON",Mge="OAUTH_RESPONSE_IS_NOT_CONFORM",Uge="OAUTH_HTTP_REQUEST_FORBIDDEN",Lge="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",nN="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",sf="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var Fge="OAUTH_MISSING_SERVER_METADATA",Vge="OAUTH_INVALID_SERVER_METADATA";function Bge(t,e){if(typeof e.header.typ!="string"||cge(e.header.typ)!==t)throw he('unexpected JWT "typ" header parameter value',Ge,{header:e.header});return e}async function fZ(t,e,r,o,n){return Wa(t),Ja(e),fN(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function pZ(t,e,r,o){return Wx(t,e,r,void 0,o?.[cg],o?.recognizedTokenTypes)}async function mZ(t,e,r,o,n){Wa(t),Ja(e),yr(o,'"token"');let i=uN(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[oN]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=sN(n?.headers);return a.delete("accept"),dN(t,e,r,i,s,a,n)}async function hZ(t){if(!fg(t,Response))throw Ht('"response" must be an instance of Response',Ui);await lN(t,200,"Revocation Endpoint")}function Kx(t){if(t.bodyUsed)throw Ht('"response" body has been used already',Mi)}async function gZ(t,e,r,o,n){Wa(t),Ja(e),yr(o,'"token"');let i=uN(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[oN]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=sN(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),dN(t,e,r,i,s,a,n)}async function yZ(t,e,r,o){if(Wa(t),Ja(e),!fg(r,Response))throw Ht('"response" must be an instance of Response',Ui);await lN(r,200,"Introspection Endpoint");let n;if(Xq(r)==="application/token-introspection+jwt"){Kx(r);let{claims:i,jwt:s}=await vZ(await r.text(),wZ.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),aN(e),cN(e),o?.[cg]).then(Bge.bind(void 0,"token-introspection+jwt")).then(aZ.bind(void 0,["aud","iat","iss"])).then(oZ.bind(void 0,t)).then(nZ.bind(void 0,e.client_id));if(eZ.set(r,s),!lg(i.token_introspection))throw he('JWT "token_introspection" claim must be a JSON object',Ge,{claims:i});n=i.token_introspection}else Kx(r),n=await _Z(r);if(typeof n.active!="boolean")throw he('"response" body "active" property must be a boolean',Ge,{body:n});return n}async function vZ(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 of("JWE decryption is not configured",{cause:t});if(a!==3)throw he("Invalid JWT",Ge,t);let c;try{c=JSON.parse(GO(QO(i)))}catch(d){throw he("failed to parse JWT Header body as base64url encoded JSON",rN,d)}if(!lg(c))throw he("JWT Header must be a top level object",Ge,t);if(e(c),c.crit!==void 0)throw new of('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(GO(QO(s)))}catch(d){throw he("failed to parse JWT Payload body as base64url encoded JSON",rN,d)}if(!lg(u))throw he("JWT Payload must be a top level object",Ge,t);let l=Kq()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw he('unexpected JWT "exp" (expiration time) claim type',Ge,{claims:u});if(u.exp<=l-o)throw he('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',nN,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw he('unexpected JWT "iat" (issued at) claim type',Ge,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw he('unexpected JWT "iss" (issuer) claim type',Ge,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw he('unexpected JWT "nbf" (not before) claim type',Ge,{claims:u});if(u.nbf>l+o)throw he('unexpected JWT "nbf" (not before) claim value',nN,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw he('unexpected JWT "aud" (audience) claim type',Ge,{claims:u});return{header:c,claims:u,jwt:t}}function wZ(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw he('unexpected JWT "alg" header parameter',Ge,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw he('unexpected JWT "alg" header parameter',Ge,{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 he('unexpected JWT "alg" header parameter',Ge,{header:o,expected:r,reason:"default value"});return}throw he('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Vu(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw he(`"${e}" parameter must be provided only once`,Ge);return r}var Hge=Symbol(),qge=Symbol();function bZ(t,e,r,o){if(Wa(t),Ja(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Ht('"parameters" must be an instance of URLSearchParams, or URL',Ui);if(Vu(r,"response"))throw he('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Ge,{parameters:r});let n=Vu(r,"iss"),i=Vu(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw he('response parameter "iss" (issuer) missing',Ge,{parameters:r});if(n&&n!==t.issuer)throw he('unexpected "iss" (issuer) response parameter value',Ge,{expected:t.issuer,parameters:r});switch(o){case void 0:case qge:if(i!==void 0)throw he('unexpected "state" response parameter encountered',Ge,{expected:void 0,parameters:r});break;case Hge:break;default:if(yr(o,'"expectedState" argument'),i!==o)throw he(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Ge,{expected:o,parameters:r})}if(Vu(r,"error"))throw new dg("authorization response from the server is an error",{cause:r});let a=Vu(r,"id_token"),c=Vu(r,"token");if(a!==void 0||c!==void 0)throw new of("implicit and hybrid flows are not supported");return Ige(new URLSearchParams(r))}async function _Z(t,e=qq){let r;try{r=await t.json()}catch(o){throw e(t),he('failed to parse "response" body as JSON',rN,o)}if(!lg(r))throw he('"response" body must be a top level object',Ge,{body:r});return r}var Zge=Symbol();import{lookup as Wge}from"node:dns/promises";import{isIP as EZ}from"node:net";import{request as Jge}from"node:https";import{brotliDecompressSync as Gge,gunzipSync as Xge,inflateSync as Yge}from"node:zlib";var Gx=St(xZ(),1),Qge=Gx.default.IPv6.parseCIDR("2000::/3"),eye=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function kZ(t){if(!EZ(t)||t.includes("%"))return!1;let e=Gx.default.parse(t);return eye.has(e.range())&&(!(e instanceof Gx.default.IPv6)||e.match(Qge))}function af(t,e){let r;try{r=new URL(t)}catch{U(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)&&U(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||EZ(o)&&!kZ(o))&&U(400,"private_destination","Choose a public HTTPS destination."),r}var Xx=class{constructor(e){this.origin=e}origin;async send(e){let r=af(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&U(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))&&U(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await Wge(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!kZ(u.address)))&&U(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:(f,m,h)=>{m.all?h(null,[a]):h(null,a.address,a.family)}},p=Jge(r,d,f=>{let m=[],h=0;f.on("data",y=>{h+=y.length,h>n?f.destroy(new Ct(413,"body_limit","The response body is too large.")):m.push(y)}),f.on("error",l),f.on("end",()=>{try{let y=Buffer.concat(m),w=f.headers["content-encoding"];if(w&&w!=="identity"){let _=w==="gzip"?Xge:w==="deflate"?Yge:w==="br"?Gge:null;if(!_)throw new Ct(502,"invalid_response","The service returned an unsupported response.");y=_(y,{maxOutputLength:n})}let b={};for(let[_,x]of Object.entries(f.headers))x!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(_)&&(b[_]=Array.isArray(x)?x.join(", "):x);u({status:f.statusCode??502,headers:b,body:new Uint8Array(y)})}catch(y){l(y)}})});p.on("error",l),p.end(e.body)})}catch(s){if(s instanceof Ct)throw s;e.signal?.aborted&&U(409,"cancelled","The operation was cancelled."),U(502,"service_unavailable","The service could not be reached. Try again.")}}};function pg(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{U(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&U(502,"invalid_response","The service returned an invalid response."),e}var IZ=t=>tye("sha256").update(t).digest("hex");function cf(t,e){try{return af(new Ax(t).expand(e)).href}catch{U(400,"invalid_service_url","Check the service URL and its required fields.")}}var hN=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],gN=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&U(502,"invalid_response","The service returned an invalid expiry."),e},$Z=(t,e)=>{let r=new URL(t);return r.hostname.endsWith(".myshopify.com")&&(typeof e=="string"?r.pathname===e:e.test(r.pathname))},AZ=Object.assign(Object.create(null),{dpop:()=>U(502,"invalid_response","The service returned an unsupported token.")}),rye=Object.assign(Object.create(null),AZ,{"user access token":()=>{}}),Yx=class{constructor(e){this.transport=e}transport;appValues(e,r){return{...e.defaults,...r.fields,clientId:r.clientId}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&U(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(cf(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:e.adapter==="ebay"?r.fields.ruName:i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await Zq(n),c.code_challenge_method="S256"),e.adapter==="openrouter"&&(delete c.response_type,delete c.client_id,delete c.redirect_uri,c.callback_url=i,c.key_label="Foundation");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(cf(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:cf(e.tokenUrl,this.appValues(e,r))};return e.issuer&&af(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?Gq():(e.clientSecret||U(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?Jq(e.clientSecret):Wq(e.clientSecret))}options(e="form"){return{[iN]:async(r,{body:o,headers:n,method:i,signal:s})=>{let a=await this.transport.send({url:r,method:i,headers:e==="json"?{...n,"content-type":"application/json"}:n,body:e==="json"?JSON.stringify(Object.fromEntries(o)):o.toString(),signal:s});return new Response([204,205,304].includes(a.status)?null:new Uint8Array(a.body),{status:a.status,headers:a.headers})}}}async json(e){return pg({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&Zo(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&U(409,"reconnect_required","Reconnect this service to renew access."),r===429&&U(503,"service_rate_limit","The service is busy. Try again later."),U(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&U(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,c.hostname.endsWith(".myshopify.com")&&c.pathname==="/admin/oauth/access_token"&&u.token_type===void 0&&(u.token_type="bearer"),c.hostname==="api.notion.com"&&c.pathname==="/v1/oauth/token"&&u.refresh_token===null&&delete u.refresh_token,u.expires_in!==void 0&&(u.expires_in=gN(u.expires_in));try{let d=await(n?rZ:e.grantType==="client_credentials"?pZ:dZ)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:e.adapter==="ebay"?rye:AZ});return{...i,...d}}catch(l){if(l instanceof Ct)throw l;U(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=e.adapter==="openrouter"?r.key:r.access_token;(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&U(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+gN(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&U(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?hN(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()+gN(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"&&U(400,"wrong_grant","This connection exchanges application credentials directly.");let u;if(e.adapter==="openrouter"){let p=o.parameters;(p.getAll("state").length!==1||p.get("state")!==o.state||p.getAll("code").length!==1||!p.get("code"))&&U(400,"invalid_state","Start the connection again.");let f=await this.transport.send({url:cf(e.tokenUrl,this.appValues(e,r)),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:p.get("code"),code_verifier:n,code_challenge_method:"S256"})});u=this.checkResponse(e,f.status,pg(f))}else{let{server:p,client:f}=this.configuration(e,r),m;try{let h=bZ(p,f,o.parameters,o.state);m=await iZ(p,f,this.authentication(r,e.clientAuth),h,e.adapter==="ebay"?r.fields.ruName:i,e.pkce?n:mN,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(h){throw(h instanceof ug||h instanceof dg)&&U(400,"invalid_state","Start the connection again."),h}u=await this.tokenResponse(e,r,m)}let l=this.token(e,u,s,a);await c?.(l,u);let d=await this.inspect(e,r,l,u);return a&&d.account!==a.account&&e.adapter!=="openrouter"&&U(409,"account_changed","Reconnect using the same service account."),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&U(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=$Z(s.token_endpoint,"/admin/oauth/access_token"),u=await fZ(s,a,this.authentication(r,e.clientAuth),{...e.tokenParams,...o.length&&!c?{scope:o.join(e.scopes.separator)}:{}},this.options(e.tokenFormat)),l=await this.tokenResponse(e,r,u),d={...this.token(e,l,o,n,!!n),requestedScopes:o};await i?.(d,l);let p=await this.inspect(e,r,d,l);return n&&p.account!==n.account&&U(409,"account_changed","Reconnect using the same service account."),p}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return this.clientCredentials(e,r,o.requestedScopes??e.scopes.default,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&U(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await Yq(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e.tokenFormat),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(e.identity?.url||e.adapter==="ebay"||e.adapter==="openrouter")&&(i=await this.inspect(e,r,i)),i.account!==o.account&&U(409,"account_changed","Reconnect using the same service account."),i}async inspect(e,r,o,n){let i=n??{};if(e.adapter==="ebay"){let{server:u,client:l}=this.configuration(e,r),d=await gZ({...u,introspection_endpoint:u.token_endpoint+"/introspect"},l,this.authentication(r,"basic"),o.accessToken,{...this.options(),additionalParameters:{token_type_hint:"access_token"}});try{i=await yZ(u,l,Response.json(await this.json(d),{status:d.status}))}catch{U(409,"reconnect_required","Reconnect this service to renew access.")}return(i.active!==!0||i.client_id!==r.clientId||typeof i.sub!="string"||!i.sub||typeof i.exp!="number"||i.exp*1e3<=Date.now())&&U(409,"reconnect_required","Reconnect this service to renew access."),{...o,account:i.sub,accountName:typeof i.username=="string"?i.username:i.sub,scopes:hN(i.scope),scopesStatus:"reported",accountVerified:!0,expiresAt:Math.min(o.expiresAt??1/0,i.exp*1e3)}}if(e.adapter==="openrouter"){let u=await this.transport.send({url:"https://openrouter.ai/api/v1/key",headers:{authorization:"Bearer "+o.accessToken}});i=pg(u),(u.status!==200||!i.data||typeof i.data!="object")&&U(409,"reconnect_required","Reconnect this service to renew access.");let l=i.data;return{...o,account:IZ(o.accessToken),accountName:typeof l.label=="string"?l.label:"OpenRouter",facts:l}}if(e.identity?.url){let u=cf(e.identity.url,{...this.appValues(e,r),...o.extra,accessToken:o.accessToken,refreshToken:o.refreshToken??""}),l=e.grantType==="client_credentials"&&$Z(u,/^\/admin\/api\/[^/]+\/graphql\.json$/),d=await this.transport.send({url:u,method:e.identity.method,headers:l?{...e.identity.headers,"content-type":"application/json","X-Shopify-Access-Token":o.accessToken}:{...e.identity.headers,authorization:"Bearer "+o.accessToken},...l?{body:JSON.stringify({query:"{ shop { id name myshopifyDomain } }"})}:{}});i=pg(d),(d.status===401||d.status===403)&&U(409,"reconnect_required","Reconnect this service to renew access."),d.status>=400&&U(502,"invalid_response","The service account could not be verified."),l&&((Array.isArray(i.errors)?i.errors.length:i.errors)||Zo(i,"/data/shop/myshopifyDomain")!==r.fields.shop+".myshopify.com")&&U(502,"invalid_response","The Shopify store could not be verified."),e.adapter==="github"&&d.headers["x-oauth-scopes"]!==void 0&&(o.scopes=hN(d.headers["x-oauth-scopes"].replaceAll(","," ")),o.scopesStatus="reported"),e.adapter==="google"&&i.email_verified!==!0&&U(502,"invalid_response","The service account could not be verified.")}else e.identity?.from==="app"&&(i=this.appValues(e,r));let s=u=>{for(let l of Array.isArray(u)?u:[u]){let d=Zo(i,l);if(typeof d=="string"&&d||typeof d=="number")return String(d)}return""},a=e.identity?.id,c=a?Array.isArray(a)?a.map(u=>s(u)).filter(Boolean).join(":"):s(a):o.account||r.fields.domain||r.fields.shop||IZ(o.accessToken);return(!c||c.length>1e3)&&U(502,"invalid_response","The service account could not be verified."),{...o,account:c,accountName:e.identity&&s(e.identity.name)||c,accountVerified:!!(e.identity?.url||e.identity?.from==="token"&&n)}}async revoke(e,r,o){e.revoke||U(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=cf(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:u,client:l}=this.configuration(e,r),d=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),p=await mZ({...u,revocation_endpoint:n},l,d,o.refreshToken??o.accessToken,this.options());try{await hZ(p)}catch{U(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:(s==="basic"||e.revoke.style==="github")&&(i.authorization="Basic "+Buffer.from(r.clientId+":"+(r.clientSecret??"")).toString("base64"));let a;e.revoke.style==="github"&&(i["content-type"]="application/json",a=JSON.stringify({access_token:o.accessToken})),(await this.transport.send({url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i,...a?{body:a}:{}})).status>=300&&U(502,"revoke_failed","Access could not be removed at the service. Try again.")}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,nf(Zo(n,s))]))}};function Gs(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Qx(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(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=lt(nf(Zo(JSON.parse(Gs(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Gs(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}}function nye(t,e){return t.policy.contentType===Me.value?e.output===void 0:t.policy.contentType===Me.tokenSet&&e.output!==void 0}var Li=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},e0=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Gd(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Gd(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await Ne(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let p=await Gd(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:p,delivered:!1}),await this.broker.finish(r.lease,p),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(p=>{p.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let p=await NH(r.request,this.binding,this.keys);await wx(this.environment,p.intent);let f=Xd.parse(p.operation);if(pe[f.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await this.preflight(f,o,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.execute(f,o,r.sources,c);d=await Gd(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(p){if(p instanceof Li)throw p;p instanceof Jh&&(p=new Ct(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let f=l&&(c.aborted||!(p instanceof Ct)||["service_unavailable","connection_uncertain","lease_lost"].includes(p.code));d=await Gd(o,f?"uncertain":"failed",{ok:!1,result:null,error:p instanceof Ct?{code:p.code,message:p.message}:{code:f?"execution_uncertain":"invalid_execution",message:f?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){return e.kind==="http"?e.request:e.kind==="function"?Tx(e.definition,e.arguments):null}async preflight(e,r,o){if(new Set(o.map(s=>s.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let s of o){await qo(s);let a=r.sources.find(u=>u.id===s.policy.id);if(!a||!await kO(s,a))throw new Error("An execution input changed.");let c=await this.journal.read("checkpoint_"+s.policy.id);if(c&&(s.policy.revision<c.policy||s.materialRevision<c.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write("checkpoint_"+s.policy.id,{policy:s.policy.revision,material:s.materialRevision})}if(e.kind==="function"&&await Ne(e.definition)!==r.functionDigest)throw new Error("Run the exact function authorized by this intent.");let n=this.request(e);if(n){if(af(n.url,r.origin),[n.body,n.json,n.form].filter(a=>a!==void 0).length>1)throw new Error("Choose one request body format.");for(let a of n.bindings){let c=sg(a.pointer);if(!c.length||!["headers","body","json","form"].includes(c[0])||c[0]==="body"&&c.length!==1||["headers","form"].includes(c[0])&&c.length!==2)throw new Error("Bind credentials to request headers or the body.");WO(structuredClone(n),a.pointer,"validation")}let s=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};if(e.kind==="function"&&(Object.keys(s).length!==Object.keys(e.definition.save).length||Object.entries(e.definition.save).some(([a,c])=>s[a]?.name!==c)))throw new Error("Use the output destinations declared by this function.");for(let[a,c]of Object.entries(s)){if(sg(a),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let u=await Wd(c.approval);if(R(u.policy.authorities.find(l=>l.id===u.authorityId))!==R(r.actor)||u.policy.origin!==r.origin||u.policy.contentType!==Me.value||u.policy.ownerId!==r.ownerId||e.kind==="function"&&e.definition.outputOwnerId!==u.policy.ownerId||!u.policy.producers.some(l=>l.runId===r.id&&R(l.executor)===R(this.binding)&&Date.parse(l.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}}let i=e.kind==="command"?e.inputs.map(s=>s.source):n?n.bindings.flatMap(s=>s.parts.filter(a=>typeof a!="string")):[];for(let s of i){let a=o.find(c=>c.policy.id===s.id);if(!a||!nye(a,s))throw new Error("Use the input named in the signed request.");await zu(a,r,{...n?{destination:n.url}:{}}),await Fa(a,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async execute(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=[],a=new Map,c=async f=>{let m=o.find(y=>y.policy.id===f.id);if(m.policy.contentType===Me.value)return Fa(m,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");a.has(f.id)||a.set(f.id,this.extension.outputs(m,r,o,n,i?.url));let h=await a.get(f.id);if(!f.output||!Object.hasOwn(h,f.output))throw new Error("Choose an available connection output.");return lt(h[f.output])};if(e.kind==="command"){let f=await Qx(e.inputs,c),m=await this.commands.execute({command:e.command,timeoutSeconds:e.timeoutSeconds,...e.stdin===void 0?{}:{stdin:e.stdin},environment:f.environment,files:f.files},n);return{...m,stdout:ag(m.stdout,f.sensitive),stderr:ag(m.stderr,f.sensitive)}}let u=structuredClone(i);for(let f of u.bindings){let m="";for(let h of f.parts)if(typeof h=="string")m+=h;else{let y=Gs(await c(h));s.push(y,Buffer.from(y).toString("base64"),Buffer.from(y).toString("base64url")),m+=y}WO(u,f.pointer,m)}let l=u.body;u.json!==void 0&&(l=JSON.stringify(u.json),u.headers["content-type"]="application/json"),u.form!==void 0&&(l=new URLSearchParams(u.form).toString(),u.headers["content-type"]="application/x-www-form-urlencoded");let d=await this.transport.send({url:u.url,method:u.method,headers:u.headers,...l===void 0?{}:{body:l},signal:n}),p=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};if(Object.keys(p).length){if(d.status>=400)throw new Ct(502,"service_response","The service returned an unsuccessful response.");let f={};for(let[m,h]of Object.entries(p)){let y=d.body;if(m!==""){let b=Zo(JSON.parse(Gs(y)),m);if(b===void 0)throw new Ct(400,"invalid_pointer","The response value was not found.");y=lt(typeof b=="string"?b:JSON.stringify(b))}let w=await hx(y,h.approval,r.id,this.binding,this.keys,{bytes:y.length});f[h.name]=(await this.broker.capture(h.name,w)).id}return{status:d.status,saved:f}}return{status:d.status,headers:Object.fromEntries(Object.entries(d.headers).map(([f,m])=>[f,ag(m,s)])),body:ag(Gs(d.body),s)}}};var ua=St(wne(),1);import{randomUUID as SAe}from"node:crypto";function xAe(t){let e=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(t);return e?`arn:${e[1]}:iam::${e[2]}:role/${e[3]}`:/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/.+$/.test(t)?t:null}async function bne(t=3e3){let e=new ua.STSClient({region:process.env.AWS_REGION||"us-east-1"});try{let r=await e.send(new ua.GetCallerIdentityCommand({}),{abortSignal:AbortSignal.timeout(t)});return r.Arn?xAe(r.Arn):null}catch{return null}finally{e.destroy()}}var _$=class{async obtain(e,r,o){let n=new ua.STSClient({region:o});try{let s=(await n.send(new ua.AssumeRoleCommand({RoleArn:e,RoleSessionName:"foundation-"+SAe().slice(0,8),ExternalId:r,DurationSeconds:3600}))).Credentials;(!s?.AccessKeyId||!s.SecretAccessKey||!s.SessionToken)&&U(502,"invalid_response","AWS did not return credentials.");let a=new ua.STSClient({region:o,credentials:{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken}});try{(await a.send(new ua.GetCallerIdentityCommand({}))).Account!==e.split(":")[4]&&U(502,"account_changed","The AWS account could not be verified.")}finally{a.destroy()}return{AWS_ACCESS_KEY_ID:s.AccessKeyId,AWS_SECRET_ACCESS_KEY:s.SecretAccessKey,AWS_SESSION_TOKEN:s.SessionToken,AWS_DEFAULT_REGION:o}}catch(i){if(i instanceof Ct)throw i;U(502,"role_denied","Check the IAM role and its trust policy for this executor.")}finally{n.destroy()}}};function A4(t,e){if(t.kind==="role")return{};let r=t.config.fields,o={...t.kind==="oauth"?t.config.defaults:{},...e};for(let n of r)n.required!==!1&&!o[n.name]&&U(400,"missing_field","Complete the required service fields."),o[n.name]?.includes("\0")&&U(400,"invalid_field","Check the service fields."),n.pattern&&(n.pattern.length>200||!(0,Sne.default)(n.pattern))&&U(400,"invalid_pattern","Use a simple field validation pattern."),n.pattern&&o[n.name]&&!new RegExp(n.pattern,"u").test(o[n.name].slice(0,1e3))&&U(400,"invalid_field","Check the service fields.");return Object.keys(e).some(n=>!r.some(i=>i.name===n))&&U(400,"invalid_field","Remove unrecognized service fields."),o}var Cp=class{constructor(e,r,o,n,i,s=new _$){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.roles=s}binding;keys;broker;journal;transport;roles;active=new Set;oauth(e){return new Yx({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||U(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=qs.parse(JSON.parse(Gs(await Fa(e,r,this.keys,{destination:o}))));return(await Mu(n)).authorizationDigest!==e.metadata.authorizationDigest&&U(409,"connection_changed","Approve the current service account and permissions before using this connection."),n.state==="reconnect"&&r.operation!==pe.revoke&&U(409,"reconnect_required","Reconnect this service before using it."),n}async app(e,r,o,n){let i=this.source(e,Me.clientCredential,n),s=Ha.parse(JSON.parse(Gs(await Fa(i,o,this.keys))));return s.methodId!==r&&U(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(!ju(e.method))return Ha.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===pe.revoke?pe.revoke:pe.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&U(409,"app_changed","Reconnect this service with the current application."),i}async flow(e,r){let o=await this.journal.read("oauth_"+e);return(!o||o.expiresAt<=Date.now()||R(o.actor)!==R(r.actor)||o.ownerId!==r.ownerId)&&U(409,"connection_expired","Start the connection again."),o}async validate(e,r,o){let n=Ex.parse(e),i=pe[n.action==="refresh"||n.action==="revoke"?n.action:"connect"];if(r.operation!==i&&U(400,"wrong_operation","Use the approved connection operation."),n.action==="start")if(n.method.kind==="oauth"){if(ju(n.method)&&!n.appId&&U(400,"app_required","Choose an OAuth application."),n.method.config.grantType!=="client_credentials"){n.redirectUri||U(400,"invalid_redirect","Choose a callback URL.");let a=new URL(n.redirectUri);(a.username||a.password||a.hash||a.search||!(n.redirectUri===r.origin+"/oauth/callback"||a.protocol==="http:"&&["127.0.0.1","[::1]"].includes(a.hostname)))&&U(400,"invalid_redirect","Use the Foundation callback or a callback on this computer.")}let s=n.appId?await this.app(n.appId,n.methodId,r,o):Ha.parse({format:1,methodId:n.methodId,generation:n.flowId,clientId:"",fields:{}});A4(n.method,s.fields),ju(n.method)&&n.method.config.clientAuth!=="none"&&!s.clientSecret&&U(409,"app_required","Add a client secret to this OAuth application.")}else n.method.kind==="token"?A4(n.method,n.fields):n.role||U(400,"role_required","Choose a role trusted for this executor.");else if(n.action==="commit"){let s=await this.flow(n.flowId,r),a=await Wd(n.approval);(!s.material||n.authorizationDigest!==(await Mu(s.material)).authorizationDigest||a.policy.contentType!==Me.tokenSet||a.policy.ownerId!==r.ownerId||a.policy.origin!==r.origin||R(a.policy.authorities.find(c=>c.id===a.authorityId))!==R(r.actor)||!a.policy.producers.some(c=>c.runId===r.id&&R(c.executor)===R(this.binding)&&Date.parse(c.expiresAt)>Date.now()))&&U(403,"approval_required","Review the connection and approve its recipients before saving.")}else if(n.action==="exchange"){let s=await this.flow(n.flowId,r);if(s.app&&s.input.appId){let a=await this.app(s.input.appId,s.input.methodId,r,o);R(a)!==R(s.app)&&U(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,Me.tokenSet,o),a=await this.material(s,r);a.method.kind==="oauth"&&await this.connectionApp(a,r,o)}}async execute(e,r,o,n){let i=Ex.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&U(409,"connection_busy","Another operation is updating this connection."),this.active.add(s);try{if(n.throwIfAborted(),i.action==="start")return await this.start(i,r,o,n);if(i.action==="exchange")return await this.exchange(i,r,n);if(i.action==="commit")return await this.commit(i,r);let a=this.source(i.id,Me.tokenSet,o),c=await this.material(a,r);if(i.action==="refresh"){let u=c.method.kind==="oauth"?await this.refresh(a,c,r,o,n):c;return{kind:"refreshed",id:a.policy.id,...await Mu(u)}}return c.method.kind!=="oauth"&&U(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await this.oauth(n).revoke(c.method.config,await this.connectionApp(c,r,o),c.oauth),{kind:"revoked",id:a.policy.id}}finally{this.active.delete(s)}}async review(e,r){return{kind:"review",flowId:e,name:r.input.name,metadata:{...await Mu(r.material),...xx(r.material)}}}async start(e,r,o,n){let i="oauth_"+e.flowId;await this.journal.read(i)&&U(409,"flow_exists","Use a new connection request.");let s={actor:r.actor,ownerId:r.ownerId,input:e,app:e.method.kind!=="oauth"?null:e.appId?await this.app(e.appId,e.methodId,r,o):Ha.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}}),state:_ne(32).toString("base64url"),verifier:_ne(32).toString("base64url"),expiresAt:Math.min(Date.now()+6e5,Date.parse(r.expiresAt)),phase:e.method.kind==="oauth"?"authorize":"review"};if(e.method.kind!=="oauth"&&(e.method.kind==="role"&&await this.roles.obtain(e.role.arn,e.role.externalId,e.role.region),s.material=qs.parse({format:1,methodId:e.methodId,method:e.method,generation:S$(),appId:null,appGeneration:null,...e.method.kind==="role"?{role:e.role}:{fields:A4(e.method,e.fields)}})),await this.journal.write(i,s),e.method.kind!=="oauth")return this.review(e.flowId,s);let a=[...new Set([...e.method.config.scopes.default,...e.scopes])];if(e.method.config.grantType==="client_credentials"){s.phase="exchanging",await this.journal.write(i,s);let c=await this.oauth(n).clientCredentials(e.method.config,s.app,a,void 0,async(u,l)=>{s.checkpoint={token:u,response:l},s.phase="received",await this.journal.write(i,s)});return s.material=qs.parse({format:1,methodId:e.methodId,method:e.method,generation:S$(),appId:e.appId,appGeneration:s.app.generation,oauth:c}),s.phase="review",await this.journal.write(i,s),this.review(e.flowId,s)}return e.redirectUri===r.origin+"/oauth/callback"&&await this.broker.relay?.({id:e.flowId,runId:r.id,stateDigest:await Ne(s.state),expiresAt:new Date(s.expiresAt).toISOString()}),{kind:"authorize",flowId:e.flowId,url:await this.oauth().authorize(e.method.config,s.app,s.state,s.verifier,e.redirectUri,a)}}async exchange(e,r,o){let n=await this.flow(e.flowId,r),i="oauth_"+e.flowId;if(n.phase==="review")return this.review(e.flowId,n);(n.input.method.kind!=="oauth"||!n.app||!["authorize","received"].includes(n.phase))&&U(409,"connection_uncertain","Check the connection before authorizing it again.");let s=this.oauth(o),a=n.input.method.config,c=new URLSearchParams(e.parameters);(c.getAll("state").length!==1||c.get("state")!==n.state)&&U(400,"invalid_state","Start the connection again.");let u;return n.phase==="received"?u=await s.inspect(a,n.app,n.checkpoint.token,n.checkpoint.response):(n.phase="exchanging",await this.journal.write(i,n),u=await s.exchange(a,n.app,{parameters:c,state:n.state},n.verifier,n.input.redirectUri,[...new Set([...a.scopes.default,...n.input.scopes])],void 0,async(l,d)=>{n.checkpoint={token:l,response:d},n.phase="received",await this.journal.write(i,n)})),n.material=qs.parse({format:1,methodId:n.input.methodId,method:n.input.method,generation:S$(),appId:n.input.appId,appGeneration:n.input.appId?n.app.generation:null,oauth:u}),n.phase="review",await this.journal.write(i,n),this.review(e.flowId,n)}async commit(e,r){let o=await this.flow(e.flowId,r),n="oauth_"+e.flowId;if(o.phase==="committed")return{kind:"connected",id:o.content.policy.id};["review","committing"].includes(o.phase)||U(409,"approval_required","Review this connection before saving."),o.content?(R(o.content.policy)!==R(e.approval.policy)||o.content.creationRunId!==r.id)&&U(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await hx(lt(R(o.material)),e.approval,r.id,this.binding,this.keys,await Mu(o.material)),o.phase="committing",await this.journal.write(n,o));let i;try{i=await this.broker.capture(o.input.name,o.content,xx(o.material))}catch(s){throw s instanceof Ct&&s.status<500?s:new Li}return o.phase="committed",await this.journal.write(n,o),{kind:"connected",id:i.id}}async recover(e,r){let o=Ex.parse(e);if(o.action!=="commit")return null;let n="oauth_"+o.flowId,i=await this.journal.read(n);if(!i?.content||i.ownerId!==r.ownerId||R(i.actor)!==R(r.actor)||i.content.creationRunId!==r.id||R(i.content.policy)!==R(o.approval.policy)||!["committing","committed"].includes(i.phase))return null;try{await this.broker.capture(i.input.name,i.content,xx(i.material))}catch(s){if(s instanceof Ct&&s.status<500)return null;throw new Li}return i.phase="committed",await this.journal.write(n,i),{kind:"connected",id:i.content.policy.id}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);if(s.method.kind==="token")return Object.fromEntries(Object.entries(s.method.config.outputs).map(([a,c])=>[a,nf(Zo(s.fields,c))]));if(s.method.kind==="role")return this.roles.obtain(s.role.arn,s.role.externalId,s.role.region);if(await this.broker.state(e.policy.id)&&U(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),s.method.kind!=="oauth")throw new Error("Use an OAuth connection.");return this.oauth(n).outputs(s.method.config,await this.connectionApp(s,r,o),s.oauth)}async refreshed(e,r){let o=qs.parse({...e.material,oauth:r}),n=await Mu(o);return n.authorizationDigest!==e.previous.metadata.authorizationDigest&&U(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=o,e.content=await CH(e.previous,lt(R(o)),this.binding,this.keys,n),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),o}async refresh(e,r,o,n,i,s){if(r.method.kind!=="oauth"||r.oauth.expiresAt===null||r.oauth.expiresAt>=Date.now()+6e4)return r;try{await zu(e,{...o,operation:pe.refresh},{destination:s})}catch{U(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let a=await this.connectionApp(r,o,n),c=S$(),u=await this.broker.prepare(c,e.policy.id,e.materialRevision),l={operation:u,previous:e,material:r,app:a,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+c,l);try{i.throwIfAborted(),l.phase="dispatched",await this.journal.write("refresh_"+c,l),await this.broker.dispatch(c,u.fence),i.throwIfAborted();let d=await this.oauth(i).refresh(r.method.config,a,r.oauth,async(p,f)=>{l.checkpoint={token:p,response:f},l.phase="received",await this.journal.write("refresh_"+c,l)});return await this.refreshed(l,d)}catch(d){if(l.phase==="prepared"?await this.broker.abort(c,u.fence):await this.broker.uncertain(c,u.fence).catch(()=>{}),d instanceof Ct&&["connection_review","reconnect_required","account_changed"].includes(d.code))throw d;U(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("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&&o.material.method.kind==="oauth"){let i=await this.oauth().inspect(o.material.method.config,o.app,o.checkpoint.token,o.checkpoint.response);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}};function Hr(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=T4(EAe(Hs()),"custody",r.id),i=new Lu(T4(n,"client"),o,r,e),s=new Rx(t,o,r,e,new Cx(i)),a=new Ox(t),c=new Xx(o),u=new Cp(r,e,a.connections(),new Lu(T4(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 xne(t,e){let{custody:r,keys:o,binding:n,connections:i}=Hr(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 Ne(n),operation:pe.command,functionDigest:null,operationDigest:await Ne(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await Ne(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===Me.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Qx(e,async u=>{let l=s.find(p=>p.policy.id===u.id);if(l.policy.contentType===Me.value)return Fa(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 lt(d[u.output])})}import{mkdir as $Ae}from"node:fs/promises";import{join as O4}from"node:path";import{setTimeout as AAe}from"node:timers/promises";import{spawn as kAe}from"node:child_process";import{constants as P4}from"node:fs";import{open as Ene,rm as IAe}from"node:fs/promises";async function kne(t){if(process.platform!=="linux"){let r=await Ene(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await IAe(t,{force:!0})}}let e=await Ene(t,P4.O_CREAT|P4.O_WRONLY|P4.O_NOFOLLOW,384);try{let r=kAe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var R4=g.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),C4=R4.max(4096).startsWith("/"),Ine=g.object({command:g.array(R4.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:C4.optional(),environment:g.record(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),R4.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:g.string().max(1e6).default(""),timeoutSeconds:g.number().int().min(1).max(3600).default(60)}).strict(),$pt=Ine.extend({id:k.optional()}),$ne=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),Ane=g.object({exitCode:g.number().int().nullable(),signal:g.string().max(32).nullable(),stdout:g.string().max(1e6),stderr:g.string().max(1e6),timedOut:g.boolean(),truncated:g.boolean()}).strict(),Apt=g.object({state:$ne.exclude(["queued","running"]),result:Ane.nullable(),error:g.string().max(100).nullable()}).strict(),x$=Ine.extend({id:k,environmentId:k,ownerId:k,actorId:k,workingDirectory:C4,state:$ne,result:Ane.nullable(),error:g.string().nullable(),createdAt:Be,startedAt:Be.nullable(),finishedAt:Be.nullable()}).strict(),Tpt=x$.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),Ppt=g.object({workingDirectory:C4}).strict(),Tne=g.object({lease:k,process:x$}).strict().nullable();var E$=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},Tne)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},x$)}},k$=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Li}return!0}};async function I$(t,e){let{directory:r,keys:o,binding:n,broker:i,transport:s}=Hr(t),a=k.parse(e.id??crypto.randomUUID()),c=O4(r,"executors",a);await $Ae(c,{recursive:!0,mode:448});let u=await kne(O4(c,"process.lock")),l=new AbortController,d=()=>l.abort();process.on("SIGINT",d),process.on("SIGTERM",d);try{let p=new Lu(c,t.identity.origin,n,o),f=await p.read("environment_"+a),m=await bne();if(f){if(await Jd(f),f.manifest.ownerId!==e.ownerId||R(f.manifest.executor)!==R(n))throw new Error("Use the owner and identity originally registered for this executor.");if((f.manifest.awsPrincipal??null)!==m){let{awsPrincipal:_,...x}=f.manifest;f=await $O({...x,...m?{awsPrincipal:m}:{},revision:x.revision+1},o),await p.write("environment_"+a,f)}}else f=await $O({format:3,id:a,origin:t.identity.origin,ownerId:e.ownerId,name:e.name,executor:n,operatorId:n.principalId,driver:e.managed?"managed":"attached",capabilities:Object.values(pe),isolation:e.isolation,...e.image?{commandImage:e.image}:{},...m?{awsPrincipal:m}:{},revision:1},o),await p.write("environment_"+a,f);await t.json("/api/environments/"+a+"/registration",{method:"PUT",body:f}),process.stdout.write(JSON.stringify({environmentId:a,identityId:n.principalId,fingerprint:await Ou(n),isolation:f.manifest.isolation,...f.manifest.awsPrincipal?{awsPrincipal:f.manifest.awsPrincipal}:{},...f.manifest.isolation==="process"?{notice:"Only allow trusted code on this host."}:{}})+`
131
131
  `);let h=new Cp(n,o,i.connections(),p,s),y=new e0(f,o,i,p,s,new Qh({isolation:f.manifest.isolation,image:f.manifest.commandImage}),h),w=f.manifest.isolation==="container"?"/workspace":process.cwd();await t.json("/api/environments/"+a+"/processes/registration",{method:"PUT",body:{workingDirectory:w}});let b=new k$(a,new E$(t),p,new Qh({isolation:f.manifest.isolation,image:f.manifest.commandImage,workspace:O4(c,"workspace")}));do{let _=[...await h.reconcile(),...await y.reconcile(),...await b.reconcile()];_.length&&process.stderr.write(JSON.stringify({event:"reconciliation_pending",ids:_})+`
132
132
  `);let x=!1;try{x=await y.tick(l.signal),x=await b.tick(l.signal)||x}catch($){if(!($ instanceof Li)||e.once)throw $}if(e.once)break;x||await AAe(1e3,void 0,{signal:l.signal})}while(!l.signal.aborted)}catch(p){if(!l.signal.aborted)throw p}finally{process.off("SIGINT",d),process.off("SIGTERM",d),await u()}return 0}import{randomBytes as TAe}from"node:crypto";import{execFile as PAe}from"node:child_process";import{promisify as RAe}from"node:util";import{lstat as CAe}from"node:fs/promises";async function Pne(){let t=process.env.FOUNDATION_EXECUTOR_BOOTSTRAP;if(!t)throw new Error("The executor enrollment is missing.");let e=XH.parse(JSON.parse(Buffer.from(t,"base64url").toString("utf8")));e.origin=Ba(e.origin),delete process.env.FOUNDATION_EXECUTOR_BOOTSTRAP;let r=!1;try{await CAe(Hs()),r=!0}catch(c){if(!(c instanceof Error&&"code"in c&&c.code==="ENOENT"))throw c}if(!r){let c=await ux(),u=lx(e.executorId,c);await Xh({origin:e.origin,principalId:e.executorId,token:"fk_"+TAe(32).toString("base64url"),keys:c,binding:u})}let o=await bx(e.origin),n=new Bs(o);if(o.principalId!==e.executorId||!o.keys||!o.binding)throw new Error("The saved keys belong to another executor.");if(!(await n.session().catch(async c=>{if(!(c instanceof Va)||c.status!==401)throw c;return await OAe(e,n),n.session()})).principal)throw new Error("The executor credential is no longer active.");let s=RAe(PAe),a=Qd();try{await s("docker",["image","inspect",e.commandImage],{env:a})}catch{await s("docker",["pull",e.commandImage],{env:a,timeout:3e5,maxBuffer:2e6})}return I$(n,{id:e.id,ownerId:e.ownerId,name:e.name,isolation:"container",image:e.commandImage,managed:!0})}async function OAe(t,e){let{keys:r,binding:o,token:n}=e.identity;if(!r||!o)throw new Error("Create executor keys before enrollment.");if(!(await fetch(t.origin+"/api/environments/"+t.id+"/enroll",{method:"POST",redirect:"error",signal:AbortSignal.timeout(3e4),headers:{"content-type":"application/json"},body:JSON.stringify({bootstrap:t.bootstrap,token:n,binding:await Kh(o,r)})})).ok)throw new Error("The executor could not enroll. Keep its saved keys and check the environment status.")}var je;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let s of n)i[s]=s;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),s={};for(let a of i)s[a]=n[a];return t.objectValues(s)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&i.push(s);return i},t.find=(n,i)=>{for(let s of n)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,i=" | "){return n.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=o,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(je||(je={}));var Rne;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Rne||(Rne={}));var q=je.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),la=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}};var N=je.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var Wn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},o={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(n);else if(s.code==="invalid_return_type")n(s.returnTypeError);else if(s.code==="invalid_arguments")n(s.argumentsError);else if(s.path.length===0)o._errors.push(r(s));else{let a=o,c=0;for(;c<s.path.length;){let u=s.path[c],l=c===s.path.length-1;if(u==="_errors"){l&&a._errors.push(r(s)),c++;continue}Object.prototype.hasOwnProperty.call(a,u)||(u==="__proto__"?Object.defineProperty(a,u,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):a[u]={_errors:[]}),a=a[u],l&&a._errors.push(r(s)),c++}}};return n(this),o}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,je.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r=Object.create(null),o=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else o.push(e(n));return{formErrors:o,fieldErrors:r}}get formErrors(){return this.flatten()}};Wn.create=t=>new Wn(t);var NAe=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,je.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${je.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${je.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${je.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:je.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,je.assertNever(t)}return{message:r}},Fc=NAe;var DAe=Fc;function vv(){return DAe}var $$=t=>{let{data:e,path:r,errorMaps:o,issueData:n}=t,i=[...r,...n.path||[]],s={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",c=o.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:e,defaultError:a}).message;return{...n,path:i,message:a}};function F(t,e){let r=vv(),o=$$({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Fc?void 0:Fc].filter(n=>!!n)});t.common.issues.push(o)}var qr=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let o=[];for(let n of r){if(n.status==="aborted")return oe;n.status==="dirty"&&e.dirty(),o.push(n.value)}return{status:e.value,value:o}}static async mergeObjectAsync(e,r){let o=[];for(let n of r){let i=await n.key,s=await n.value;o.push({key:i,value:s})}return t.mergeObjectSync(e,o)}static mergeObjectSync(e,r){let o={};for(let n of r){let{key:i,value:s}=n;if(i.status==="aborted"||s.status==="aborted")return oe;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||n.alwaysSet)&&(o[i.value]=s.value)}return{status:e.value,value:o}}},oe=Object.freeze({status:"aborted"}),Op=t=>({status:"dirty",value:t}),cn=t=>({status:"valid",value:t}),N4=t=>t.status==="aborted",D4=t=>t.status==="dirty",xl=t=>t.status==="valid",wv=t=>typeof Promise<"u"&&t instanceof Promise;var W;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}));var Po=class{constructor(e,r,o,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=o,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Cne=(t,e)=>{if(xl(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Wn(t.common.issues);return this._error=r,this._error}}};function be(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:o,description:n}=t;if(e&&(r||o))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??o??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:n}}var Te=class{get description(){return this._def.description}_getType(e){return la(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:la(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new qr,ctx:{common:e.parent.common,data:e.data,parsedType:la(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(wv(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let o=this.safeParse(e,r);if(o.success)return o.data;throw o.error}safeParse(e,r){let o={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:la(e)},n=this._parseSync({data:e,path:o.path,parent:o});return Cne(o,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:la(e)};if(!this["~standard"].async)try{let o=this._parseSync({data:e,path:[],parent:r});return xl(o)?{value:o.value}:{issues:r.common.issues}}catch(o){o?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(o=>xl(o)?{value:o.value}:{issues:r.common.issues})}async parseAsync(e,r){let o=await this.safeParseAsync(e,r);if(o.success)return o.data;throw o.error}async safeParseAsync(e,r){let o={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:la(e)},n=this._parse({data:e,path:o.path,parent:o}),i=await(wv(n)?n:Promise.resolve(n));return Cne(o,i)}refine(e,r){let o=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let s=e(n),a=()=>i.addIssue({code:N.custom,...o(n)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((o,n)=>e(o)?!0:(n.addIssue(typeof r=="function"?r(o,n):r),!1))}_refinement(e){return new bi({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return wi.create(this,this._def)}nullable(){return pa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Bc.create(this)}promise(){return El.create(this,this._def)}or(e){return Mp.create([this,e],this._def)}and(e){return Up.create(this,e,this._def)}transform(e){return new bi({...be(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Hp({...be(this._def),innerType:this,defaultValue:r,typeName:z.ZodDefault})}brand(){return new A$({typeName:z.ZodBranded,type:this,...be(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new qp({...be(this._def),innerType:this,catchValue:r,typeName:z.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return T$.create(this,e)}readonly(){return Zp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zAe=/^c[^\s-]{8,}$/i,jAe=/^[0-9a-z]+$/,MAe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,UAe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,LAe=/^[a-z0-9_-]{21}$/i,FAe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,VAe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,BAe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,HAe="^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",z4,qAe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ZAe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,KAe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,WAe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,JAe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,GAe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,One="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",XAe=new RegExp(`^${One}$`);function Nne(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function YAe(t){return new RegExp(`^${Nne(t)}$`)}function QAe(t){let e=`${One}T${Nne(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function eTe(t,e){return!!((e==="v4"||!e)&&qAe.test(t)||(e==="v6"||!e)&&KAe.test(t))}function tTe(t,e){if(!FAe.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let o=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(o));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function rTe(t,e){return!!((e==="v4"||!e)&&ZAe.test(t)||(e==="v6"||!e)&&WAe.test(t))}var Dp=class t extends Te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){let i=this._getOrReturnCtx(e);return F(i,{code:N.invalid_type,expected:q.string,received:i.parsedType}),oe}let o=new qr,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(n=this._getOrReturnCtx(e,n),s?F(n,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&F(n,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),o.dirty())}else if(i.kind==="email")BAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"email",code:N.invalid_string,message:i.message}),o.dirty());else if(i.kind==="emoji")z4||(z4=new RegExp(HAe,"u")),z4.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"emoji",code:N.invalid_string,message:i.message}),o.dirty());else if(i.kind==="uuid")UAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"uuid",code:N.invalid_string,message:i.message}),o.dirty());else if(i.kind==="nanoid")LAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"nanoid",code:N.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid")zAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"cuid",code:N.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid2")jAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"cuid2",code:N.invalid_string,message:i.message}),o.dirty());else if(i.kind==="ulid")MAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"ulid",code:N.invalid_string,message:i.message}),o.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),F(n,{validation:"url",code:N.invalid_string,message:i.message}),o.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"regex",code:N.invalid_string,message:i.message}),o.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),F(n,{code:N.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),o.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:N.invalid_string,validation:{startsWith:i.value},message:i.message}),o.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),F(n,{code:N.invalid_string,validation:{endsWith:i.value},message:i.message}),o.dirty()):i.kind==="datetime"?QAe(i).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:N.invalid_string,validation:"datetime",message:i.message}),o.dirty()):i.kind==="date"?XAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:N.invalid_string,validation:"date",message:i.message}),o.dirty()):i.kind==="time"?YAe(i).test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:N.invalid_string,validation:"time",message:i.message}),o.dirty()):i.kind==="duration"?VAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"duration",code:N.invalid_string,message:i.message}),o.dirty()):i.kind==="ip"?eTe(e.data,i.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"ip",code:N.invalid_string,message:i.message}),o.dirty()):i.kind==="jwt"?tTe(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"jwt",code:N.invalid_string,message:i.message}),o.dirty()):i.kind==="cidr"?rTe(e.data,i.version)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"cidr",code:N.invalid_string,message:i.message}),o.dirty()):i.kind==="base64"?JAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"base64",code:N.invalid_string,message:i.message}),o.dirty()):i.kind==="base64url"?GAe.test(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{validation:"base64url",code:N.invalid_string,message:i.message}),o.dirty()):je.assertNever(i);return{status:o.value,value:e.data}}_regex(e,r,o){return this.refinement(n=>e.test(n),{validation:r,code:N.invalid_string,...W.errToObj(o)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...W.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...W.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...W.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...W.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...W.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...W.errToObj(r)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Dp.create=t=>new Dp({checks:[],typeName:z.ZodString,coerce:t?.coerce??!1,...be(t)});function nTe(t,e){let r=(t.toString().split(".")[1]||"").length,o=(e.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(t.toFixed(n).replace(".","")),s=Number.parseInt(e.toFixed(n).replace(".",""));return i%s/10**n}var bv=class t extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){let i=this._getOrReturnCtx(e);return F(i,{code:N.invalid_type,expected:q.number,received:i.parsedType}),oe}let o,n=new qr;for(let i of this._def.checks)i.kind==="int"?je.isInteger(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:N.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(o=this._getOrReturnCtx(e,o),F(o,{code:N.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(o=this._getOrReturnCtx(e,o),F(o,{code:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?nTe(e.data,i.value)!==0&&(o=this._getOrReturnCtx(e,o),F(o,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:N.not_finite,message:i.message}),n.dirty()):je.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,W.toString(r))}gt(e,r){return this.setLimit("min",e,!1,W.toString(r))}lte(e,r){return this.setLimit("max",e,!0,W.toString(r))}lt(e,r){return this.setLimit("max",e,!1,W.toString(r))}setLimit(e,r,o,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:o,message:W.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&je.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let o of this._def.checks){if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;o.kind==="min"?(r===null||o.value>r)&&(r=o.value):o.kind==="max"&&(e===null||o.value<e)&&(e=o.value)}return Number.isFinite(r)&&Number.isFinite(e)}};bv.create=t=>new bv({checks:[],typeName:z.ZodNumber,coerce:t?.coerce||!1,...be(t)});var _v=class t extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let o,n=new qr;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(o=this._getOrReturnCtx(e,o),F(o,{code:N.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(o=this._getOrReturnCtx(e,o),F(o,{code:N.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(o=this._getOrReturnCtx(e,o),F(o,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):je.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return F(r,{code:N.invalid_type,expected:q.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,W.toString(r))}gt(e,r){return this.setLimit("min",e,!1,W.toString(r))}lte(e,r){return this.setLimit("max",e,!0,W.toString(r))}lt(e,r){return this.setLimit("max",e,!1,W.toString(r))}setLimit(e,r,o,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:o,message:W.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};_v.create=t=>new _v({checks:[],typeName:z.ZodBigInt,coerce:t?.coerce??!1,...be(t)});var Sv=class extends Te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){let o=this._getOrReturnCtx(e);return F(o,{code:N.invalid_type,expected:q.boolean,received:o.parsedType}),oe}return cn(e.data)}};Sv.create=t=>new Sv({typeName:z.ZodBoolean,coerce:t?.coerce||!1,...be(t)});var xv=class t extends Te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){let i=this._getOrReturnCtx(e);return F(i,{code:N.invalid_type,expected:q.date,received:i.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return F(i,{code:N.invalid_date}),oe}let o=new qr,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:N.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),o.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),F(n,{code:N.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),o.dirty()):je.assertNever(i);return{status:o.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:W.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};xv.create=t=>new xv({checks:[],coerce:t?.coerce||!1,typeName:z.ZodDate,...be(t)});var Ev=class extends Te{_parse(e){if(this._getType(e)!==q.symbol){let o=this._getOrReturnCtx(e);return F(o,{code:N.invalid_type,expected:q.symbol,received:o.parsedType}),oe}return cn(e.data)}};Ev.create=t=>new Ev({typeName:z.ZodSymbol,...be(t)});var zp=class extends Te{_parse(e){if(this._getType(e)!==q.undefined){let o=this._getOrReturnCtx(e);return F(o,{code:N.invalid_type,expected:q.undefined,received:o.parsedType}),oe}return cn(e.data)}};zp.create=t=>new zp({typeName:z.ZodUndefined,...be(t)});var jp=class extends Te{_parse(e){if(this._getType(e)!==q.null){let o=this._getOrReturnCtx(e);return F(o,{code:N.invalid_type,expected:q.null,received:o.parsedType}),oe}return cn(e.data)}};jp.create=t=>new jp({typeName:z.ZodNull,...be(t)});var kv=class extends Te{constructor(){super(...arguments),this._any=!0}_parse(e){return cn(e.data)}};kv.create=t=>new kv({typeName:z.ZodAny,...be(t)});var Vc=class extends Te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return cn(e.data)}};Vc.create=t=>new Vc({typeName:z.ZodUnknown,...be(t)});var $s=class extends Te{_parse(e){let r=this._getOrReturnCtx(e);return F(r,{code:N.invalid_type,expected:q.never,received:r.parsedType}),oe}};$s.create=t=>new $s({typeName:z.ZodNever,...be(t)});var Iv=class extends Te{_parse(e){if(this._getType(e)!==q.undefined){let o=this._getOrReturnCtx(e);return F(o,{code:N.invalid_type,expected:q.void,received:o.parsedType}),oe}return cn(e.data)}};Iv.create=t=>new Iv({typeName:z.ZodVoid,...be(t)});var Bc=class t extends Te{_parse(e){let{ctx:r,status:o}=this._processInputParams(e),n=this._def;if(r.parsedType!==q.array)return F(r,{code:N.invalid_type,expected:q.array,received:r.parsedType}),oe;if(n.exactLength!==null){let s=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(s||a)&&(F(r,{code:s?N.too_big:N.too_small,minimum:a?n.exactLength.value:void 0,maximum:s?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),o.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(F(r,{code:N.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),o.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(F(r,{code:N.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),o.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>n.type._parseAsync(new Po(r,s,r.path,a)))).then(s=>qr.mergeArray(o,s));let i=[...r.data].map((s,a)=>n.type._parseSync(new Po(r,s,r.path,a)));return qr.mergeArray(o,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:W.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:W.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:W.toString(r)}})}nonempty(e){return this.min(1,e)}};Bc.create=(t,e)=>new Bc({type:t,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...be(e)});function Np(t){if(t instanceof Jn){let e={};for(let r in t.shape){let o=t.shape[r];e[r]=wi.create(Np(o))}return new Jn({...t._def,shape:()=>e})}else return t instanceof Bc?new Bc({...t._def,type:Np(t.element)}):t instanceof wi?wi.create(Np(t.unwrap())):t instanceof pa?pa.create(Np(t.unwrap())):t instanceof fa?fa.create(t.items.map(e=>Np(e))):t}var Jn=class t extends Te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=je.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){let u=this._getOrReturnCtx(e);return F(u,{code:N.invalid_type,expected:q.object,received:u.parsedType}),oe}let{status:o,ctx:n}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof $s&&this._def.unknownKeys==="strip"))for(let u in n.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let l=i[u],d=n.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Po(n,d,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof $s){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(u==="strict")a.length>0&&(F(n,{code:N.unrecognized_keys,keys:a}),o.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=n.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Po(n,d,n.path,l)),alwaysSet:l in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>qr.mergeObjectSync(o,u)):qr.mergeObjectSync(o,c)}get shape(){return this._def.shape()}strict(e){return W.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,o)=>{let n=this._def.errorMap?.(r,o).message??o.defaultError;return r.code==="unrecognized_keys"?{message:W.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:z.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let o of je.objectKeys(e))e[o]&&this.shape[o]&&(r[o]=this.shape[o]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let o of je.objectKeys(this.shape))e[o]||(r[o]=this.shape[o]);return new t({...this._def,shape:()=>r})}deepPartial(){return Np(this)}partial(e){let r={};for(let o of je.objectKeys(this.shape)){let n=this.shape[o];e&&!e[o]?r[o]=n:r[o]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let o of je.objectKeys(this.shape))if(e&&!e[o])r[o]=this.shape[o];else{let i=this.shape[o];for(;i instanceof wi;)i=i._def.innerType;r[o]=i}return new t({...this._def,shape:()=>r})}keyof(){return Dne(je.objectKeys(this.shape))}};Jn.create=(t,e)=>new Jn({shape:()=>t,unknownKeys:"strip",catchall:$s.create(),typeName:z.ZodObject,...be(e)});Jn.strictCreate=(t,e)=>new Jn({shape:()=>t,unknownKeys:"strict",catchall:$s.create(),typeName:z.ZodObject,...be(e)});Jn.lazycreate=(t,e)=>new Jn({shape:t,unknownKeys:"strip",catchall:$s.create(),typeName:z.ZodObject,...be(e)});var Mp=class extends Te{_parse(e){let{ctx:r}=this._processInputParams(e),o=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Wn(a.ctx.common.issues));return F(r,{code:N.invalid_union,unionErrors:s}),oe}if(r.common.async)return Promise.all(o.map(async i=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(n);{let i,s=[];for(let c of o){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(c=>new Wn(c));return F(r,{code:N.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}};Mp.create=(t,e)=>new Mp({options:t,typeName:z.ZodUnion,...be(e)});var da=t=>t instanceof Lp?da(t.schema):t instanceof bi?da(t.innerType()):t instanceof Fp?[t.value]:t instanceof Vp?t.options:t instanceof Bp?je.objectValues(t.enum):t instanceof Hp?da(t._def.innerType):t instanceof zp?[void 0]:t instanceof jp?[null]:t instanceof wi?[void 0,...da(t.unwrap())]:t instanceof pa?[null,...da(t.unwrap())]:t instanceof A$||t instanceof Zp?da(t.unwrap()):t instanceof qp?da(t._def.innerType):[],j4=class t extends Te{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return F(r,{code:N.invalid_type,expected:q.object,received:r.parsedType}),oe;let o=this.discriminator,n=r.data[o],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(F(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),oe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,o){let n=new Map;for(let i of r){let s=da(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:z.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...be(o)})}};function M4(t,e){let r=la(t),o=la(e);if(t===e)return{valid:!0,data:t};if(r===q.object&&o===q.object){let n=je.objectKeys(e),i=je.objectKeys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};Object.prototype.hasOwnProperty.call(s,"__proto__")&&delete s.__proto__;for(let a of i){if(a==="__proto__")continue;let c=M4(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===q.array&&o===q.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],c=M4(s,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return r===q.date&&o===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Up=class extends Te{_parse(e){let{status:r,ctx:o}=this._processInputParams(e),n=(i,s)=>{if(N4(i)||N4(s))return oe;let a=M4(i.value,s.value);return a.valid?((D4(i)||D4(s))&&r.dirty(),{status:r.value,value:a.data}):(F(o,{code:N.invalid_intersection_types}),oe)};return o.common.async?Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([i,s])=>n(i,s)):n(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}};Up.create=(t,e,r)=>new Up({left:t,right:e,typeName:z.ZodIntersection,...be(r)});var fa=class t extends Te{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==q.array)return F(o,{code:N.invalid_type,expected:q.array,received:o.parsedType}),oe;if(o.data.length<this._def.items.length)return F(o,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;!this._def.rest&&o.data.length>this._def.items.length&&(F(o,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...o.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Po(o,s,o.path,a)):null}).filter(s=>!!s);return o.common.async?Promise.all(i).then(s=>qr.mergeArray(r,s)):qr.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};fa.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fa({items:t,typeName:z.ZodTuple,rest:null,...be(e)})};var U4=class t extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==q.object)return F(o,{code:N.invalid_type,expected:q.object,received:o.parsedType}),oe;let n=[],i=this._def.keyType,s=this._def.valueType;for(let a in o.data)n.push({key:i._parse(new Po(o,a,o.path,a)),value:s._parse(new Po(o,o.data[a],o.path,a)),alwaysSet:a in o.data});return o.common.async?qr.mergeObjectAsync(r,n):qr.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,o){return r instanceof Te?new t({keyType:e,valueType:r,typeName:z.ZodRecord,...be(o)}):new t({keyType:Dp.create(),valueType:e,typeName:z.ZodRecord,...be(r)})}},$v=class extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==q.map)return F(o,{code:N.invalid_type,expected:q.map,received:o.parsedType}),oe;let n=this._def.keyType,i=this._def.valueType,s=[...o.data.entries()].map(([a,c],u)=>({key:n._parse(new Po(o,a,o.path,[u,"key"])),value:i._parse(new Po(o,c,o.path,[u,"value"]))}));if(o.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return oe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return oe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};$v.create=(t,e,r)=>new $v({valueType:e,keyType:t,typeName:z.ZodMap,...be(r)});var Av=class t extends Te{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==q.set)return F(o,{code:N.invalid_type,expected:q.set,received:o.parsedType}),oe;let n=this._def;n.minSize!==null&&o.data.size<n.minSize.value&&(F(o,{code:N.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&o.data.size>n.maxSize.value&&(F(o,{code:N.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function s(c){let u=new Set;for(let l of c){if(l.status==="aborted")return oe;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...o.data.values()].map((c,u)=>i._parse(new Po(o,c,o.path,u)));return o.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:W.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:W.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Av.create=(t,e)=>new Av({valueType:t,minSize:null,maxSize:null,typeName:z.ZodSet,...be(e)});var L4=class t extends Te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.function)return F(r,{code:N.invalid_type,expected:q.function,received:r.parsedType}),oe;function o(a,c){return $$({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,vv(),Fc].filter(u=>!!u),issueData:{code:N.invalid_arguments,argumentsError:c}})}function n(a,c){return $$({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,vv(),Fc].filter(u=>!!u),issueData:{code:N.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof El){let a=this;return cn(async function(...c){let u=new Wn([]),l=await a._def.args.parseAsync(c,i).catch(f=>{throw u.addIssue(o(c,f)),u}),d=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(d,i).catch(f=>{throw u.addIssue(n(d,f)),u})})}else{let a=this;return cn(function(...c){let u=a._def.args.safeParse(c,i);if(!u.success)throw new Wn([o(c,u.error)]);let l=Reflect.apply(s,this,u.data),d=a._def.returns.safeParse(l,i);if(!d.success)throw new Wn([n(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:fa.create(e).rest(Vc.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,o){return new t({args:e||fa.create([]).rest(Vc.create()),returns:r||Vc.create(),typeName:z.ZodFunction,...be(o)})}},Lp=class extends Te{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Lp.create=(t,e)=>new Lp({getter:t,typeName:z.ZodLazy,...be(e)});var Fp=class extends Te{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return F(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fp.create=(t,e)=>new Fp({value:t,typeName:z.ZodLiteral,...be(e)});function Dne(t,e){return new Vp({values:t,typeName:z.ZodEnum,...be(e)})}var Vp=class t extends Te{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),o=this._def.values;return F(r,{expected:je.joinValues(o),received:r.parsedType,code:N.invalid_type}),oe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),o=this._def.values;return F(r,{received:r.data,code:N.invalid_enum_value,options:o}),oe}return cn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(o=>!e.includes(o)),{...this._def,...r})}};Vp.create=Dne;var Bp=class extends Te{_parse(e){let r=je.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(e);if(o.parsedType!==q.string&&o.parsedType!==q.number){let n=je.objectValues(r);return F(o,{expected:je.joinValues(n),received:o.parsedType,code:N.invalid_type}),oe}if(this._cache||(this._cache=new Set(je.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=je.objectValues(r);return F(o,{received:o.data,code:N.invalid_enum_value,options:n}),oe}return cn(e.data)}get enum(){return this._def.values}};Bp.create=(t,e)=>new Bp({values:t,typeName:z.ZodNativeEnum,...be(e)});var El=class extends Te{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return F(r,{code:N.invalid_type,expected:q.promise,received:r.parsedType}),oe;let o=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return cn(o.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};El.create=(t,e)=>new El({type:t,typeName:z.ZodPromise,...be(e)});var bi=class extends Te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:o}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:s=>{F(o,s),s.fatal?r.abort():r.dirty()},get path(){return o.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let s=n.transform(o.data,i);if(o.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return oe;let c=await this._def.schema._parseAsync({data:a,path:o.path,parent:o});return c.status==="aborted"?oe:c.status==="dirty"?Op(c.value):r.value==="dirty"?Op(c.value):c});{if(r.value==="aborted")return oe;let a=this._def.schema._parseSync({data:s,path:o.path,parent:o});return a.status==="aborted"?oe:a.status==="dirty"?Op(a.value):r.value==="dirty"?Op(a.value):a}}if(n.type==="refinement"){let s=a=>{let c=n.refinement(a,i);if(o.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(o.common.async===!1){let a=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});return a.status==="aborted"?oe:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(a=>a.status==="aborted"?oe:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(o.common.async===!1){let s=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!xl(s))return oe;let a=n.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(s=>xl(s)?Promise.resolve(n.transform(s.value,i)).then(a=>({status:r.value,value:a})):oe);je.assertNever(n)}};bi.create=(t,e,r)=>new bi({schema:t,typeName:z.ZodEffects,effect:e,...be(r)});bi.createWithPreprocess=(t,e,r)=>new bi({schema:e,effect:{type:"preprocess",transform:t},typeName:z.ZodEffects,...be(r)});var wi=class extends Te{_parse(e){return this._getType(e)===q.undefined?cn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wi.create=(t,e)=>new wi({innerType:t,typeName:z.ZodOptional,...be(e)});var pa=class extends Te{_parse(e){return this._getType(e)===q.null?cn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pa.create=(t,e)=>new pa({innerType:t,typeName:z.ZodNullable,...be(e)});var Hp=class extends Te{_parse(e){let{ctx:r}=this._processInputParams(e),o=r.data;return r.parsedType===q.undefined&&(o=this._def.defaultValue()),this._def.innerType._parse({data:o,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Hp.create=(t,e)=>new Hp({innerType:t,typeName:z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...be(e)});var qp=class extends Te{_parse(e){let{ctx:r}=this._processInputParams(e),o={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return wv(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Wn(o.common.issues)},input:o.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Wn(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}};qp.create=(t,e)=>new qp({innerType:t,typeName:z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...be(e)});var Tv=class extends Te{_parse(e){if(this._getType(e)!==q.nan){let o=this._getOrReturnCtx(e);return F(o,{code:N.invalid_type,expected:q.nan,received:o.parsedType}),oe}return{status:"valid",value:e.data}}};Tv.create=t=>new Tv({typeName:z.ZodNaN,...be(t)});var A$=class extends Te{_parse(e){let{ctx:r}=this._processInputParams(e),o=r.data;return this._def.type._parse({data:o,path:r.path,parent:r})}unwrap(){return this._def.type}},T$=class t extends Te{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return i.status==="aborted"?oe:i.status==="dirty"?(r.dirty(),Op(i.value)):this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();{let n=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return n.status==="aborted"?oe:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:o.path,parent:o})}}static create(e,r){return new t({in:e,out:r,typeName:z.ZodPipeline})}},Zp=class extends Te{_parse(e){let r=this._def.innerType._parse(e),o=n=>(xl(n)&&(n.value=Object.freeze(n.value)),n);return wv(r)?r.then(n=>o(n)):o(r)}unwrap(){return this._def.innerType}};Zp.create=(t,e)=>new Zp({innerType:t,typeName:z.ZodReadonly,...be(e)});var Imt={object:Jn.lazycreate},z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(z||(z={}));var $mt=Dp.create,Amt=bv.create,Tmt=Tv.create,Pmt=_v.create,Rmt=Sv.create,Cmt=xv.create,Omt=Ev.create,Nmt=zp.create,Dmt=jp.create,zmt=kv.create,jmt=Vc.create,Mmt=$s.create,Umt=Iv.create,Lmt=Bc.create,zne=Jn.create,Fmt=Jn.strictCreate,Vmt=Mp.create,Bmt=j4.create,Hmt=Up.create,qmt=fa.create,Zmt=U4.create,Kmt=$v.create,Wmt=Av.create,Jmt=L4.create,Gmt=Lp.create,Xmt=Fp.create,Ymt=Vp.create,Qmt=Bp.create,eht=El.create,tht=bi.create,rht=wi.create,nht=pa.create,oht=bi.createWithPreprocess,iht=T$.create;var iTe=S("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ae.init(t,e),t.def=e,t.type=e.type},{get with(){return this.check},set with(t){Ti(this,"with",t)},parse(t,e){return su(this,t,e,{callee:this.parse})},parseAsync(t,e){return au(this,t,e,{callee:this.parseAsync})},safeParse(t,e){return Jl(this,t,e)},safeParseAsync(t,e){return Xl(this,t,e)},check(...t){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0})},clone(t,e){return Ke(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},apply(t,...e){return e.length===0?t(this):t(this,...e)}});var sTe=S("ZodMiniObject",(t,e)=>{Nb.init(t,e),iTe.init(t,e),aT(t,"shape",r=>r._zod.def.shape,!1)});function F4(t,e){let r={type:"object",shape:t??{},...D(e)};return new sTe(r)}function As(t){return!!t._zod}function kl(t){let e=Object.values(t);if(e.length===0)return F4({});let r=e.every(As),o=e.every(n=>!As(n));if(r)return F4(t);if(o)return zne(t);throw new Error("Mixed Zod versions detected in object shape.")}function Hc(t,e){return As(t)?Jl(t,e):t.safeParse(e)}async function P$(t,e){return As(t)?await Xl(t,e):await t.safeParseAsync(e)}function qc(t){if(!t)return;let e;if(As(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Kp(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let o=Object.values(t);if(o.length>0&&o.every(n=>typeof n=="object"&&n!==null&&(n._def!==void 0||n._zod!==void 0||typeof n.parse=="function")))return kl(t)}}if(As(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function cTe(t){return t.length===0?"object root":t.reduce((e,r,o)=>o===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function R$(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${cTe(e.path)}`:e.message).join(`
133
133
  `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function jne(t){return t.description}function Mne(t){if(As(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Wp(t){if(As(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let o=t.value;if(o!==void 0)return o}var B4="2025-11-25";var Une=[B4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zc="io.modelcontextprotocol/related-task",O$="2.0",Yt=PS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Lne=ot([I(),We().int()]),Fne=I(),wht=dr({ttl:We().optional(),pollInterval:We().optional()}),uTe=B({ttl:We().optional()}),lTe=B({taskId:I()}),H4=dr({progressToken:Lne.optional(),[Zc]:lTe.optional()}),Gn=B({_meta:H4.optional()}),Pv=Gn.extend({task:uTe.optional()}),Vne=t=>Pv.safeParse(t).success,Ar=B({method:I(),params:Gn.loose().optional()}),Ro=B({_meta:H4.optional()}),Co=B({method:I(),params:Ro.loose().optional()}),Tr=dr({_meta:H4.optional()}),N$=ot([I(),We().int()]),Bne=B({jsonrpc:G(O$),id:N$,...Ar.shape}).strict(),q4=t=>Bne.safeParse(t).success,Hne=B({jsonrpc:G(O$),...Co.shape}).strict(),qne=t=>Hne.safeParse(t).success,Z4=B({jsonrpc:G(O$),id:N$,result:Tr}).strict(),Rv=t=>Z4.safeParse(t).success;var Y;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Y||(Y={}));var K4=B({jsonrpc:G(O$),id:N$.optional(),error:B({code:We().int(),message:I(),data:ft().optional()})}).strict();var Zne=t=>K4.safeParse(t).success;var Kne=ot([Bne,Hne,Z4,K4]),bht=ot([Z4,K4]),D$=Tr.strict(),dTe=Ro.extend({requestId:N$.optional(),reason:I().optional()}),z$=Co.extend({method:G("notifications/cancelled"),params:dTe}),fTe=B({src:I(),mimeType:I().optional(),sizes:Ae(I()).optional(),theme:fr(["light","dark"]).optional()}),Cv=B({icons:Ae(fTe).optional()}),Jp=B({name:I(),title:I().optional()}),Wne=Jp.extend({...Jp.shape,...Cv.shape,version:I(),websiteUrl:I().optional(),description:I().optional()}),pTe=Od(B({applyDefaults:Lt().optional()}),ct(I(),ft())),mTe=Rh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Od(B({form:pTe.optional(),url:Yt.optional()}),ct(I(),ft()).optional())),hTe=dr({list:Yt.optional(),cancel:Yt.optional(),requests:dr({sampling:dr({createMessage:Yt.optional()}).optional(),elicitation:dr({create:Yt.optional()}).optional()}).optional()}),gTe=dr({list:Yt.optional(),cancel:Yt.optional(),requests:dr({tools:dr({call:Yt.optional()}).optional()}).optional()}),yTe=B({experimental:ct(I(),Yt).optional(),sampling:B({context:Yt.optional(),tools:Yt.optional()}).optional(),elicitation:mTe.optional(),roots:B({listChanged:Lt().optional()}).optional(),tasks:hTe.optional(),extensions:ct(I(),Yt).optional()}),vTe=Gn.extend({protocolVersion:I(),capabilities:yTe,clientInfo:Wne}),W4=Ar.extend({method:G("initialize"),params:vTe});var wTe=B({experimental:ct(I(),Yt).optional(),logging:Yt.optional(),completions:Yt.optional(),prompts:B({listChanged:Lt().optional()}).optional(),resources:B({subscribe:Lt().optional(),listChanged:Lt().optional()}).optional(),tools:B({listChanged:Lt().optional()}).optional(),tasks:gTe.optional(),extensions:ct(I(),Yt).optional()}),bTe=Tr.extend({protocolVersion:I(),capabilities:wTe,serverInfo:Wne,instructions:I().optional()}),J4=Co.extend({method:G("notifications/initialized"),params:Ro.optional()});var j$=Ar.extend({method:G("ping"),params:Gn.optional()}),_Te=B({progress:We(),total:st(We()),message:st(I())}),STe=B({...Ro.shape,..._Te.shape,progressToken:Lne}),M$=Co.extend({method:G("notifications/progress"),params:STe}),xTe=Gn.extend({cursor:Fne.optional()}),Ov=Ar.extend({params:xTe.optional()}),Nv=Tr.extend({nextCursor:Fne.optional()}),ETe=fr(["working","input_required","completed","failed","cancelled"]),Dv=B({taskId:I(),status:ETe,ttl:ot([We(),xh()]),createdAt:I(),lastUpdatedAt:I(),pollInterval:st(We()),statusMessage:st(I())}),Gp=Tr.extend({task:Dv}),kTe=Ro.merge(Dv),zv=Co.extend({method:G("notifications/tasks/status"),params:kTe}),U$=Ar.extend({method:G("tasks/get"),params:Gn.extend({taskId:I()})}),L$=Tr.merge(Dv),F$=Ar.extend({method:G("tasks/result"),params:Gn.extend({taskId:I()})}),_ht=Tr.loose(),V$=Ov.extend({method:G("tasks/list")}),B$=Nv.extend({tasks:Ae(Dv)}),H$=Ar.extend({method:G("tasks/cancel"),params:Gn.extend({taskId:I()})}),Jne=Tr.merge(Dv),Gne=B({uri:I(),mimeType:st(I()),_meta:ct(I(),ft()).optional()}),Xne=Gne.extend({text:I()}),G4=I().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Yne=Gne.extend({blob:G4}),jv=fr(["user","assistant"]),Xp=B({audience:Ae(jv).optional(),priority:We().min(0).max(1).optional(),lastModified:Su.datetime({offset:!0}).optional()}),Qne=B({...Jp.shape,...Cv.shape,uri:I(),description:st(I()),mimeType:st(I()),size:st(We()),annotations:Xp.optional(),_meta:st(dr({}))}),ITe=B({...Jp.shape,...Cv.shape,uriTemplate:I(),description:st(I()),mimeType:st(I()),annotations:Xp.optional(),_meta:st(dr({}))}),q$=Ov.extend({method:G("resources/list")}),$Te=Nv.extend({resources:Ae(Qne)}),Z$=Ov.extend({method:G("resources/templates/list")}),ATe=Nv.extend({resourceTemplates:Ae(ITe)}),X4=Gn.extend({uri:I()}),TTe=X4,K$=Ar.extend({method:G("resources/read"),params:TTe}),PTe=Tr.extend({contents:Ae(ot([Xne,Yne]))}),RTe=Co.extend({method:G("notifications/resources/list_changed"),params:Ro.optional()}),CTe=X4,OTe=Ar.extend({method:G("resources/subscribe"),params:CTe}),NTe=X4,DTe=Ar.extend({method:G("resources/unsubscribe"),params:NTe}),zTe=Ro.extend({uri:I()}),jTe=Co.extend({method:G("notifications/resources/updated"),params:zTe}),MTe=B({name:I(),description:st(I()),required:st(Lt())}),UTe=B({...Jp.shape,...Cv.shape,description:st(I()),arguments:st(Ae(MTe)),_meta:st(dr({}))}),W$=Ov.extend({method:G("prompts/list")}),LTe=Nv.extend({prompts:Ae(UTe)}),FTe=Gn.extend({name:I(),arguments:ct(I(),I()).optional()}),J$=Ar.extend({method:G("prompts/get"),params:FTe}),Y4=B({type:G("text"),text:I(),annotations:Xp.optional(),_meta:ct(I(),ft()).optional()}),Q4=B({type:G("image"),data:G4,mimeType:I(),annotations:Xp.optional(),_meta:ct(I(),ft()).optional()}),eU=B({type:G("audio"),data:G4,mimeType:I(),annotations:Xp.optional(),_meta:ct(I(),ft()).optional()}),VTe=B({type:G("tool_use"),name:I(),id:I(),input:ct(I(),ft()),_meta:ct(I(),ft()).optional()}),BTe=B({type:G("resource"),resource:ot([Xne,Yne]),annotations:Xp.optional(),_meta:ct(I(),ft()).optional()}),HTe=Qne.extend({type:G("resource_link")}),tU=ot([Y4,Q4,eU,HTe,BTe]),qTe=B({role:jv,content:tU}),ZTe=Tr.extend({description:I().optional(),messages:Ae(qTe)}),KTe=Co.extend({method:G("notifications/prompts/list_changed"),params:Ro.optional()}),WTe=B({title:I().optional(),readOnlyHint:Lt().optional(),destructiveHint:Lt().optional(),idempotentHint:Lt().optional(),openWorldHint:Lt().optional()}),JTe=B({taskSupport:fr(["required","optional","forbidden"]).optional()}),eoe=B({...Jp.shape,...Cv.shape,description:I().optional(),inputSchema:B({type:G("object"),properties:ct(I(),Yt).optional(),required:Ae(I()).optional()}).catchall(ft()),outputSchema:B({type:G("object"),properties:ct(I(),Yt).optional(),required:Ae(I()).optional()}).catchall(ft()).optional(),annotations:WTe.optional(),execution:JTe.optional(),_meta:ct(I(),ft()).optional()}),G$=Ov.extend({method:G("tools/list")}),GTe=Nv.extend({tools:Ae(eoe)}),X$=Tr.extend({content:Ae(tU).default([]),structuredContent:ct(I(),ft()).optional(),isError:Lt().optional()}),Sht=X$.or(Tr.extend({toolResult:ft()})),XTe=Pv.extend({name:I(),arguments:ct(I(),ft()).optional()}),Yp=Ar.extend({method:G("tools/call"),params:XTe}),YTe=Co.extend({method:G("notifications/tools/list_changed"),params:Ro.optional()}),xht=B({autoRefresh:Lt().default(!0),debounceMs:We().int().nonnegative().default(300)}),Mv=fr(["debug","info","notice","warning","error","critical","alert","emergency"]),QTe=Gn.extend({level:Mv}),rU=Ar.extend({method:G("logging/setLevel"),params:QTe}),ePe=Ro.extend({level:Mv,logger:I().optional(),data:ft()}),tPe=Co.extend({method:G("notifications/message"),params:ePe}),rPe=B({name:I().optional()}),nPe=B({hints:Ae(rPe).optional(),costPriority:We().min(0).max(1).optional(),speedPriority:We().min(0).max(1).optional(),intelligencePriority:We().min(0).max(1).optional()}),oPe=B({mode:fr(["auto","required","none"]).optional()}),iPe=B({type:G("tool_result"),toolUseId:I().describe("The unique identifier for the corresponding tool call."),content:Ae(tU).default([]),structuredContent:B({}).loose().optional(),isError:Lt().optional(),_meta:ct(I(),ft()).optional()}),sPe=$h("type",[Y4,Q4,eU]),C$=$h("type",[Y4,Q4,eU,VTe,iPe]),aPe=B({role:jv,content:ot([C$,Ae(C$)]),_meta:ct(I(),ft()).optional()}),cPe=Pv.extend({messages:Ae(aPe),modelPreferences:nPe.optional(),systemPrompt:I().optional(),includeContext:fr(["none","thisServer","allServers"]).optional(),temperature:We().optional(),maxTokens:We().int(),stopSequences:Ae(I()).optional(),metadata:Yt.optional(),tools:Ae(eoe).optional(),toolChoice:oPe.optional()}),uPe=Ar.extend({method:G("sampling/createMessage"),params:cPe}),Uv=Tr.extend({model:I(),stopReason:st(fr(["endTurn","stopSequence","maxTokens"]).or(I())),role:jv,content:sPe}),nU=Tr.extend({model:I(),stopReason:st(fr(["endTurn","stopSequence","maxTokens","toolUse"]).or(I())),role:jv,content:ot([C$,Ae(C$)])}),lPe=B({type:G("boolean"),title:I().optional(),description:I().optional(),default:Lt().optional()}),dPe=B({type:G("string"),title:I().optional(),description:I().optional(),minLength:We().optional(),maxLength:We().optional(),format:fr(["email","uri","date","date-time"]).optional(),default:I().optional()}),fPe=B({type:fr(["number","integer"]),title:I().optional(),description:I().optional(),minimum:We().optional(),maximum:We().optional(),default:We().optional()}),pPe=B({type:G("string"),title:I().optional(),description:I().optional(),enum:Ae(I()),default:I().optional()}),mPe=B({type:G("string"),title:I().optional(),description:I().optional(),oneOf:Ae(B({const:I(),title:I()})),default:I().optional()}),hPe=B({type:G("string"),title:I().optional(),description:I().optional(),enum:Ae(I()),enumNames:Ae(I()).optional(),default:I().optional()}),gPe=ot([pPe,mPe]),yPe=B({type:G("array"),title:I().optional(),description:I().optional(),minItems:We().optional(),maxItems:We().optional(),items:B({type:G("string"),enum:Ae(I())}),default:Ae(I()).optional()}),vPe=B({type:G("array"),title:I().optional(),description:I().optional(),minItems:We().optional(),maxItems:We().optional(),items:B({anyOf:Ae(B({const:I(),title:I()}))}),default:Ae(I()).optional()}),wPe=ot([yPe,vPe]),bPe=ot([hPe,gPe,wPe]),_Pe=ot([bPe,lPe,dPe,fPe]),SPe=Pv.extend({mode:G("form").optional(),message:I(),requestedSchema:B({type:G("object"),properties:ct(I(),_Pe),required:Ae(I()).optional()})}),xPe=Pv.extend({mode:G("url"),message:I(),elicitationId:I(),url:I().url()}),EPe=ot([SPe,xPe]),kPe=Ar.extend({method:G("elicitation/create"),params:EPe}),IPe=Ro.extend({elicitationId:I()}),$Pe=Co.extend({method:G("notifications/elicitation/complete"),params:IPe}),Qp=Tr.extend({action:fr(["accept","decline","cancel"]),content:Rh(t=>t===null?void 0:t,ct(I(),ot([I(),We(),Lt(),Ae(I())])).optional())}),APe=B({type:G("ref/resource"),uri:I()});var TPe=B({type:G("ref/prompt"),name:I()}),PPe=Gn.extend({ref:ot([TPe,APe]),argument:B({name:I(),value:I()}),context:B({arguments:ct(I(),I()).optional()}).optional()}),Y$=Ar.extend({method:G("completion/complete"),params:PPe});function toe(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function roe(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var RPe=Tr.extend({completion:dr({values:Ae(I()).max(100),total:st(We().int()),hasMore:st(Lt())})}),CPe=B({uri:I().startsWith("file://"),name:I().optional(),_meta:ct(I(),ft()).optional()}),OPe=Ar.extend({method:G("roots/list"),params:Gn.optional()}),oU=Tr.extend({roots:Ae(CPe)}),NPe=Co.extend({method:G("notifications/roots/list_changed"),params:Ro.optional()}),Eht=ot([j$,W4,Y$,rU,J$,W$,q$,Z$,K$,OTe,DTe,Yp,G$,U$,F$,V$,H$]),kht=ot([z$,M$,J4,NPe,zv]),Iht=ot([D$,Uv,nU,Qp,oU,L$,B$,Gp]),$ht=ot([j$,uPe,kPe,OPe,U$,F$,V$,H$]),Aht=ot([z$,M$,tPe,jTe,RTe,YTe,KTe,zv,$Pe]),Tht=ot([D$,bTe,RPe,ZTe,LTe,$Te,ATe,PTe,X$,GTe,L$,B$,Gp]),Z=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===Y.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new V4(n.elicitations,r)}return new t(e,r,o)}},V4=class extends Z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Y.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Kc(t){return t==="completed"||t==="failed"||t==="cancelled"}var ooe=Symbol("Let zodToJsonSchema decide on which parser to use");var noe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},ioe=t=>typeof t=="string"?{...noe,name:t}:{...noe,...t};var soe=t=>{let e=ioe(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([o,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}};function iU(t,e,r,o){o?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Le(t,e,r,o,n){t[e]=r,iU(t,e,o,n)}var Q$=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Rt(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Q$(e,t.currentPath):e.join("/")}}function aoe(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==z.ZodAny&&(r.items=ie(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Le(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Le(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Le(r,"minItems",t.exactLength.value,t.exactLength.message,e),Le(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function coe(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"min":e.target==="jsonSchema7"?o.inclusive?Le(r,"minimum",o.value,o.message,e):Le(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),Le(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?Le(r,"maximum",o.value,o.message,e):Le(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),Le(r,"maximum",o.value,o.message,e));break;case"multipleOf":Le(r,"multipleOf",o.value,o.message,e);break}return r}function uoe(){return{type:"boolean"}}function eA(t,e){return ie(t.type._def,e)}var loe=(t,e)=>ie(t.innerType._def,e);function sU(t,e,r){let o=r??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,i)=>sU(t,e,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return DPe(t,e)}}var DPe=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let o of t.checks)switch(o.kind){case"min":Le(r,"minimum",o.value,o.message,e);break;case"max":Le(r,"maximum",o.value,o.message,e);break}return r};function doe(t,e){return{...ie(t.innerType._def,e),default:t.defaultValue()}}function foe(t,e){return e.effectStrategy==="input"?ie(t.schema._def,e):Rt(e)}function poe(t){return{type:"string",enum:Array.from(t.values)}}var zPe=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function moe(t,e){let r=[ie(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ie(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),o=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(i=>{if(zPe(i))n.push(...i.allOf),i.unevaluatedProperties===void 0&&(o=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else o=void 0;n.push(s)}}),n.length?{allOf:n,...o}:void 0}function hoe(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var aU,_i={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(aU===void 0&&(aU=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),aU),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function tA(t,e){let r={type:"string"};if(t.checks)for(let o of t.checks)switch(o.kind){case"min":Le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":Le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Si(r,"email",o.message,e);break;case"format:idn-email":Si(r,"idn-email",o.message,e);break;case"pattern:zod":un(r,_i.email,o.message,e);break}break;case"url":Si(r,"uri",o.message,e);break;case"uuid":Si(r,"uuid",o.message,e);break;case"regex":un(r,o.regex,o.message,e);break;case"cuid":un(r,_i.cuid,o.message,e);break;case"cuid2":un(r,_i.cuid2,o.message,e);break;case"startsWith":un(r,RegExp(`^${cU(o.value,e)}`),o.message,e);break;case"endsWith":un(r,RegExp(`${cU(o.value,e)}$`),o.message,e);break;case"datetime":Si(r,"date-time",o.message,e);break;case"date":Si(r,"date",o.message,e);break;case"time":Si(r,"time",o.message,e);break;case"duration":Si(r,"duration",o.message,e);break;case"length":Le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),Le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{un(r,RegExp(cU(o.value,e)),o.message,e);break}case"ip":{o.version!=="v6"&&Si(r,"ipv4",o.message,e),o.version!=="v4"&&Si(r,"ipv6",o.message,e);break}case"base64url":un(r,_i.base64url,o.message,e);break;case"jwt":un(r,_i.jwt,o.message,e);break;case"cidr":{o.version!=="v6"&&un(r,_i.ipv4Cidr,o.message,e),o.version!=="v4"&&un(r,_i.ipv6Cidr,o.message,e);break}case"emoji":un(r,_i.emoji(),o.message,e);break;case"ulid":{un(r,_i.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Si(r,"binary",o.message,e);break}case"contentEncoding:base64":{Le(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{un(r,_i.base64,o.message,e);break}}break}case"nanoid":un(r,_i.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function cU(t,e){return e.patternStrategy==="escape"?MPe(t):t}var jPe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function MPe(t){let e="";for(let r=0;r<t.length;r++)jPe.has(t[r])||(e+="\\"),e+=t[r];return e}function Si(t,e,r,o){t.format||t.anyOf?.some(n=>n.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&o.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&o.errorMessages&&{errorMessage:{format:r}}})):Le(t,"format",e,r,o)}function un(t,e,r,o){t.pattern||t.allOf?.some(n=>n.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&o.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:goe(e,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):Le(t,"pattern",goe(e,o),r,o)}function goe(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},o=r.i?t.source.toLowerCase():t.source,n="",i=!1,s=!1,a=!1;for(let c=0;c<o.length;c++){if(i){n+=o[c],i=!1;continue}if(r.i){if(s){if(o[c].match(/[a-z]/)){a?(n+=o[c],n+=`${o[c-2]}-${o[c]}`.toUpperCase(),a=!1):o[c+1]==="-"&&o[c+2]?.match(/[a-z]/)?(n+=o[c],a=!0):n+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){n+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){n+=`(^|(?<=[\r