@tomato414941/foundation 19.1.0 → 21.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.mjs CHANGED
@@ -119,7 +119,7 @@ ${c}
119
119
  }`,m;try{m=new l(...s,d)(...a)}catch(f){throw new Ae(`this schema (generated code failed to evaluate: ${f.message})`)}return t?.debug&&(m.code=u),m.definite=i.definite,m}function ne(e,t){for(let[i,n]of e.constants)if(n===t)return i;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function ec(e,t){return e.definite=!1,ne(e,t)}function Y(e){return`v${e.varCounter++}`}function xve(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return Cr;let i=r;return i.issues.length===0?i.value:Cr}function yr(e,t,r,i,n=!0){let o=e.content.length,s=t.constants.size,a=t.constantCounter,c=t.varCounter;try{return ht(e,t,r,i,n)}catch(u){if(!(u instanceof Ae)||!u.islandable)throw u;if(e.content.length=o,t.constants.size>s){let l=Array.from(t.constants.keys()).slice(s);for(let d of l)t.constants.delete(d)}return t.constantCounter=a,t.varCounter=c,Eve(e,t,r,i)}}function Eve(e,t,r,i){t.definite=!1;let n=ne(t,r),o=ne(t,xve),s=Y(t);return e.write(`const ${s} = ${o}(${n}, ${i});`),e.write(`if (${s} === INVALID) return INVALID;`),s}var Ave=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Rve(e,t,r,i){let n=r._zod.def.checks;if(!n||n.length===0)return i;let o=i;for(let s of n){let a=s._zod.def;if(a.when&&!Ave.has(a.check))throw new Ae('check with a custom "when" condition');switch(a.check){case"greater_than":Ive(e,t,a,o);break;case"less_than":$ve(e,t,a,o);break;case"multiple_of":Pve(e,t,a,o);break;case"number_format":O2(e,a,o);break;case"min_length":{let c=Ya(a.minimum,"min_length"),u=zT(e,t,o,`${o}.length >= ${c} && ${o}.length < ${a.minimum*2}`);e.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Ya(a.maximum,"max_length"),u=zT(e,t,o,`${o}.length > ${c}`);e.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Ya(a.length,"length_equals"),u=zT(e,t,o,`${o}.length >= ${c} && ${o}.length <= ${a.length*2}`);e.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":e.write(`if (${o}.size < ${Ya(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${o}.size > ${Ya(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${o}.size !== ${Ya(a.size,"size_equals")}) return INVALID;`);break;case"string_format":o=N2(e,t,a,o);break;case"custom":o=Nve(e,t,s,o);break;case"bigint_format":Tve(e,a,o);break;case"mime_type":Cve(e,t,a,o);break;case"property":Dve(e,t,a,o);break;case"properties":kve(e,t,a,o);break;case"overwrite":{let c=Y(t);Ove(e,t,s,o,c),o=c;break}default:throw new Ae(`check type ${a.check}`)}}return o}function zT(e,t,r,i){let n=ne(t,Wa),o=Y(t);return e.write(`const ${o} = typeof ${r} === "string" && ${i} ? ${n}(${r}) : ${r}.length;`),o}function Ya(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Ae(`${t} bound of type ${typeof e}`);return`${e}`}function D2(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Ae("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Ae("comparison check with Invalid Date bound");return ne(e,t)}throw new Ae(`comparison check bound of type ${typeof t}`)}function Ive(e,t,r,i){let n=r.inclusive?"<":"<=";e.write(`if (${i} ${n} ${D2(t,r.value)}) return INVALID;`)}function $ve(e,t,r,i){let n=r.inclusive?">":">=";e.write(`if (${i} ${n} ${D2(t,r.value)}) return INVALID;`)}function Pve(e,t,r,i){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Ae("multiple_of check with a zero divisor");e.write(`if (${i} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ne(t,pp);e.write(`if (${n}(${i}, ${Ya(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function O2(e,t,r){let i=t.format;switch(i){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Ae(`number format ${i}`)}}function Tve(e,t,r){let i=t.format;if(i)switch(i){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Ae(`bigint format ${i}`)}}function Cve(e,t,r,i){let n=r.mime;if(n&&n.length>0){let o=ne(t,new Set(n));e.write(`if (!${o}.has(${i}.type)) return INVALID;`)}}function kve(e,t,r,i){if(r.when)throw new Ae('check with a custom "when" condition');e.write(`if (${i} == null) return INVALID;`);let n=r.shape;for(let o of Reflect.ownKeys(n)){let s=typeof o=="symbol"?ne(t,o):Pr(o),a=Y(t);e.write(`const ${a} = ${i}[${s}];`),yr(e,t,n[o],a,!1)}}function Dve(e,t,r,i){let n=`${i}[${JSON.stringify(r.property)}]`;ht(e,t,r.schema,n)}function Ove(e,t,r,i,n){let o=r._zod.def.tx;if(!o)throw new Ae("overwrite check without a transform function");if(tc(o))throw new Yn("z.compile: async overwrite transforms are not supported");let s=ne(t,o);e.write(`const ${n} = ${s}(${i});`)}function jT(){throw new Kr}function qT(e){this.issues.push(e)}function Nve(e,t,r,i){let n=r._zod.def;if(n.fn){if(tc(n.fn))throw new Yn("z.compile: async .refine() predicates are not supported");let o=ec(t,n.fn),s=ne(t,jT),a=Y(t);return e.write(`const ${a} = ${o}(${i});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`),i}if(r._zod.check){if(tc(r._zod.check))throw new Yn("z.compile: async .superRefine() / check functions are not supported");let o=r._zod.check,a=ec(t,u=>{let l={value:u,issues:[],addIssue:qT};return o(l)instanceof Promise&&jT(),l.issues.length===0?l.value:Cr}),c=Y(t);return e.write(`const ${c} = ${a}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),c}throw new Ae("custom check without a predicate or check function")}var Uve=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 N2(e,t,r,i,n=!0){let o=r.format;if(o==="base64"){let u=ne(t,Cp);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="base64url"){let u=ne(t,vy);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="jwt"){let u=ne(t,by),l=ne(t,r.alg??null);return e.write(`if (!${u}(${i}, ${l})) return INVALID;`),i}if(o==="ipv6"){let u=ne(t,Tp);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="cidrv6"){let u=ne(t,gy);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="credit_card"){let u=ne(t,Sy);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="iban"){let u=ne(t,wy);return e.write(`if (!${u}(${i})) return INVALID;`),i}let s=r;if(o==="url"||o==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=ne(t,fy),l=ne(t,r),d=Y(t),m=Y(t);if(e.write(`const ${d} = ${i}.trim();`),e.write(`const ${m} = ${u}(${d}, ${l});`),e.write(`if (typeof ${m} === "number") return INVALID;`),s.hostname!==void 0){let v=ne(t,my);e.write(`if (!${v}(${m}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let v=ne(t,hy);e.write(`if (!${v}(${m}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let f=Y(t),g=s.normalize?`${m}.href`:`${ne(t,Pp)}(${d})`;return e.write(`const ${f} = ${g};`),f}let a=r.fn;if(a){if(tc(a))throw new Ae(`async string format ${o}`);let u=ne(t,a);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(Uve.has(o)&&r.pattern){let u=ne(t,r.pattern);return e.write(`${u}.lastIndex = 0;`),e.write(`if (!${u}.test(${i})) return INVALID;`),i}let c=r.format;switch(c){case"regex":throw new Ae("regex format without a pattern");case"lowercase":e.write(`if (${i} !== ${i}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${i} !== ${i}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${i}.includes(${Pr(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;e.write(`if (${i}.slice(0, ${u.length}) !== ${Pr(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;e.write(`if (${i}.slice(-${u.length}) !== ${Pr(u)}) return INVALID;`);break}default:throw new Ae(`string format ${c}`)}return i}function ht(e,t,r,i,n=!0){let o=r._zod.def,s=o.type;if(o.coerce)throw new Ae(`coercion (z.coerce.${s}())`);let a=n||!!o.checks?.length,c;switch(s){case"string":c=Lve(e,t,r,i,a);break;case"number":c=Mve(e,r,i);break;case"boolean":c=zve(e,i);break;case"bigint":c=jve(e,r,i);break;case"symbol":c=Fve(e,i);break;case"undefined":c=Gve(e,i);break;case"null":c=qve(e,i);break;case"any":case"unknown":c=i;break;case"never":e.write("return INVALID;"),c=i;break;case"void":c=Vve(e,i);break;case"nan":c=Kve(e,i);break;case"date":c=Bve(e,i);break;case"object":c=Hve(e,t,r,i,a);break;case"optional":c=Wve(e,t,r,i,a);break;case"nullable":c=Xve(e,t,r,i,a);break;case"array":c=Yve(e,t,r,i,a);break;case"literal":c=Qve(e,t,r,i);break;case"enum":c=eSe(e,t,r,i);break;case"readonly":{let u=T2(e,t,r,i),l=Y(t);e.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":T2(e,t,r,i),c="true";break;case"default":case"prefault":c=tSe(e,t,r,i);break;case"nonoptional":c=rSe(e,t,r,i);break;case"tuple":c=nSe(e,t,r,i);break;case"union":c=iSe(e,t,r,i);break;case"intersection":c=aSe(e,t,r,i);break;case"record":c=cSe(e,t,r,i);break;case"map":c=lSe(e,t,r,i);break;case"set":c=dSe(e,t,r,i);break;case"file":c=pSe(e,i);break;case"template_literal":c=fSe(e,t,r,i);break;case"lazy":c=mSe(e,t,r,i);break;case"pipe":c=hSe(e,t,r,i);break;case"custom":c=gSe(e,t,r,i);break;case"transform":c=SSe(e,t,r,i);break;case"catch":c=vSe(e,t,r,i);break;default:throw new Ae(`schema type ${s}`)}return c===null?null:Rve(e,t,r,c)}function Lve(e,t,r,i,n=!0){e.write(`if (typeof ${i} !== "string") return INVALID;`);let o=r._zod.def;return o.format===void 0?i:N2(e,t,o,i,n)}function Mve(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let i=t._zod.def;return i.check==="number_format"&&i.format&&O2(e,{format:i.format},r),r}function zve(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function jve(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let i=t._zod.def;if(i.format)switch(i.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function Fve(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function Gve(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function qve(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function Vve(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function Kve(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function Bve(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function Hve(e,t,r,i,n=!0){let o=r._zod.def;e.write(`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) return INVALID;`);let s=o.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=_=>typeof _=="symbol"?ne(t,_):Pr(_),d=_=>typeof _=="symbol"?`[${l(_)}]`:Pr(_),m=s;if(a.includes("__proto__"))throw new Ae('object shape key "__proto__"');let f=new Map;for(let _ of u){let x=m[_],T=l(_),U=Y(t);if(e.write(`const ${U} = ${i}[${T}];`),x._zod.optin!==void 0){let N=Y(t);e.write(`let ${N} = (() => {`),e.indented(K=>{let B=yr(K,t,x,U);K.write(`return ${B};`)}),e.write("})();"),x._zod.optout==="optional"?(e.write(`if (${N} === INVALID) {`),e.indented(K=>{K.write(`if (${T} in ${i}) return INVALID;`),K.write(`${N} = undefined;`)}),e.write("}")):e.write(`if (${N} === INVALID) return INVALID;`),f.set(_,N)}else{Zve(x)&&e.write(`if (!(${T} in ${i})) return INVALID;`);let N=yr(e,t,x,U,n);N!==null&&f.set(_,N)}}let g=o.catchall,v="none";if(g){let _=g._zod.def.type;if(_==="never"){let x=a.map(T=>`k !== ${Pr(T)}`).join(" && ")||"true";e.write(`for (const k in ${i}) {`),e.indented(T=>{T.write(`if (${x}) return INVALID;`)}),e.write("}")}else(_==="unknown"||_==="any")&&!g._zod.def.checks?.length?v="passthrough":v="schema"}let S=Y(t),b=u.some(_=>P2(m[_])||FT(m[_]));if(!n){if(v==="schema"){let _=a.length>0?ne(t,new Set(a)):null;e.write(`for (const k in ${i}) {`),e.indented(x=>{x.write('if (k === "__proto__") continue;'),_&&x.write(`if (${_}.has(k)) continue;`);let T=Y(t);x.write(`const ${T} = ${i}[k];`),yr(x,t,g,T,!1)}),e.write("}")}return null}if(b){e.write(`const ${S} = {};`);for(let _ of u){let x=l(_),T=f.get(_);FT(m[_])?e.write(`if (${x} in ${i}) ${S}[${x}] = ${T};`):P2(m[_])?e.write(`if (${T} !== undefined || ${x} in ${i}) ${S}[${x}] = ${T};`):e.write(`${S}[${x}] = ${T};`)}}else{let _=u.map(x=>`${d(x)}: ${f.get(x)}`).join(", ");e.write(`const ${S} = { ${_} };`)}if(v!=="none"){let _=a.length>0?ne(t,new Set(a)):null;e.write(`for (const k in ${i}) {`),e.indented(x=>{if(x.write('if (k === "__proto__") continue;'),_&&x.write(`if (${_}.has(k)) continue;`),v==="passthrough")x.write(`${S}[k] = ${i}[k];`);else{let T=Y(t);x.write(`const ${T} = ${i}[k];`);let U=yr(x,t,g,T);x.write(`${S}[k] = ${U};`)}}),e.write("}")}return S}function Wve(e,t,r,i,n=!0){let o=r._zod.def;if(Jve(r))return ht(e,t,o.innerType,i,n);if(o.innerType._zod.optin==="defaulted"){let a=Y(t),c=Y(t);return e.write(`let ${a};`),e.write(`if (${i} === undefined) {`),e.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=ht(l,t,o.innerType,i);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),e.write("} else {"),e.indented(u=>{let l=ht(u,t,o.innerType,i);u.write(`${a} = ${l};`)}),e.write("}"),a}let s=n?Y(t):null;return s&&e.write(`let ${s};`),e.write(`if (${i} !== undefined) {`),e.indented(a=>{let c=ht(a,t,o.innerType,i,n);s&&c!==null&&a.write(`${s} = ${c};`)}),e.write("}"),s}function Jve(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function Zve(e){return e._zod.optin===void 0&&Qa(e)}function Qa(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Qa(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Qa(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Qa):!0;case"intersection":return!t.left||!t.right?!0:Qa(t.left)&&Qa(t.right);case"pipe":return t.in?Qa(t.in):!0;default:return!0}}function FT(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function P2(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&Cu(e)}function Cu(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?Cu(t.innerType):!0;case"union":return t.options?t.options.some(Cu):!0;case"intersection":return!t.left||!t.right||Cu(t.left)||Cu(t.right);case"pipe":return t.out?Cu(t.out):!0;default:return!0}}function Xve(e,t,r,i,n=!0){let o=r._zod.def,s=n?Y(t):null;return s&&e.write(`let ${s} = null;`),e.write(`if (${i} !== null) {`),e.indented(a=>{let c=ht(a,t,o.innerType,i,n);s&&c!==null&&a.write(`${s} = ${c};`)}),e.write("}"),s}function Yve(e,t,r,i,n=!0){let o=r._zod.def;e.write(`if (!Array.isArray(${i})) return INVALID;`);let s=n?Y(t):null,a=Y(t),c=Y(t);return s&&e.write(`const ${s} = new Array(${i}.length);`),e.write(`for (let ${a} = 0; ${a} < ${i}.length; ${a}++) {`),e.indented(u=>{u.write(`const ${c} = ${i}[${a}];`);let l=yr(u,t,o.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),e.write("}"),s}function Qve(e,t,r,i){let o=r._zod.def.values;if(o.length!==1){let a=ne(t,new Set(o));return e.write(`if (!${a}.has(${i})) return INVALID;`),i}let s=o[0];if(typeof s=="number"&&Number.isNaN(s)){let a=ne(t,new Set(o));return e.write(`if (!${a}.has(${i})) return INVALID;`),i}if(typeof s=="string")e.write(`if (${i} !== ${Pr(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")e.write(`if (${i} !== ${s}) return INVALID;`);else if(s===null)e.write(`if (${i} !== null) return INVALID;`);else if(s===void 0)e.write(`if (${i} !== undefined) return INVALID;`);else if(typeof s=="bigint")e.write(`if (${i} !== ${s}n) return INVALID;`);else throw new Ae(`literal type ${typeof s}`);return i}function eSe(e,t,r,i){let n=r._zod.values;if(!n)throw new Ae("enum schema without enumerated values");let o=ne(t,n);return e.write(`if (!${o}.has(${i})) return INVALID;`),i}function T2(e,t,r,i){let n=r._zod.def;return ht(e,t,n.innerType,i)}function tSe(e,t,r,i){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 ht(e,t,n.innerType,i);let c=ne(t,s),u=Y(t);return e.write(`let ${u} = ${i};`),e.write(`if (${i} === undefined) ${u} = ${c}();`),ht(e,t,n.innerType,u)}let a=Y(t);if(s){let c=ne(t,s),u=ne(t,fp);e.write(`let ${a};`),e.write(`if (${i} === undefined) {`),e.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),e.write("} else {"),e.indented(l=>{let d=ht(l,t,n.innerType,i);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${i} !== undefined) {`),e.indented(c=>{let u=ht(c,t,n.innerType,i);c.write(`${a} = ${u};`)}),e.write("}");return a}function rSe(e,t,r,i){let n=r._zod.def,o=ht(e,t,n.innerType,i),s=Y(t);return e.write(`const ${s} = ${o};`),e.write(`if (${s} === undefined) return INVALID;`),s}function nSe(e,t,r,i){let n=r._zod.def,o=n.items,s=n.rest;e.write(`if (!Array.isArray(${i})) return INVALID;`);let a=C2(o,"optin"),c=C2(o,"optout");s?e.write(`if (${i}.length < ${a}) return INVALID;`):e.write(`if (${i}.length < ${a} || ${i}.length > ${o.length}) return INVALID;`);let u=Y(t);e.write(`const ${u} = [];`);for(let l=0;l<o.length;l++){let d=o[l];if(l>=c)e.write(`if (${u}.length === ${l}) {`),e.indented(m=>{m.write(`if (${l} < ${i}.length) {`),m.indented(f=>{let g=Y(t);f.write(`const ${g} = ${i}[${l}];`);let v=yr(f,t,d,g);f.write(`${u}[${l}] = ${v};`)}),m.write("} else {"),m.indented(f=>{if(FT(d)){f.write(`${u}.length = ${l};`);return}let g=Y(t),v=Y(t);f.write(`const ${g} = undefined;`),f.write(`const ${v} = (() => {`),f.indented(S=>{let b=yr(S,t,d,g);S.write(`return ${b};`)}),f.write("})();"),f.write(`if (${v} === INVALID || ${v} === undefined) ${u}.length = ${l};`),f.write(`else ${u}[${l}] = ${v};`)}),m.write("}")}),e.write("}");else{let m=Y(t);e.write(`const ${m} = ${i}[${l}];`);let f=yr(e,t,d,m);e.write(`${u}[${l}] = ${f};`)}}if(s){let l=Y(t),d=Y(t);e.write(`for (let ${l} = ${o.length}; ${l} < ${i}.length; ${l}++) {`),e.indented(m=>{m.write(`const ${d} = ${i}[${l}];`);let f=yr(m,t,s,d);m.write(`${u}[${l}] = ${f};`)}),e.write("}")}return u}function C2(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function iSe(e,t,r,i){let n=r._zod.def,o=n.options;if(n.discriminator)return oSe(e,t,n,i);if(n.inclusive===!1)throw new Ae("exclusive unions (z.xor)");if(o.length===0)return e.write("return INVALID;"),i;if(o.length===1)return ht(e,t,o[0],i);if(o.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(o.flatMap(l=>l._zod.def.values)),u=ne(t,c);return e.write(`if (!${u}.has(${i})) return INVALID;`),i}let a=Y(t);e.write(`let ${a};`);for(let c=0;c<o.length;c++){let u=o[c];c===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(l=>{let d=ht(l,t,u,i);l.write(`return ${d};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function oSe(e,t,r,i){if(r.unionFallback)throw new Ae("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),i;let n=Y(t),o=Y(t);e.write(`const ${n} = ${i}?.[${Pr(r.discriminator)}];`),e.write(`let ${o};`);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 Ae("discriminated union option without static discriminator values");for(let m of u){if(a.has(m))throw new Ae(`duplicate discriminator value ${String(m)}`);a.add(m)}let l=Array.from(u,m=>sSe(t,n,m)),d=s?"if":"else if";e.write(`${d} (${l.join(" || ")}) {`),e.indented(m=>{let f=ht(m,t,c,i);m.write(`${o} = ${f};`)}),e.write("}"),s=!1}return e.write("else { return INVALID; }"),o}function sSe(e,t,r){if(typeof r=="string")return`${t} === ${Pr(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let i=ne(e,r);return`${t} === ${i}`}throw new Ae(`literal discriminator value ${String(r)}`)}function aSe(e,t,r,i){let n=r._zod.def;t.definite=!1;let o=yr(e,t,n.left,i),s=yr(e,t,n.right,i),a=ne(t,$u),c=Y(t);return e.write(`const ${c} = ${a}(${o}, ${s});`),e.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function cSe(e,t,r,i){let n=r._zod.def,o=ne(t,bn);e.write(`if (!${o}(${i})) return INVALID;`);let s=Y(t),a=Y(t),c=Y(t);e.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let f=[];for(let v of l){if(!(typeof v=="string"||typeof v=="number"||typeof v=="symbol"))throw new Ae(`record key value ${String(v)}`);let S=typeof v=="number"?v.toString():v;if(S==="__proto__")throw new Ae('record key "__proto__"');f.push(S);let b=ne(t,v),_=ht(e,t,n.keyType,b),x=Y(t);e.write(`const ${x} = ${i}[${uSe(t,S)}];`);let T=yr(e,t,n.valueType,x);e.write(`${s}[${_}] = ${T};`)}let g=ne(t,new Set(f));return e.write(`for (const ${a} in ${i}) {`),e.indented(v=>{v.write(`if (${g}.has(${a})) continue;`),u.mode==="loose"?v.write(`if (${a} !== "__proto__") ${s}[${a}] = ${i}[${a}];`):v.write("return INVALID;")}),e.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let f=n.mode==="loose",g=zy(n.keyType);g.definite===!1&&(t.definite=!1);let v=ne(t,g),S=ne(t,Do),b=Y(t);return k2(e,t,i,a,_=>{_.write(`let ${b} = ${v}(${a});`),_.write(`if (${b} === INVALID && typeof ${a} === "string" && ${S}.test(${a})) ${b} = ${v}(Number(${a}));`),f?_.write(`if (${b} === INVALID) { ${s}[${a}] = ${i}[${a}]; continue; }`):_.write(`if (${b} === INVALID) return INVALID;`),_.write(`if (${b} === "__proto__") continue;`);let x=Y(t);_.write(`const ${x} = ${i}[${a}];`);let T=yr(_,t,n.valueType,x);_.write(`${s}[${b}] = ${T};`)}),s}return k2(e,t,i,a,f=>{f.write(`const ${c} = ${i}[${a}];`);let g=yr(f,t,n.valueType,c);f.write(`${s}[${a}] = ${g};`)},"return INVALID;"),s}function k2(e,t,r,i,n,o){let s=ne(t,Object.prototype.propertyIsEnumerable),a=Y(t),c=Y(t),u=Y(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${c} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),e.indented(l=>{l.write(`const ${i} = ${c}[${u}];`),l.write(`if (${i} === "__proto__" || !${s}.call(${r}, ${i})) continue;`),n(l)}),e.write("}"),e.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),e.indented(l=>{l.write(`const ${i} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${i})) continue;`),o?l.write(o):n(l)}),e.write("}")}function uSe(e,t){return typeof t=="string"?Pr(t):ne(e,t)}function lSe(e,t,r,i){let n=r._zod.def;e.write(`if (!(${i} instanceof Map)) return INVALID;`);let o=Y(t),s=Y(t),a=Y(t);return e.write(`const ${o} = new Map();`),e.write(`for (const [${s}, ${a}] of ${i}) {`),e.indented(c=>{let u=ht(c,t,n.keyType,s),l=ht(c,t,n.valueType,a);c.write(`${o}.set(${u}, ${l});`)}),e.write("}"),o}function dSe(e,t,r,i){let n=r._zod.def;e.write(`if (!(${i} instanceof Set)) return INVALID;`);let o=Y(t),s=Y(t);return e.write(`const ${o} = new Set();`),e.write(`for (const ${s} of ${i}) {`),e.indented(a=>{let c=ht(a,t,n.valueType,s);a.write(`${o}.add(${c});`)}),e.write("}"),o}function pSe(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function fSe(e,t,r,i){e.write(`if (typeof ${i} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let o=ne(t,n);e.write(`${o}.lastIndex = 0;`),e.write(`if (!${o}.test(${i})) return INVALID;`)}return i}function mSe(e,t,r,i){let n=r._zod.def,o=ec(t,n.getter),s=ne(t,{parser:null});e.write(`if (!${s}.parser) {`),e.indented(c=>{c.write(`const inner = ${o}();`),c.write(`${s}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),e.write("}");let a=Y(t);return e.write(`const ${a} = ${s}.parser(${i});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function hSe(e,t,r,i){let n=r._zod.def,o=ht(e,t,n.in,i);if(n.transform){if(tc(n.transform))throw new Yn("z.compile: async transforms in pipes are not supported");let s=n.transform,c=ec(t,l=>{let d={value:l,issues:[],addIssue:qT},m=s(l,d);return m instanceof Promise?Cr:d.issues.length===0?m:Cr}),u=Y(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),ht(e,t,n.out,u)}else return ht(e,t,n.out,o)}function tc(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function gSe(e,t,r,i){let n=r._zod.def;if(n.fn){if(tc(n.fn))throw new Yn("z.compile: async custom predicates are not supported");let o=ec(t,n.fn),s=ne(t,jT),a=Y(t);e.write(`const ${a} = ${o}(${i});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Ae("custom schema without a predicate function");return i}function ySe(e,t,r){let i=e._zod.run({value:r,issues:[]},{});if(i&&typeof i.then=="function")return Cr;let n=i;return n.issues.length===0?n.value:t()}function vSe(e,t,r,i){let n=r._zod.def;if(!n.catchValue[Vg])throw new Ae("catch with a callback (only a constant catch value compiles)",!1);let o=Y(t);e.write(`let ${o} = (() => {`),e.indented(u=>{let l=yr(u,t,n.innerType,i);u.write(`return ${l};`)}),e.write("})();");let s=ne(t,n.innerType),a=ec(t,n.catchValue),c=ne(t,ySe);return e.write(`if (${o} === INVALID) {`),e.indented(u=>{u.write(`${o} = ${c}(${s}, ${a}, ${i});`),u.write(`if (${o} === INVALID) return INVALID;`)}),e.write("}"),o}function SSe(e,t,r,i){let n=r._zod.def;if(n.transform){if(tc(n.transform))throw new Yn("z.compile: async transforms are not supported");let o=n.transform,a=ec(t,u=>{let l={value:u,issues:[],addIssue:qT},d=o(u,l);return d instanceof Promise?Cr:l.issues.length===0?d:Cr}),c=Y(t);return e.write(`const ${c} = ${a}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),c}return i}function jy(e){return e.checks&&(e.checks=[...e.checks]),e}function VT(e,t){return new e(jy({type:"string",...L(t)}))}function KT(e,t){return new e(jy({type:"string",coerce:!0,...L(t)}))}function Fy(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...L(t)})}function Gy(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...L(t)})}function qy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...L(t)})}function Vy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(t)})}function Ky(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(t)})}function By(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(t)})}function Gp(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...L(t)})}function Hy(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...L(t)})}function Wy(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(t)})}function Jy(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...L(t)})}function Zy(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(t)})}function Xy(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...L(t)})}function Yy(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...L(t)})}function Qy(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(t)})}function ev(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(t)})}function tv(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(t)})}function BT(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...L(t)})}function rv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(t)})}function nv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(t)})}function iv(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...L(t)})}function ov(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...L(t)})}function sv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...L(t)})}function HT(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...L(t)})}function WT(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...L(t)})}function av(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...L(t)})}var JT={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function qp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(t)})}function Vp(e,t){return new e({type:"string",format:"date",check:"string_format",...L(t)})}function Kp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...L(t)})}function Bp(e,t){return new e({type:"string",format:"duration",check:"string_format",...L(t)})}function ZT(e,t){return new e(jy({type:"number",checks:[],...L(t)}))}function XT(e,t){return new e(jy({type:"number",coerce:!0,checks:[],...L(t)}))}function YT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...L(t)})}function QT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...L(t)})}function eC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...L(t)})}function tC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...L(t)})}function rC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...L(t)})}function nC(e,t){return new e({type:"boolean",...L(t)})}function iC(e,t){return new e({type:"boolean",coerce:!0,...L(t)})}function oC(e,t){return new e({type:"bigint",...L(t)})}function sC(e,t){return new e({type:"bigint",coerce:!0,...L(t)})}function aC(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...L(t)})}function cC(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...L(t)})}function uC(e,t){return new e({type:"symbol",...L(t)})}function lC(e,t){return new e({type:"undefined",...L(t)})}function dC(e,t){return new e({type:"null",...L(t)})}function pC(e){return new e({type:"any"})}function fC(e){return new e({type:"unknown"})}function mC(e,t){return new e({type:"never",...L(t)})}function hC(e,t){return new e({type:"void",...L(t)})}function gC(e,t){return new e({type:"date",...L(t)})}function yC(e,t){return new e({type:"date",coerce:!0,...L(t)})}function vC(e,t){return new e({type:"nan",...L(t)})}function Oi(e,t){return new sy({check:"less_than",...L(t),value:e,inclusive:!1})}function tn(e,t){return new sy({check:"less_than",...L(t),value:e,inclusive:!0})}function Ni(e,t){return new ay({check:"greater_than",...L(t),value:e,inclusive:!1})}function rn(e,t){return new ay({check:"greater_than",...L(t),value:e,inclusive:!0})}function cv(e){return Ni(0,e)}function uv(e){return Oi(0,e)}function lv(e){return tn(0,e)}function dv(e){return rn(0,e)}function vs(e,t){return new rP({check:"multiple_of",...L(t),value:e})}function Ss(e,t){return new oP({check:"max_size",...L(t),maximum:e})}function Ui(e,t){return new sP({check:"min_size",...L(t),minimum:e})}function rc(e,t){return new aP({check:"size_equals",...L(t),size:e})}function nc(e,t){return new cP({check:"max_length",...L(t),maximum:e})}function Oo(e,t){return new uP({check:"min_length",...L(t),minimum:e})}function ic(e,t){return new lP({check:"length_equals",...L(t),length:e})}function ku(e,t){return new dP({check:"string_format",format:"regex",...L(t),pattern:e})}function Du(e){return new pP({check:"string_format",format:"lowercase",...L(e)})}function Ou(e){return new fP({check:"string_format",format:"uppercase",...L(e)})}function Nu(e,t){return new mP({check:"string_format",format:"includes",...L(t),includes:e})}function Uu(e,t){return new hP({check:"string_format",format:"starts_with",...L(t),prefix:e})}function Lu(e,t){return new gP({check:"string_format",format:"ends_with",...L(t),suffix:e})}function pv(e,t,r){return new yP({check:"property",property:e,schema:t,...L(r)})}function Mu(e,t){return new vP({check:"properties",shape:e,...L(t)})}function zu(e,t){return new SP({check:"mime_type",mime:e,...L(t)})}function Qn(e){return new wP({check:"overwrite",tx:e})}function ju(e){return Qn(t=>t.normalize(e))}function Fu(){return Qn(e=>e.trim())}function Gu(){return Qn(e=>e.toLowerCase())}function qu(){return Qn(e=>e.toUpperCase())}function Vu(){return Qn(e=>i$(e))}function SC(e,t,r){return new e({type:"array",element:t,...L(r)})}function wSe(e,t,r){return new e({type:"union",options:t,...L(r)})}function bSe(e,t,r){return new e({type:"union",options:t,inclusive:!1,...L(r)})}function _Se(e,t,r,i){return new e({type:"union",options:r,discriminator:t,...L(i)})}function xSe(e,t,r){return new e({type:"intersection",left:t,right:r})}function ESe(e,t,r,i){let n=r instanceof ue,o=n?i:r,s=n?r:null;return new e({type:"tuple",items:t,rest:s,...L(o)})}function ASe(e,t,r,i){return new e({type:"record",keyType:t,valueType:r,...L(i)})}function RSe(e,t,r,i){return new e({type:"map",keyType:t,valueType:r,...L(i)})}function ISe(e,t,r){return new e({type:"set",valueType:t,...L(r)})}function $Se(e,t,r){let i=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:i,...L(r)})}function PSe(e,t,r){return new e({type:"enum",entries:t,...L(r)})}function TSe(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...L(r)})}function wC(e,t){return new e({type:"file",...L(t)})}function CSe(e,t){return new e({type:"transform",transform:t})}function kSe(e,t){return new e({type:"optional",innerType:t})}function DSe(e,t){return new e({type:"nullable",innerType:t})}function OSe(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():fp(r)}})}function NSe(e,t,r){return new e({type:"nonoptional",innerType:t,...L(r)})}function USe(e,t){return new e({type:"success",innerType:t})}function LSe(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:l$(r)})}function MSe(e,t,r){return new e({type:"pipe",in:t,out:r})}function zSe(e,t){return new e({type:"readonly",innerType:t})}function jSe(e,t,r){return new e({type:"template_literal",parts:t,...L(r)})}function FSe(e,t){return new e({type:"lazy",getter:t})}function GSe(e,t){return new e({type:"promise",innerType:t})}function bC(e,t,r){let i=L(r);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function _C(e,t,r){return new e({type:"custom",check:"custom",fn:t,...L(r)})}function xC(e,t){let r=U2(i=>(i.addIssue=n=>{if(typeof n=="string")i.issues.push(_u(n,i.value,r._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=i.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),i.issues.push(_u(o))}},e(i.value,i)),t);return r}function U2(e,t){let r=new rt({check:"custom",...L(t)});return r._zod.check=e,r}function EC(e){let t=new rt({check:"describe"});return t._zod.onattach=[r=>{let i=tr.get(r)??{};tr.add(r,{...i,description:e})}],t._zod.check=()=>{},t}function AC(e){let t=new rt({check:"meta"});return t._zod.onattach=[r=>{let i=tr.get(r)??{};tr.add(r,{...i,...e})}],t._zod.check=()=>{},t}function RC(e,t){let r=L(t),i=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(i=i.map(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let o=new Set(i),s=new Set(n),a=e.Codec??Np,c=e.Boolean??Dp,u=e.String??Xa,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),m=new a({type:"pipe",in:l,out:d,transform:((f,g)=>{let v=f;return r.case!=="sensitive"&&(v=v.toLowerCase()),o.has(v)?!0:s.has(v)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((f,g)=>f===!0?i[0]||"true":n[0]||"false"),error:r.error});return m._zod.bag.truthy=i,m._zod.bag.falsy=n,m._zod.bag.case=r.case??"insensitive",m}function oc(e,t,r,i={}){let n=L(i),o={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(o.pattern=r),new e(o)}function Hp(e,...t){for(let r of t)for(let i of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,i)&&er(e,i,r[i]);return e}function ws(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??tr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ut(e,t,r,i,n){let o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:i.path,message:n}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(n);return Object.assign(r,o),!0}function Ze(e,t,r={path:[],schemaPath:[]}){var i;let n=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{let m=s.schema,f=t.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(e,t,m,l)}let d=e._zod.parent;d&&(s.ref||(s.ref=d),Ze(d,t,l),t.seen.get(d).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Hp(s.schema,c),t.io==="input"&&kr(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function L2(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function bs(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let i=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=i.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.`);i.set(a,s[0])}}let n=s=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(s[0])?.id,m=e.external.uri??(g=>g);if(d)return{ref:m(d)};let f=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=f,{defId:f,ref:`${m("__shared")}#/${a}/${L2(f)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+L2(l)}},o=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=n(s);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
120
120
 
121
121
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}a.count>1&&e.reused==="ref"&&o(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function j2(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let i of t){if(!i||typeof i!="object")return;j2(i);let n=Object.keys(i);if(n.length!==1||n[0]!=="type")return;let o=i.type;for(let s of Array.isArray(o)?o:[o]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var F2=new Set(["type","properties","required","additionalProperties"]),M2=["oneOf","anyOf"];function z2(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function IC(e){let t=[];for(let o of e){if(typeof o!="object"||o.type!=="object")return null;for(let s in o)if(!F2.has(s))return null;t.push(o)}let r={},i=new Set;for(let o of t){for(let s in o.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of t){let l=u.properties?.[s]??z2(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:IC(a)??{allOf:a};er(r,s,c)}for(let s of o.required??[])i.add(s)}let n={type:"object",properties:r};if(i.size&&(n.required=[...i]),t.every(o=>o.additionalProperties===!1))n.additionalProperties=!1;else{let o=[];for(let s of t){let a=z2(s);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?n.additionalProperties=o[0]:o.length>1&&(n.additionalProperties={allOf:o})}return n}function qSe(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of F2)if(n in e)return;let r=t.filter(n=>M2.some(o=>Array.isArray(n[o]))),i=null;if(!r.length)i=IC(t);else{let n=r[0],o=M2.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=t.filter(c=>c!==n),a=n[o].map(c=>IC([...s,c]));if(a.some(c=>!c))return;i={[o]:a}}i&&(delete e.allOf,Hp(e,i))}function _s(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){i(d);let f=e.seen.get(d),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):Hp(u,g),Hp(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(g.$ref&&f.def)for(let S in u)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(u[S])===JSON.stringify(f.def[S])&&delete u[S]}let m=a._zod.parent;if(m&&m!==d){i(m);let f=e.seen.get(m);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let g in u)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(u[g])===JSON.stringify(f.def[g])&&delete u[g]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())i(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())j2(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])qSe(u)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Hp(n,r.defId?r.schema:r.def??r.schema);let o=e.metadataRegistry.get(t)?.id;o!==void 0&&n.id===o&&delete n.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,er(s,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ku(t,"input",e.processors),output:Ku(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function kr(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return kr(i.element,r);if(i.type==="set")return kr(i.valueType,r);if(i.type==="lazy")return kr(i.getter(),r);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault"||i.type==="catch")return kr(i.innerType,r);if(i.type==="intersection")return kr(i.left,r)||kr(i.right,r);if(i.type==="record"||i.type==="map")return kr(i.keyType,r)||kr(i.valueType,r);if(i.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:kr(i.in,r)||kr(i.out,r);if(i.type==="object"){for(let n in i.shape)if(kr(i.shape[n],r))return!0;return!1}if(i.type==="union"){for(let n of i.options)if(kr(n,r))return!0;return!1}if(i.type==="tuple"){for(let n of i.items)if(kr(n,r))return!0;return!!(i.rest&&kr(i.rest,r))}return!1}var $C=(e,t={})=>r=>{let i=ws({...r,processors:t});return Ze(e,i),bs(i,e),_s(i,e)},Ku=(e,t,r={})=>i=>{let{libraryOptions:n,target:o}=i??{},s=ws({...n??{},target:o,io:t,processors:r});return Ze(e,s),bs(s,e),_s(s,e)};var Bu=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Hu=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},G2=(e,t)=>{Bu(e,"minimum",t),Hu(e,"maximum",t)},B2=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},H2=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},W2=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},J2=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},q2=(e,t)=>Bu(e,"minimum",t.minimum),V2=(e,t)=>Hu(e,"maximum",t.maximum),K2=e=>(t,r)=>{J2(t,r.format);let[i,n]=e[r.format];Bu(t,"minimum",i),Hu(t,"maximum",n)},VSe={greater_than:(e,t)=>Bu(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Hu(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>B2(e,t.value),number_format:K2(hp),bigint_format:K2(gp),min_length:q2,max_length:V2,length_equals:(e,t)=>G2(e,t.length),min_size:q2,max_size:V2,size_equals:(e,t)=>G2(e,t.size),string_format:(e,t)=>{J2(e,t.format),t.pattern&&H2(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>W2(e,t.mime)};function Lt(e){let t={},r=e._zod.def,i=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let o of i)VSe[o._zod.def.check]?.(t,o._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Bu(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Bu(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Hu(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Hu(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&B2(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&W2(t,n.mime);for(let o of n.patterns??[])H2(t,o);return t}var KSe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},BSe=new Map([[yy,U$],[kp,L$]]),Z2=e=>BSe.get(e)??e,CC=(e,t,r,i)=>{let n=r;n.type="string";let{minimum:o,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Lt(e);if(typeof o=="number"&&(n.minLength=o),typeof s=="number"&&(n.maxLength=s),a&&(n.format=KSe[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(Z2);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},kC=(e,t,r,i)=>{let n=r,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Lt(e);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof o=="number"&&(n.minimum=o),m?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let g=new Set;for(let b of a)Number.isFinite(b)&&b!==0?g.add(Math.abs(b)):Ut(e,t,n,i,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[v,...S]=g;v!==void 0&&(n.multipleOf=v),S.length&&(n.allOf=[...n.allOf??[],...S.map(b=>({multipleOf:b}))])}},DC=(e,t,r,i)=>{r.type="boolean"},OC=(e,t,r,i)=>{Ut(e,t,r,i,"BigInt cannot be represented in JSON Schema")},NC=(e,t,r,i)=>{Ut(e,t,r,i,"Symbols cannot be represented in JSON Schema")},UC=(e,t,r,i)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},LC=(e,t,r,i)=>{Ut(e,t,r,i,"Undefined cannot be represented in JSON Schema")},MC=(e,t,r,i)=>{Ut(e,t,r,i,"Void cannot be represented in JSON Schema")},zC=(e,t,r,i)=>{r.not={}},jC=(e,t,r,i)=>{},FC=(e,t,r,i)=>{},GC=(e,t,r,i)=>{Ut(e,t,r,i,"Date cannot be represented in JSON Schema")},qC=(e,t,r,i)=>{let n=e._zod.def,o=vu(n.entries);if(o.length===0){r.not={};return}o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),r.enum=o},VC=(e,t,r,i)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let o=[];for(let s of n.values)if(s===void 0){if(Ut(e,t,r,i,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Ut(e,t,r,i,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(o.length!==0)if(o.length===1){let s=o[0];r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[s]:r.const=s}else o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),o.every(s=>typeof s=="boolean")&&(r.type="boolean"),o.every(s=>s===null)&&(r.type="null"),r.enum=o},KC=(e,t,r,i)=>{Ut(e,t,r,i,"NaN cannot be represented in JSON Schema")},BC=(e,t,r,i)=>{let n=r,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=o.source},HC=(e,t,r,i)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:o,maximum:s,mime:a}=Lt(e);o!==void 0&&(n.minLength=o),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})))},WC=(e,t,r,i)=>{r.type="boolean"},JC=(e,t,r,i)=>{Ut(e,t,r,i,"Custom types cannot be represented in JSON Schema")},ZC=(e,t,r,i)=>{Ut(e,t,r,i,"Function types cannot be represented in JSON Schema")},XC=(e,t,r,i)=>{Ut(e,t,r,i,"Transforms cannot be represented in JSON Schema")},YC=(e,t,r,i)=>{Ut(e,t,r,i,"Map cannot be represented in JSON Schema")},QC=(e,t,r,i)=>{Ut(e,t,r,i,"Set cannot be represented in JSON Schema")},ek=(e,t,r,i)=>{let n=r,o=e._zod.def,{minimum:s,maximum:a}=Lt(e);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Ze(o.element,t,{...i,path:[...i.path,"items"]})};function Wp(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Wp(t.out):t.type==="catch"?Wp(t.innerType):e._zod.optin}var tk=(e,t,r,i)=>{let n=r,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&Ut(e,t,n,i,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)er(n.properties,u,Ze(s[u],t,{...i,path:[...i.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=o.shape[u];(t.io==="input"?Wp(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),o.catchall?._zod.def.type==="never"?n.additionalProperties=!1:o.catchall?o.catchall&&(n.additionalProperties=Ze(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},mv=(e,t,r,i)=>{let n=e._zod.def,o=n.inclusive===!1,s=n.options.map((a,c)=>Ze(a,t,{...i,path:[...i.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=s:r.anyOf=s},rk=(e,t,r,i)=>{let n=e._zod.def,o=Ze(n.left,t,{...i,path:[...i.path,"allOf",0]}),s=Ze(n.right,t,{...i,path:[...i.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];r.allOf=c,t.intersections.push(c)},nk=(e,t,r,i)=>{let n=r,o=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((v,S)=>Ze(v,t,{...i,path:[...i.path,s,S]})),u=o.rest?Ze(o.rest,t,{...i,path:[...i.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,l=o.items.length;for(;l>0;){let v=o.items[l-1];if(!(t.io==="input"?Wp(v)!==void 0:v._zod.optout==="optional"))break;l--}let d=o.items.length,m=!o.rest;t.target==="draft-2020-12"?(n.prefixItems=c,m?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),m&&(n.maxItems=d)):t.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),m&&(n.maxItems=d)):(n.items=c,m?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),m&&(n.maxItems=d));let{minimum:f,maximum:g}=Lt(e);typeof f=="number"&&(n.minItems=f),typeof g=="number"&&(n.maxItems=g)};function PC(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let v=PC(e,g,r);return v===g?t:v}for(let g of["anyOf","oneOf"]){let v=t[g];if(!Array.isArray(v))continue;let S=v.map(b=>PC(e,b,r));S.some((b,_)=>b!==v[_])&&(t={...t,[g]:S})}let i=Array.isArray(t.type)?t.type:[t.type],n=!i.includes("string")&&i.some(g=>g==="number"||g==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!o?.some(g=>typeof g=="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:m,...f}=t;return f.enum?f.enum=f.enum.map(g=>typeof g=="number"?String(g):g):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",o||(f.pattern=(i.includes("number")?Do:Ap).source)),f}var TC=new WeakMap;function HSe(e){let t=new Map;for(let i of e.seen.values())i.def&&!t.has(i.schema)&&t.set(i.schema,i);let r=new Map;for(let i of TC.get(e)??[]){let n=e.seen.get(i),o=(n?.def??n?.schema)?.propertyNames;if(!o||o===!0||r.has(o))continue;let s=PC(t,o,new Set);s!==o&&r.set(o,s)}if(r.size)for(let i of e.seen.values())for(let n of[i.schema,i.def]){let o=n&&r.get(n.propertyNames);o&&(n.propertyNames=o)}}var ik=(e,t,r,i)=>{let n=r,o=e._zod.def;n.type="object";let s=o.keyType,a=Lt(s).patterns;if(o.mode==="loose"&&a&&a.size>0){let l=Ze(o.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)er(n.patternProperties,Z2(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=Ze(o.keyType,t,{...i,path:[...i.path,"propertyNames"]});let l=TC.get(t);l||(l=[],TC.set(t,l),t.deferred.push(()=>HSe(t))),l.push(e)}n.additionalProperties=Ze(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let c=s._zod.values,u=t.io==="input"&&Wp(o.valueType)!==void 0;if(c&&!o.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},ok=(e,t,r,i)=>{let n=e._zod.def,o=Ze(n.innerType,t,i),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},sk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType},ak=Symbol();function X2(e,t,r,i,n){let o=!1,s=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(Ut(t,r,i,n,"BigInt defaults cannot be represented in JSON Schema"),ak):JSON.parse(s)}var ck=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType;let s=X2(n.defaultValue,e,t,r,i);s!==ak&&(r.default=s)},uk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);if(o.ref=n.innerType,t.io!=="input")return;let s=X2(n.defaultValue,e,t,r,i);s!==ak&&(r._prefault=s)},lk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Ut(e,t,r,i,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},dk=(e,t,r,i)=>{let n=e._zod.def,o=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?n.out:n.in:n.out;Ze(s,t,i);let a=t.seen.get(e);a.ref=s},pk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType,r.readOnly=!0},fk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType},hv=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType},mk=(e,t,r,i)=>{let n=e._zod.innerType;Ze(n,t,i);let o=t.seen.get(e);o.ref=n},fv={string:CC,number:kC,boolean:DC,bigint:OC,symbol:NC,null:UC,undefined:LC,void:MC,never:zC,any:jC,unknown:FC,date:GC,enum:qC,literal:VC,nan:KC,template_literal:BC,file:HC,success:WC,custom:JC,function:ZC,transform:XC,map:YC,set:QC,array:ek,object:tk,union:mv,intersection:rk,tuple:nk,record:ik,nullable:ok,nonoptional:sk,default:ck,prefault:uk,catch:lk,pipe:dk,readonly:pk,promise:fk,optional:hv,lazy:mk};function gv(e,t){if("_idmap"in e){let i=e,n=ws({...t,processors:fv}),o={};for(let c of i._idmap.entries()){let[u,l]=c;Ze(l,n)}let s={},a={registry:i,uri:t?.uri,defs:o};n.external=a;for(let c of i._idmap.entries()){let[u,l]=c;bs(n,l),er(s,u,_s(n,l))}if(Object.keys(o).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:o}}return{schemas:s}}let r=ws({...t,processors:fv});return Ze(e,r),bs(r,e),_s(r,e)}var yv=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ws({processors:fv,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return Ze(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,bs(this.ctx,t);let i=_s(this.ctx,t),{"~standard":n,...o}=i;return o}};var Y2={};var tl={};it(tl,{ZodAny:()=>Uk,ZodArray:()=>jk,ZodBase64:()=>Uv,ZodBase64URL:()=>Lv,ZodBigInt:()=>Qu,ZodBigIntFormat:()=>jv,ZodBoolean:()=>Yu,ZodCIDRv4:()=>Ov,ZodCIDRv6:()=>Nv,ZodCUID:()=>Iv,ZodCUID2:()=>$v,ZodCatch:()=>aD,ZodCodec:()=>of,ZodCreditCard:()=>$k,ZodCustom:()=>sf,ZodCustomStringFormat:()=>uc,ZodDate:()=>Yp,ZodDefault:()=>tD,ZodDiscriminatedUnion:()=>Gk,ZodE164:()=>Mv,ZodEmail:()=>xv,ZodEmoji:()=>Av,ZodEnum:()=>Ju,ZodExactOptional:()=>Vv,ZodFile:()=>Xk,ZodFunction:()=>yD,ZodGUID:()=>Ev,ZodIBAN:()=>Pk,ZodIPv4:()=>kv,ZodIPv6:()=>Dv,ZodISODate:()=>Es,ZodISODateTime:()=>xs,ZodISODuration:()=>Rs,ZodISOTime:()=>As,ZodInstanceOf:()=>wD,ZodIntersection:()=>qk,ZodJWT:()=>zv,ZodKSUID:()=>Cv,ZodLazy:()=>mD,ZodLiteral:()=>Zk,ZodMAC:()=>Ik,ZodMap:()=>Wk,ZodNaN:()=>uD,ZodNanoID:()=>Rv,ZodNever:()=>Mk,ZodNonOptional:()=>Kv,ZodNull:()=>Ok,ZodNullable:()=>eD,ZodNumber:()=>Xu,ZodNumberFormat:()=>lc,ZodObject:()=>ef,ZodOptional:()=>rf,ZodPipe:()=>nf,ZodPrefault:()=>nD,ZodPreprocess:()=>lD,ZodPromise:()=>gD,ZodReadonly:()=>dD,ZodRecord:()=>Wu,ZodSet:()=>Jk,ZodString:()=>Zu,ZodStringFormat:()=>Xe,ZodSuccess:()=>sD,ZodSymbol:()=>kk,ZodTemplateLiteral:()=>fD,ZodTransform:()=>Yk,ZodTuple:()=>Kk,ZodType:()=>he,ZodULID:()=>Pv,ZodURL:()=>Xp,ZodUUID:()=>Li,ZodUndefined:()=>Dk,ZodUnion:()=>tf,ZodUnknown:()=>Lk,ZodVoid:()=>zk,ZodXID:()=>Tv,ZodXor:()=>Fk,_ZodString:()=>_v,_default:()=>rD,_function:()=>lG,any:()=>F6,array:()=>Qp,base64:()=>b6,base64url:()=>_6,bigint:()=>U6,boolean:()=>Ck,catch:()=>cD,check:()=>dG,cidrv4:()=>S6,cidrv6:()=>w6,codec:()=>sG,creditCard:()=>E6,cuid:()=>d6,cuid2:()=>p6,currencyCode:()=>T6,custom:()=>pG,date:()=>q6,describe:()=>fG,discriminatedUnion:()=>J6,e164:()=>x6,email:()=>t6,emoji:()=>u6,enum:()=>Gv,exactOptional:()=>Qk,file:()=>rG,float32:()=>k6,float64:()=>D6,function:()=>lG,guid:()=>r6,hash:()=>C6,hex:()=>P6,hostname:()=>$6,httpUrl:()=>c6,iban:()=>A6,instanceof:()=>hG,int:()=>wv,int32:()=>O6,int64:()=>L6,intersection:()=>Vk,invertCodec:()=>aG,ipv4:()=>g6,ipv6:()=>v6,json:()=>yG,jwt:()=>R6,keyof:()=>V6,ksuid:()=>h6,lazy:()=>hD,literal:()=>tG,looseObject:()=>H6,looseRecord:()=>X6,mac:()=>y6,map:()=>Y6,meta:()=>mG,nan:()=>oG,nanoid:()=>l6,nativeEnum:()=>eG,never:()=>Fv,nonoptional:()=>oD,null:()=>Nk,nullable:()=>Zp,nullish:()=>nG,number:()=>Tk,object:()=>K6,optional:()=>ac,partialRecord:()=>Z6,pipe:()=>bv,prefault:()=>iD,preprocess:()=>vG,promise:()=>uG,readonly:()=>pD,record:()=>Hk,refine:()=>vD,set:()=>Q6,strictObject:()=>B6,string:()=>Jp,stringFormat:()=>I6,stringbool:()=>gG,success:()=>iG,superRefine:()=>SD,symbol:()=>z6,templateLiteral:()=>cG,transform:()=>qv,tuple:()=>Bk,uint32:()=>N6,uint64:()=>M6,ulid:()=>f6,undefined:()=>j6,union:()=>el,unknown:()=>sc,url:()=>a6,uuid:()=>n6,uuidv4:()=>i6,uuidv6:()=>o6,uuidv7:()=>s6,void:()=>G6,xid:()=>m6,xor:()=>W6});var vv={};it(vv,{endsWith:()=>Lu,gt:()=>Ni,gte:()=>rn,includes:()=>Nu,length:()=>ic,lowercase:()=>Du,lt:()=>Oi,lte:()=>tn,maxLength:()=>nc,maxSize:()=>Ss,mime:()=>zu,minLength:()=>Oo,minSize:()=>Ui,multipleOf:()=>vs,negative:()=>uv,nonnegative:()=>dv,nonpositive:()=>lv,normalize:()=>ju,overwrite:()=>Qn,positive:()=>cv,properties:()=>Mu,property:()=>pv,regex:()=>ku,size:()=>rc,slugify:()=>Vu,startsWith:()=>Uu,toLowerCase:()=>Gu,toUpperCase:()=>qu,trim:()=>Fu,uppercase:()=>Ou});var Q2=new WeakSet([Object.prototype,Error.prototype]);function Sv(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let i=r(this);return Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0}),i},set(i){Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0})}})}var e6=(e,t)=>{g$.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Q2.has(r)||(Q2.add(r),Sv(r,"format",i=>n=>bp(i,n)),Sv(r,"flatten",i=>n=>wp(i,n)),Sv(r,"addIssue",i=>n=>{i.issues.push(n),i.message=JSON.stringify(i.issues,Su,2)}),Sv(r,"addIssues",i=>n=>{i.issues.push(...n),i.message=JSON.stringify(i.issues,Su,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},JSe=E("ZodError",e6),Hr=E("ZodError",e6,void 0,{Parent:Error});var hk=xu(Hr),gk=Eu(Hr),yk=Au(Hr),vk=Ru(Hr),Sk=Wg(Hr),wk=Jg(Hr),bk=Zg(Hr),_k=Xg(Hr),xk=Yg(Hr),Ek=Qg(Hr),Ak=ey(Hr),Rk=ty(Hr);function XSe(){qt.localeError||bt(Dy())}function cc(){qt.memoizer||bt({memoizer:zp()})}var he=E("ZodType",(e,t)=>(XSe(),ue.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(k.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return We(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(vD(e,t))},superRefine(e,t){return this.check(SD(e,t))},overwrite(e){return this.check(Qn(e))},optional(){return ac(this)},exactOptional(){return Qk(this)},nullable(){return Zp(this)},nullish(){return ac(Zp(this))},nonoptional(e){return oD(this,e)},array(){return Qp(this)},or(e){return el([this,e])},and(e){return Vk(this,e)},transform(e){return bv(this,qv(e))},default(e){return rD(this,e)},prefault(e){return iD(this,e)},catch(e){return cD(this,e)},pipe(e){return bv(this,e)},readonly(){return pD(this)},describe(e){let t=this.clone();return tr.add(t,{description:e}),t},meta(...e){if(e.length===0)return tr.get(this);let t=this.clone();return tr.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return k.hide(this,"~standard",{...py(this),jsonSchema:{input:Ku(this,"input"),output:Ku(this,"output")}})},set"~standard"(e){k.own(this,"~standard",e)},parse:function e(t,r){return hk(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await gk(this,t,r,{callee:e})},safeParse(e,t){return yk(this,e,t)},async safeParseAsync(e,t){return vk(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){k.own(this,"spa",e)},validate(e,t){return _p(this,e,t)},validateAsync(e,t){return xp(this,e,t)},encode:function e(t,r){return Sk(this,t,r,{callee:e})},decode:function e(t,r){return wk(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await bk(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await _k(this,t,r,{callee:e})},safeEncode(e,t){return xk(this,e,t)},safeDecode(e,t){return Ek(this,e,t)},async safeEncodeAsync(e,t){return Ak(this,e,t)},async safeDecodeAsync(e,t){return Rk(this,e,t)},toJSONSchema(e){return $C(this,{})(e)},get description(){return tr.get(this)?.description},get _def(){return this._zod.def}}),_v=E("_ZodString",(e,t)=>{Xa.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>CC(e,r,i,n)},k.derived({format:e=>Lt(e).format??null,minLength:e=>Lt(e).minimum??null,maxLength:e=>Lt(e).maximum??null},{regex(...e){return this.check(ku(...e))},includes(...e){return this.check(Nu(...e))},startsWith(...e){return this.check(Uu(...e))},endsWith(...e){return this.check(Lu(...e))},min(...e){return this.check(Oo(...e))},max(...e){return this.check(nc(...e))},length(...e){return this.check(ic(...e))},nonempty(...e){return this.check(Oo(1,...e))},lowercase(e){return this.check(Du(e))},uppercase(e){return this.check(Ou(e))},trim(){return this.check(Fu())},normalize(...e){return this.check(ju(...e))},toLowerCase(){return this.check(Gu())},toUpperCase(){return this.check(qu())},slugify(){return this.check(Vu())}})),Zu=E("ZodString",(e,t)=>{Xa.init(e,t),_v.init(e,t)},{email(e){return this.check(Fy(xv,e))},url(e){return this.check(Gp(Xp,e))},jwt(e){return this.check(av(zv,e))},emoji(e){return this.check(Hy(Av,e))},guid(e){return this.check(Gy(Ev,e))},uuid(e){return this.check(qy(Li,e))},uuidv4(e){return this.check(Vy(Li,e))},uuidv6(e){return this.check(Ky(Li,e))},uuidv7(e){return this.check(By(Li,e))},nanoid(e){return this.check(Wy(Rv,e))},cuid(e){return this.check(Jy(Iv,e))},cuid2(e){return this.check(Zy($v,e))},ulid(e){return this.check(Xy(Pv,e))},base64(e){return this.check(iv(Uv,e))},base64url(e){return this.check(ov(Lv,e))},xid(e){return this.check(Yy(Tv,e))},ksuid(e){return this.check(Qy(Cv,e))},ipv4(e){return this.check(ev(kv,e))},ipv6(e){return this.check(tv(Dv,e))},cidrv4(e){return this.check(rv(Ov,e))},cidrv6(e){return this.check(nv(Nv,e))},e164(e){return this.check(sv(Mv,e))},datetime(e){return this.check(qp(xs,e))},date(e){return this.check(Vp(Es,e))},time(e){return this.check(Kp(As,e))},duration(e){return this.check(Bp(Rs,e))}});function Jp(e){return VT(Zu,e)}var Xe=E("ZodStringFormat",(e,t)=>{Je.init(e,t),_v.init(e,t)}),xs=E("ZodISODateTime",(e,t)=>{UP.init(e,t),Xe.init(e,t)}),Es=E("ZodISODate",(e,t)=>{LP.init(e,t),Xe.init(e,t)}),As=E("ZodISOTime",(e,t)=>{MP.init(e,t),Xe.init(e,t)}),Rs=E("ZodISODuration",(e,t)=>{zP.init(e,t),Xe.init(e,t)}),xv=E("ZodEmail",(e,t)=>{AP.init(e,t),Xe.init(e,t)});function t6(e){return Fy(xv,e)}var Ev=E("ZodGUID",(e,t)=>{xP.init(e,t),Xe.init(e,t)});function r6(e){return Gy(Ev,e)}var Li=E("ZodUUID",(e,t)=>{EP.init(e,t),Xe.init(e,t)});function n6(e){return qy(Li,e)}function i6(e){return Vy(Li,e)}function o6(e){return Ky(Li,e)}function s6(e){return By(Li,e)}var Xp=E("ZodURL",(e,t)=>{$P.init(e,t),Xe.init(e,t)});function a6(e){return Gp(Xp,e)}function c6(e){return Gp(Xp,{protocol:Ep,hostname:z$,...k.normalizeParams(e)})}var Av=E("ZodEmoji",(e,t)=>{PP.init(e,t),Xe.init(e,t)});function u6(e){return Hy(Av,e)}var Rv=E("ZodNanoID",(e,t)=>{TP.init(e,t),Xe.init(e,t)});function l6(e){return Wy(Rv,e)}var Iv=E("ZodCUID",(e,t)=>{CP.init(e,t),Xe.init(e,t)});function d6(e){return Jy(Iv,e)}var $v=E("ZodCUID2",(e,t)=>{kP.init(e,t),Xe.init(e,t)});function p6(e){return Zy($v,e)}var Pv=E("ZodULID",(e,t)=>{DP.init(e,t),Xe.init(e,t)});function f6(e){return Xy(Pv,e)}var Tv=E("ZodXID",(e,t)=>{OP.init(e,t),Xe.init(e,t)});function m6(e){return Yy(Tv,e)}var Cv=E("ZodKSUID",(e,t)=>{NP.init(e,t),Xe.init(e,t)});function h6(e){return Qy(Cv,e)}var kv=E("ZodIPv4",(e,t)=>{jP.init(e,t),Xe.init(e,t)});function g6(e){return ev(kv,e)}var Ik=E("ZodMAC",(e,t)=>{GP.init(e,t),Xe.init(e,t)});function y6(e){return BT(Ik,e)}var Dv=E("ZodIPv6",(e,t)=>{FP.init(e,t),Xe.init(e,t)});function v6(e){return tv(Dv,e)}var Ov=E("ZodCIDRv4",(e,t)=>{qP.init(e,t),Xe.init(e,t)});function S6(e){return rv(Ov,e)}var Nv=E("ZodCIDRv6",(e,t)=>{VP.init(e,t),Xe.init(e,t)});function w6(e){return nv(Nv,e)}var Uv=E("ZodBase64",(e,t)=>{KP.init(e,t),Xe.init(e,t)});function b6(e){return iv(Uv,e)}var Lv=E("ZodBase64URL",(e,t)=>{BP.init(e,t),Xe.init(e,t)});function _6(e){return ov(Lv,e)}var Mv=E("ZodE164",(e,t)=>{HP.init(e,t),Xe.init(e,t)});function x6(e){return sv(Mv,e)}var $k=E("ZodCreditCard",(e,t)=>{WP.init(e,t),Xe.init(e,t)});function E6(e){return HT($k,e)}var Pk=E("ZodIBAN",(e,t)=>{JP.init(e,t),Xe.init(e,t)});function A6(e){return WT(Pk,e)}var zv=E("ZodJWT",(e,t)=>{ZP.init(e,t),Xe.init(e,t)});function R6(e){return av(zv,e)}var uc=E("ZodCustomStringFormat",(e,t)=>{XP.init(e,t),Xe.init(e,t)});function I6(e,t,r={}){return oc(uc,e,t,r)}function $6(e){return oc(uc,"hostname",M$,e)}function P6(e){return oc(uc,"hex",Q$,e)}function T6(e){return oc(uc,"currency_code",F$,e)}function C6(e,t){let r=t?.enc??"hex",i=`${e}_${r}`,n=xn[i];if(!n)throw new Error(`Unrecognized hash format: ${i}`);return oc(uc,i,n,t)}var Xu=E("ZodNumber",(e,t)=>{_y.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>kC(e,r,i,n),e.isFinite=!0},k.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=Lt(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=Lt(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=Lt(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>Lt(e).format??null},{gt(e,t){return this.check(Ni(e,t))},gte(e,t){return this.check(rn(e,t))},min(e,t){return this.check(rn(e,t))},lt(e,t){return this.check(Oi(e,t))},lte(e,t){return this.check(tn(e,t))},max(e,t){return this.check(tn(e,t))},int(e){return this.check(wv(e))},safe(e){return this.check(wv(e))},positive(e){return this.check(Ni(0,e))},nonnegative(e){return this.check(rn(0,e))},negative(e){return this.check(Oi(0,e))},nonpositive(e){return this.check(tn(0,e))},multipleOf(e,t){return this.check(vs(e,t))},step(e,t){return this.check(vs(e,t))},finite(){return this}}));function Tk(e){return ZT(Xu,e)}var lc=E("ZodNumberFormat",(e,t)=>{YP.init(e,t),Xu.init(e,t)});function wv(e){return YT(lc,e)}function k6(e){return QT(lc,e)}function D6(e){return eC(lc,e)}function O6(e){return tC(lc,e)}function N6(e){return rC(lc,e)}var Yu=E("ZodBoolean",(e,t)=>{Dp.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>DC(e,r,i,n)});function Ck(e){return nC(Yu,e)}var Qu=E("ZodBigInt",(e,t)=>{xy.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>OC(e,r,i,n)},k.derived({minValue:e=>Lt(e).minimum??null,maxValue:e=>Lt(e).maximum??null,format:e=>Lt(e).format??null},{gte(e,t){return this.check(rn(e,t))},min(e,t){return this.check(rn(e,t))},gt(e,t){return this.check(Ni(e,t))},lt(e,t){return this.check(Oi(e,t))},lte(e,t){return this.check(tn(e,t))},max(e,t){return this.check(tn(e,t))},positive(e){return this.check(Ni(BigInt(0),e))},negative(e){return this.check(Oi(BigInt(0),e))},nonpositive(e){return this.check(tn(BigInt(0),e))},nonnegative(e){return this.check(rn(BigInt(0),e))},multipleOf(e,t){return this.check(vs(e,t))}}));function U6(e){return oC(Qu,e)}var jv=E("ZodBigIntFormat",(e,t)=>{QP.init(e,t),Qu.init(e,t)});function L6(e){return aC(jv,e)}function M6(e){return cC(jv,e)}var kk=E("ZodSymbol",(e,t)=>{eT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>NC(e,r,i,n)});function z6(e){return uC(kk,e)}var Dk=E("ZodUndefined",(e,t)=>{tT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>LC(e,r,i,n)});function j6(e){return lC(Dk,e)}var Ok=E("ZodNull",(e,t)=>{rT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>UC(e,r,i,n)});function Nk(e){return dC(Ok,e)}var Uk=E("ZodAny",(e,t)=>{nT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>jC(e,r,i,n)});function F6(){return pC(Uk)}var Lk=E("ZodUnknown",(e,t)=>{iT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>FC(e,r,i,n)});function sc(){return fC(Lk)}var Mk=E("ZodNever",(e,t)=>{oT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>zC(e,r,i,n)});function Fv(e){return mC(Mk,e)}var zk=E("ZodVoid",(e,t)=>{sT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>MC(e,r,i,n)});function G6(e){return hC(zk,e)}var Yp=E("ZodDate",(e,t)=>{aT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>GC(e,r,i,n),e.min=(r,i)=>e.check(rn(r,i)),e.max=(r,i)=>e.check(tn(r,i))},k.derived({minDate:e=>{let{minimum:t}=Lt(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=Lt(e);return t?new Date(t):null}},{}));function q6(e){return gC(Yp,e)}var jk=E("ZodArray",(e,t)=>{cc(),cT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ek(e,r,i,n),e.element=t.element},{min(e,t){return this.check(Oo(e,t))},nonempty(e){return this.check(Oo(1,e))},max(e,t){return this.check(nc(e,t))},length(e,t){return this.check(ic(e,t))},unwrap(){return this.element}});function Qp(e,t){return SC(jk,e,t)}function V6(e){let t=e._zod.def.shape;return Gv(Object.keys(t))}var ef=E("ZodObject",(e,t)=>{cc(),uT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>tk(e,r,i,n),k.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Gv(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(k.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(k.mergeDefs(this._zod.def,{catchall:sc()}))},loose(){return this.clone(k.mergeDefs(this._zod.def,{catchall:sc()}))},strict(){return this.clone(k.mergeDefs(this._zod.def,{catchall:Fv()}))},strip(){return this.clone(k.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return k.extend(this,e)},safeExtend(e){return k.safeExtend(this,e)},merge(e){return k.merge(this,e)},pick(e){return k.pick(this,e)},omit(e){return k.omit(this,e)},partial(...e){return k.partial(rf,this,e[0])},exactPartial(...e){return k.partial(Vv,this,e[0],"exactPartial")},required(...e){return k.required(Kv,this,e[0])}});function K6(e,t){let r={type:"object",shape:e??{},...k.normalizeParams(t)};return new ef(r)}function B6(e,t){return new ef({type:"object",shape:e,catchall:Fv(),...k.normalizeParams(t)})}function H6(e,t){return new ef({type:"object",shape:e,catchall:sc(),...k.normalizeParams(t)})}var tf=E("ZodUnion",(e,t)=>{Op.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>mv(e,r,i,n),e.options=t.options});function el(e,t){return new tf({type:"union",options:e,...k.normalizeParams(t)})}var Fk=E("ZodXor",(e,t)=>{tf.init(e,t),lT.init(e,t),e._zod.processJSONSchema=(r,i,n)=>mv(e,r,i,n),e.options=t.options});function W6(e,t){return new Fk({type:"union",options:e,inclusive:!1,...k.normalizeParams(t)})}var Gk=E("ZodDiscriminatedUnion",(e,t)=>{tf.init(e,t),pT.init(e,t)});function J6(e,t,r){return new Gk({type:"union",options:t,discriminator:e,...k.normalizeParams(r)})}var qk=E("ZodIntersection",(e,t)=>{fT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>rk(e,r,i,n)});function Vk(e,t){return new qk({type:"intersection",left:e,right:t})}var Kk=E("ZodTuple",(e,t)=>{cc(),Ey.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>nk(e,r,i,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new rf({type:"optional",innerType:t}))})}});function Bk(e,t,r){let i=t instanceof ue,n=i?r:t,o=i?t:null;return new Kk({type:"tuple",items:e,rest:o,...k.normalizeParams(n)})}var Wu=E("ZodRecord",(e,t)=>{cc(),mT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ik(e,r,i,n),e.keyType=t.keyType,e.valueType=t.valueType});function Hk(e,t,r){return!t||!t._zod?new Wu({type:"record",keyType:Jp(),valueType:e,...k.normalizeParams(t)}):new Wu({type:"record",keyType:e,valueType:t,...k.normalizeParams(r)})}function Z6(e,t,r){return new Wu({type:"record",keyType:e,valueType:t,...k.normalizeParams(r),partial:!0})}function X6(e,t,r){return new Wu({type:"record",keyType:e,valueType:t,mode:"loose",...k.normalizeParams(r)})}var Wk=E("ZodMap",(e,t)=>{cc(),hT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>YC(e,r,i,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ui(...r)),e.nonempty=r=>e.check(Ui(1,r)),e.max=(...r)=>e.check(Ss(...r)),e.size=(...r)=>e.check(rc(...r))});function Y6(e,t,r){return new Wk({type:"map",keyType:e,valueType:t,...k.normalizeParams(r)})}var Jk=E("ZodSet",(e,t)=>{cc(),gT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>QC(e,r,i,n),e.min=(...r)=>e.check(Ui(...r)),e.nonempty=r=>e.check(Ui(1,r)),e.max=(...r)=>e.check(Ss(...r)),e.size=(...r)=>e.check(rc(...r))});function Q6(e,t){return new Jk({type:"set",valueType:e,...k.normalizeParams(t)})}var Ju=E("ZodEnum",(e,t)=>{yT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(i,n,o)=>qC(e,i,n,o),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(i,n)=>{let o={};for(let s of i)if(r.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Ju({...t,checks:[],...k.normalizeParams(n),entries:o})},e.exclude=(i,n)=>{let o={...t.entries};for(let s of i)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Ju({...t,checks:[],...k.normalizeParams(n),entries:o})}});function Gv(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new Ju({type:"enum",entries:r,...k.normalizeParams(t)})}function eG(e,t){return new Ju({type:"enum",entries:e,...k.normalizeParams(t)})}var Zk=E("ZodLiteral",(e,t)=>{vT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>VC(e,r,i,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function tG(e,t){return new Zk({type:"literal",values:Array.isArray(e)?e:[e],...k.normalizeParams(t)})}var Xk=E("ZodFile",(e,t)=>{ST.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>HC(e,r,i,n),e.min=(r,i)=>e.check(Ui(r,i)),e.max=(r,i)=>e.check(Ss(r,i)),e.mime=(r,i)=>e.check(zu(Array.isArray(r)?r:[r],i))});function rG(e){return wC(Xk,e)}var Yk=E("ZodTransform",(e,t)=>{cc(),wT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>XC(e,r,i,n),e._zod.parse=(r,i)=>{if(i.direction==="backward")throw new ys(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(k.issue(o,r.value,t));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=e),r.issues.push(k.issue(s))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(o=>(r.value=o,r)):(r.value=n,r)}});function qv(e){return new Yk({type:"transform",transform:e})}var rf=E("ZodOptional",(e,t)=>{Ay.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>hv(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function ac(e){return new rf({type:"optional",innerType:e})}var Vv=E("ZodExactOptional",(e,t)=>{bT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>hv(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function Qk(e){return new Vv({type:"optional",innerType:e})}var eD=E("ZodNullable",(e,t)=>{_T.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ok(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function Zp(e){return new eD({type:"nullable",innerType:e})}function nG(e){return ac(Zp(e))}var tD=E("ZodDefault",(e,t)=>{xT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ck(e,r,i,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function rD(e,t){return new tD({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():k.shallowClone(t)}})}var nD=E("ZodPrefault",(e,t)=>{ET.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>uk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function iD(e,t){return new nD({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():k.shallowClone(t)}})}var Kv=E("ZodNonOptional",(e,t)=>{AT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>sk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function oD(e,t){return new Kv({type:"nonoptional",innerType:e,...k.normalizeParams(t)})}var sD=E("ZodSuccess",(e,t)=>{RT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>WC(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function iG(e){return new sD({type:"success",innerType:e})}var aD=E("ZodCatch",(e,t)=>{IT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>lk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function cD(e,t){return new aD({type:"catch",innerType:e,catchValue:typeof t=="function"?t:k.constantCatch(t)})}var uD=E("ZodNaN",(e,t)=>{$T.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>KC(e,r,i,n)});function oG(e){return vC(uD,e)}var nf=E("ZodPipe",(e,t)=>{Ry.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>dk(e,r,i,n),e.in=t.in,e.out=t.out});function bv(e,t){return new nf({type:"pipe",in:e,out:t})}var of=E("ZodCodec",(e,t)=>{nf.init(e,t),Np.init(e,t)});function sG(e,t,r){return new of({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function aG(e){let t=e._zod.def;return new of({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var lD=E("ZodPreprocess",(e,t)=>{nf.init(e,t),PT.init(e,t)}),dD=E("ZodReadonly",(e,t)=>{TT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>pk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function pD(e){return new dD({type:"readonly",innerType:e})}var fD=E("ZodTemplateLiteral",(e,t)=>{CT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>BC(e,r,i,n)});function cG(e,t){return new fD({type:"template_literal",parts:e,...k.normalizeParams(t)})}var mD=E("ZodLazy",(e,t)=>{Up.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>mk(e,r,i,n),e.unwrap=()=>e._zod.def.getter()});function hD(e){return new mD({type:"lazy",getter:e})}var gD=E("ZodPromise",(e,t)=>{DT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>fk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function uG(e){return new gD({type:"promise",innerType:e})}var yD=E("ZodFunction",(e,t)=>{kT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ZC(e,r,i,n)});function lG(e){return new yD({type:"function",input:Array.isArray(e?.input)?Bk(e?.input):e?.input??Qp(sc()),output:e?.output??sc()})}var sf=E("ZodCustom",(e,t)=>{OT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>JC(e,r,i,n)});function dG(e){let t=new rt({check:"custom"});return t._zod.check=e,t}function pG(e,t){return bC(sf,e??(()=>!0),t)}function vD(e,t={}){return _C(sf,e,t)}function SD(e,t){return xC(e,t)}var fG=EC,mG=AC,wD=E("ZodInstanceOf",(e,t)=>{sf.init(e,t)},{properties(e,t){return this.check(Mu(e,t))}});function hG(e,t={}){let r=new wD({type:"custom",check:"custom",fn:i=>i instanceof e,abort:!0,...k.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=i=>{i.value instanceof e||i.issues.push({code:"invalid_type",expected:e.name,input:i.value,inst:r,path:[...r._zod.def.path??[]]})},r}var gG=(...e)=>RC({Codec:of,Boolean:Yu,String:Zu},...e);function yG(e){let t=hD(()=>el([Jp(e),Tk(),Ck(),Nk(),Qp(t),Hk(Jp(),t)]));return t}function vG(e,t){return new lD({type:"pipe",in:qv(e),out:t})}var YSe={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 QSe(e){bt({customError:e})}function ewe(){return bt().customError}var bD;bD||(bD={});var af={};it(af,{ZodISODate:()=>Es,ZodISODateTime:()=>xs,ZodISODuration:()=>Rs,ZodISOTime:()=>As,date:()=>rwe,datetime:()=>twe,duration:()=>iwe,time:()=>nwe});function twe(e){return qp(xs,e)}function rwe(e){return Vp(Es,e)}function nwe(e){return Kp(As,e)}function iwe(e){return Bp(Rs,e)}var V={...tl,...vv,iso:af},owe=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 swe(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function SG(e,t){return e.map((r,i)=>i<t?r:r.optional())}function awe(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function cwe(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let i=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===i){let n=r[1]===void 0?void 0:awe(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function uwe(e,t){return V.transform(i=>i).check(i=>{let n=i.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let o=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&o.length<t.minProperties&&i.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&i.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let s of o){let a=t.keySchema.safeParse(s);a.success||i.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(e)}function _D(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let i=String(e);return`${r[0]}${i.length}:${i}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let o=[];for(let s of e){let a=_D(s,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}let i=Object.keys(e).sort(),n=[];for(let o of i){let s=_D(e[o],t);if(s===null)return null;n.push(`${o.length}:${o}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var lwe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),dwe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function cf(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(cf):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>lwe.has(t)?cf(r):!dwe.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(cf))}function wG(e){return e===1?"element":"elements"}function pwe(e,t){return V.transform(i=>i).check(i=>{let n=i.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let o=new Map;for(let s=0;s<n.length;s++){let a=_D(n[s],new Set);if(a===null)continue;let c=o.get(a);if(c===void 0){o.set(a,s);continue}i.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(t.containsSchema){let o=t.minContains??1,s=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(t.containsSchema.safeParse(c).success&&++a>=s)break;a<o&&i.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${wG(o)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&i.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${wG(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function bG(e,t){if(e!==!1)return e===void 0||e===!0?V.any():Dr(e,t)}var fwe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function _G(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return V.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return V.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let o=cwe(n,t),s=Dr(o,t);return t.refs.set(n,s),t.processing.delete(n),s}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return 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 o=n.map(s=>V.literal(s));return o.length<2?o[0]:V.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return V.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(o=>{let s={...e,type:o};return _G(s,t)});return n.length===0?V.never():n.length===1?n[0]:V.union(n)}if(!r)return V.any();let i;switch(r){case"string":{let n=V.string();if(e.format){let o=e.format;o==="email"?n=n.check(V.email()):o==="uri"||o==="uri-reference"?n=n.check(V.url()):o==="uuid"||o==="guid"?n=n.check(V.uuid()):o==="date-time"?n=n.check(V.iso.datetime({offset:!0})):o==="date"?n=n.check(V.iso.date()):o==="time"?n=n.check(V.regex(fwe)):o==="duration"?n=n.check(V.iso.duration()):o==="hostname"?n=n.check(V.hostname()):o==="ipv4"?n=n.check(V.ipv4()):o==="ipv6"?n=n.check(V.ipv6()):o==="mac"?n=n.check(V.mac()):o==="cidr"?n=n.check(V.cidrv4()):o==="cidr-v6"?n=n.check(V.cidrv6()):o==="base64"?n=n.check(V.base64()):o==="base64url"?n=n.check(V.base64url()):o==="e164"?n=n.check(V.e164()):o==="credit_card"?n=n.check(V.creditCard()):o==="iban"?n=n.check(V.iban()):o==="jwt"?n=n.check(V.jwt()):o==="emoji"?n=n.check(V.emoji()):o==="nanoid"?n=n.check(V.nanoid()):o==="cuid"?n=n.check(V.cuid()):o==="cuid2"?n=n.check(V.cuid2()):o==="ulid"?n=n.check(V.ulid()):o==="xid"?n=n.check(V.xid()):o==="ksuid"&&(n=n.check(V.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),i=n;break}case"number":case"integer":{let n=r==="integer"?V.number().int():V.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),i=n;break}case"boolean":{i=V.boolean();break}case"null":{i=V.null();break}case"object":{let n={},o=e.properties||{},s=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Dr(e.additionalProperties,t):void 0;for(let[d,m]of Object.entries(o)){let f=Dr(m,t);er(n,d,s.has(d)?f:f.optional())}if(e.patternProperties){let d=e.patternProperties,m=Object.keys(d),f=[];for(let v of m){let S=Dr(d[v],t),b=V.string().regex(new RegExp(v));f.push(V.looseRecord(b,S))}let g=[];if(Object.keys(n).length>0&&g.push(V.object(n).passthrough()),g.push(...f),g.length===0)i=V.object({}).passthrough();else if(g.length===1)i=g[0];else{let v=V.intersection(g[0],g[1]);for(let S=2;S<g.length;S++)v=V.intersection(v,g[S]);i=v}if(e.additionalProperties===!1){let v=Object.keys(n),S=m.map(_=>new RegExp(_)),b=i;i=i.check(_=>{if(!bn(_.value))return;let x=[];for(let T of Object.keys(_.value))v.includes(T)||S.some(U=>U.test(T))||x.push(T);x.length&&_.issues.push({code:"unrecognized_keys",keys:x,input:_.value,inst:b})})}}else{let d=V.object(n);e.additionalProperties===!1?i=d.strict():a?i=d.catchall(a):i=d.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=Dr(m,t)}i=uwe(i,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=e.prefixItems,o=e.items;if(n&&Array.isArray(n)){let s=typeof e.minItems=="number"?e.minItems:0,a=n.map(d=>Dr(d,t)),c=SG(a,s),u=Array.isArray(o)?void 0:bG(o,t),l=V.tuple(c);i=u?l.rest(u):l,typeof e.minItems=="number"&&(i=i.check(V.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(V.maxLength(e.maxItems)))}else if(Array.isArray(o)){let s=typeof e.minItems=="number"?e.minItems:0,a=o.map(d=>Dr(d,t)),c=SG(a,s),u=bG(e.additionalItems,t),l=V.tuple(c);i=u?l.rest(u):l,typeof e.minItems=="number"&&(i=i.check(V.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(V.maxLength(e.maxItems)))}else if(o!==void 0){let s=Dr(o,t),a=V.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),i=a}else i=V.array(V.any());(e.uniqueItems===!0||e.contains!==void 0)&&(i=pwe(i,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Dr(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return i}function Dr(e,t){if(typeof e=="boolean")return e?V.any():V.never();let r=_G(e,t),i=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Dr(u,t)),c=V.union(a);r=i?V.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Dr(u,t)),c=V.xor(a);r=i?V.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=i?r:V.any();else{let a=i?r:Dr(e.allOf[0],t),c=i?0:1;for(let u=c;u<e.allOf.length;u++)a=V.intersection(a,Dr(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=V.nullable(r)),e.readOnly===!0&&(r=V.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in e&&(n[a]=e[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in e&&(n[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!cf(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(n[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!cf(e.contains)&&(n.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(n[a]=e[a])}for(let a of Object.keys(e))owe.has(a)||er(n,a,e[a]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function xG(e,t){if(typeof e=="boolean")return e?V.any():V.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let i=swe(r,t?.defaultTarget),n=r.$defs||r.definitions||{},o={version:i,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??tr};return Dr(r,o)}var EG=Symbol("z.visit/resolving");function uf(e,t){let r=typeof t=="function"?t:(s,a)=>{let c=t[s._zod.def.type];return c?c(s,a):s},i=new Map;function n(s){let a=i.get(s);if(a===EG)return new Up({type:"lazy",getter:()=>i.get(s)});if(a!==void 0)return a;i.set(s,EG);let c=o(s),u=r(c,c!==s);return i.set(s,u),u}function o(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,m={};for(let g of l){let v=n(u[g]);v!==u[g]&&(d=!0),m[g]=v}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?We(s,{...a,shape:m,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:We(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let g=n(f);g!==f&&(l=!0),d.push(g)}let m=a.rest;return a.rest&&(m=n(a.rest),m!==a.rest&&(l=!0)),l?We(s,{...a,items:d,rest:m}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:We(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:We(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let m of u){let f=n(m);f!==m&&(l=!0),d.push(f)}return l?We(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:We(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:We(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:We(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:We(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return We(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(e)}function AG(e){return uf(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:el(r.options)}})}function mwe(e,t){if(!t?.length)return e;let r=e._zod.def;return We(e,Xn(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function RG(e){return mwe(e.out,e.checks)}function hwe(e){return e.in._zod.traits.has("$ZodTransform")?RG(e):e.in}function IG(e){return uf(e,{pipe:t=>hwe(t._zod.def),default:(t,r)=>r?ac(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function $G(e){return uf(e,{pipe:t=>RG(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var xD={};it(xD,{bigint:()=>Swe,boolean:()=>vwe,date:()=>wwe,number:()=>ywe,string:()=>gwe});function gwe(e){return KT(Zu,e)}function ywe(e){return XT(Xu,e)}function vwe(e){return iC(Yu,e)}function Swe(e){return sC(Qu,e)}function wwe(e){return yC(Yp,e)}typeof window<"u"&&p.config({jitless:!0});function bwe(e){let t=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(e.trim());if(!t)return null;try{let r=Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)),i=new DataView(r.buffer),n=0,o=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=i.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(o())!==t[1])return null;if(t[1]==="ssh-ed25519"){if(o().length!==32)return null}else if(t[1]==="ssh-rsa"){let a=o(),c=o();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(o()),c=o(),u={nistp256:65,nistp384:97,nistp521:133};if(t[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var PG=p.string().trim().max(8192).refine(e=>bwe(e)!==null,"Use an OpenSSH public key from a .pub file."),Bv=p.object({authorizedKeys:p.array(PG).max(32)}).strict(),n9e=Bv.extend({revision:p.number().int().positive().optional()}),ED=Bv.extend({host:p.string().min(1).max(253).nullable(),port:p.number().int().min(1).max(65535),username:p.string().regex(/^[a-z_][a-z0-9_-]*$/),workingDirectory:p.string().startsWith("/").max(4096),hostKey:PG.nullable(),fingerprint:p.string().nullable(),revision:p.number().int().positive(),appliedRevision:p.number().int().nonnegative(),activeSessions:p.number().int().min(0).max(1024)}).strict(),i9e=ED.extend({state:p.enum(["starting","configuring","ready","disabled","stopped"])});var rl=new TextEncoder,nl=new TextDecoder,TG=new TextDecoder("utf-8",{fatal:!0}),Hv=2**32;function Or(...e){let t=e.reduce((n,{length:o})=>n+o,0),r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r}function AD(e,t,r){if(t<0||t>=Hv)throw new RangeError(`value must be >= 0 and <= ${Hv-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function RD(e){let t=Math.floor(e/Hv),r=e%Hv,i=new Uint8Array(8);return AD(i,t,0),AD(i,r,4),i}function Wv(e){let t=new Uint8Array(4);return AD(t,e),t}var _we=/[^\x00-\x7f]/;function rr(e){if(typeof e=="string"&&e.length>=128){if(_we.test(e))throw new TypeError("non-ASCII string encountered in encode()");return rl.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=i}return t}function CG(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,i=[];for(let o=0;o<e.length;o+=r)i.push(String.fromCharCode.apply(null,e.subarray(o,o+r)));let n=btoa(i.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function kG(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),i=new Uint8Array(r.length);for(let n=0;n<r.length;n++)i[n]=r.charCodeAt(n);return i}async function Jv(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}var Uo=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var dc=class extends Uo{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},dt=class extends Uo{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Is=class extends Uo{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}},F=class extends Uo{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},pt=class extends Uo{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var lf=class extends Uo{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var Zv=class extends Uo{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var xwe="The input to be decoded is not correctly encoded.";function pc(e){try{return kG(typeof e=="string"?e:nl.decode(e),!0)}catch(t){throw new TypeError(xwe,{cause:t})}}function gt(e){return CG(typeof e=="string"?rl.encode(e):e,!0)}function nn(e,t){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be an instance of Uint8Array`)}function Pt(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function $s(...e){let t=new Set;for(let r of e)if(r)for(let i of Object.keys(r)){if(t.has(i))return!1;t.add(i)}return!0}function En(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}function Wr(e,t,r){try{return pc(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function Xv(e,t,r){try{return rr(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}function il(e,t,r){let i;try{i=JSON.parse(TG.decode(pc(e)))}catch{throw new t(r)}if(!Pt(i))throw new t(r);return i}var Yv={__proto__:null,b64:!0},Qv={__proto__:null};function df(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function eS(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Ps(e,t,r,i,n){if(n.crit!==void 0&&i?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||i.crit===void 0)return[];if(!Array.isArray(i.crit)||i.crit.length===0||i.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o=r===void 0?t:{__proto__:null,...r,...t};for(let s of i.crit){if(!(s in o))throw new dt(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o[s]&&(!Object.hasOwn(i,s)||i[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return i.crit}function tS(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new pt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function fc(e,t){let r,i;try{r=JSON.stringify(t),i=JSON.parse(r)}catch(n){throw new e("JOSE Header is not valid JSON",{cause:n})}if(!Pt(i))throw new e("JOSE Header is not a JSON object");return[i,r]}var Ewe=e=>e[Symbol.toStringTag],Awe=(e,t,r)=>{let{alg:i}=e;if(t.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==i)throw new TypeError(`Invalid key for this operation, its "alg" must be "${i}" when present`);if(Array.isArray(t.key_ops)){let n=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function ei(e,t,r){let{alg:i,secret:n}=e,o=r==="decrypt"||r==="sign";if(n&&t instanceof Uint8Array)return t;let s,a;if(Pt(t)){if(s=kD(t),typeof s.kty!="string")throw DG(i,t,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(o?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 ${o?"private":"public"} JWK`);if(Awe(e,s,r),s.kty==="oct")return pc(s.k);if(!Object.isFrozen(t)){let{key_ops:l}=t;Array.isArray(l)&&Object.freeze(l),Object.freeze(t)}}else{if(!PD(t))throw DG(i,t,n);let l=n?"secret":o?"private":"public";if(t.type!==l&&(n||["secret","public","private"].includes(t.type)))throw new TypeError(`${Ewe(t)} instances must be of type "${l}" for the ${i} algorithm`);if(Ts(t))return t;if(a=t,a.type==="secret")return a.export()}ID||=new WeakMap;let c=t,u=ID.get(c);if(u?.[i])return u[i];if(u||ID.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Rwe[a.asymmetricKeyDetails?.namedCurve],m=e.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[i]=a.toCryptoKey(m,l,e.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=i,u[i]=await sl(e,s)}var ID,Rwe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function nS(e){if(!Ts(e))throw new Error("CryptoKey instance expected")}var Ts=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},$D=e=>e?.[Symbol.toStringTag]==="KeyObject",PD=e=>Ts(e)||$D(e);function OG(e,t,...r){if(r.length>2){let i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Lo=(e,...t)=>OG("Key must be ",e,...t);function DG(e,t,r){let i=["CryptoKey","KeyObject","JSON Web Key"];return r&&i.push("Uint8Array"),new TypeError(OG(`Key for the ${e} algorithm must be `,t,...i))}var rS=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function TD(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ol(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function CD(e,t,r){let i=e.algorithm;if(i.name!==t.name)throw rS(t.name);if(t.hash&&i.hash?.name!==t.hash)throw rS(t.hash,"algorithm.hash");if(t.namedCurve&&i.namedCurve!==t.namedCurve)throw rS(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&i.length!==t.length)throw rS(t.length,"algorithm.length");TD(e,r)}function iS(e){return{__proto__:null,...e}}function kD(e){let t=iS(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,i=Array.isArray(r)?[...r]:void 0;if(!i||i.some(n=>typeof n!="string")||new Set(i).size!==i.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=i}return t}function NG(e){if(e!==void 0&&typeof e!="boolean")throw new TypeError('"extractable" option must be a boolean');return e}async function sl(e,t,r){if(!e.kty.includes(t.kty))throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let i=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),o={...t,ext:r??t.ext};return o.kty!=="AKP"&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,i,o.ext??!n,t.key_ops??e.usages[n?1:0])}async function ti(e,t,r,i=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,i,[r])),CD(e,t,r),e}var mc=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function oS(e,t){let r=e.byteLength<<3;if(r!==t)throw new F(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var Iwe=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function UG(e,t){if(t.length<<3!==e.ivBits)throw new F("Invalid Initialization Vector length")}async function LG(e,t,r){if(!(t instanceof Uint8Array))throw new TypeError(Lo(t,"Uint8Array"));let i=e.cekBits>>1,n=await crypto.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,[r]),o=await crypto.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]);return[n,o,i]}async function MG(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function $we(e,t,r,i,n){let[o,s,a]=await LG(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:i,name:"AES-CBC"},o,t)),u=Or(n,i,c,RD(n.length*8)),l=await MG(s,u,a);return{ciphertext:c,tag:l,iv:i}}async function Pwe(e,t){let r={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,i,e);return crypto.subtle.verify(r,i,n,t)}async function Twe(e,t,r,i,n,o){let[s,a,c]=await LG(e,t,"decrypt"),u=Or(o,i,r,RD(o.length*8)),l=await MG(a,u,c);try{if(await Pwe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:i,name:"AES-CBC"},s,r))}catch{}throw new Is}async function sS(e,t,r,i,n){if(!Ts(r)&&!(r instanceof Uint8Array))throw new TypeError(Lo(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(i?UG(e,i):i=Iwe(e),r instanceof Uint8Array&&oS(r,e.cekBits),e.cbc)return $we(e,t,r,i,n);let o=await ti(r,e.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:i,name:"AES-GCM",tagLength:128},o,t));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:i}}async function aS(e,t,r,i,n,o){if(!Ts(t)&&!(t instanceof Uint8Array))throw new TypeError(Lo(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!i)throw new F("JWE Initialization Vector missing");if(!n)throw new F("JWE Authentication Tag missing");if(!e.cbc&&n.length!==16)throw new F("Invalid Authentication Tag length");if(UG(e,i),t instanceof Uint8Array&&oS(t,e.cekBits),e.cbc)return Twe(e,t,r,i,n,o);let s=await ti(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:i,name:"AES-GCM",tagLength:128},s,Or(r,n)))}catch{throw new Is}}function pf(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Cwe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],kwe=[[],["deriveBits"]],lS=[[],[]];function cS(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:Cwe,ops:["wrapKey","unwrapKey"]}}function uS(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:t,crv:r,asymmetricKeyType:i})=>{if(r==="X25519"||i==="x25519")return{name:"X25519"};if(t==="OKP")throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:kwe,ops:[void 0,"deriveBits"]}}function al(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:lS,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function DD(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:lS,ops:["deriveBits","deriveBits"]}}var Mo=pf({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:lS,ops:["encrypt","decrypt"]},"RSA-OAEP":cS(1),"RSA-OAEP-256":cS(256),"RSA-OAEP-384":cS(384),"RSA-OAEP-512":cS(512),"ECDH-ES":uS("direct-key-agreement"),"ECDH-ES+A128KW":uS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":uS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":uS("key-agreement-with-key-wrapping"),A128KW:al(128),A192KW:al(192),A256KW:al(256),A128GCMKW:al(128,!0),A192GCMKW:al(192,!0),A256GCMKW:al(256,!0),"PBES2-HS256+A128KW":DD(),"PBES2-HS384+A192KW":DD(),"PBES2-HS512+A256KW":DD()}),Dwe=["encrypt","decrypt"];function cl(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:lS,ops:Dwe,cekBits:e,ivBits:t?128:96,cbc:t}}var Owe=pf({A128GCM:cl(128),A192GCM:cl(192),A256GCM:cl(256),"A128CBC-HS256":cl(256,!0),"A192CBC-HS384":cl(384,!0),"A256CBC-HS512":cl(512,!0)});function zG(e,t){throw new dt(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function ri(e){return(typeof e=="string"?Mo[e]:void 0)??zG("alg","Algorithm")}function ni(e){return e.mode==="key-wrapping"||e.mode==="key-encryption"||e.mode==="key-agreement-with-key-wrapping"}function hc(e){return(typeof e=="string"?Owe[e]:void 0)??zG("enc","Encryption Algorithm")}function jG(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");TD(e,t)}async function Nwe(e,t,r){let i=await ti(t,ri(e).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,i,"AES-KW"))}async function Uwe(e,t,r){let i=await ti(t,ri(e).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,i,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function GG(e,t,r){CD(t,ri(e).subtle,r),ol(e,t)}async function qG(e,t,r,i){if(!(e instanceof Uint8Array)||e.length<8)throw new F("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new F("PBES2 Count Input must be a positive integer");let n=Or(rr(t),Uint8Array.of(0),e),o=parseInt(t.slice(13,16),10),s={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await ti(i,ri(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}function OD(e){return Or(Wv(e.length),e)}async function Lwe(e,t,r){let i=t>>3,n=32,o=Math.ceil(i/n),s=new Uint8Array(o*n);for(let a=1;a<=o;a++){let c=await Jv("sha256",Or(Wv(a),e,r));s.set(c,(a-1)*n)}return s.slice(0,i)}async function VG(e,t,r,i,n=new Uint8Array,o=new Uint8Array){jG(e),jG(t,"deriveBits");let s=Or(OD(rr(r)),OD(n),OD(o),Wv(i)),a=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return Lwe(a,i,s)}function KG(e){nS(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new dt("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function dS(e,t){let r=e[t];if(r!==void 0){if(typeof r!="string")throw new F(`JOSE Header "${t}" (Agreement Party${t==="apu"?"U":"V"}Info) invalid`);return Wr(r,t,F)}}function BG(e,t){if(!(e===void 0||t===void 0||e.byteLength!==t.byteLength)){for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return;throw new F('JOSE Header "apu" and "apv" values must be distinct')}}function Mwe(e){if(e===void 0)throw new F("JWE Encrypted Key missing")}function FG(e){if(e!==void 0)throw new F("Encountered unexpected JWE Encrypted Key")}function zwe(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function HG(e,t,r,i,n,o){let{alg:s}=e,a=e.mode;if(a==="direct-encryption")return FG(i),r;let c=a==="direct-key-agreement";switch(c?FG(i):Mwe(i),e.subtle.name){case"ECDH":{let{epk:u}=n;if(!Pt(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(g=>Object.hasOwn(u,g)))throw new F('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');KG(r);let l=await sl(e,u),d=dS(n,"apu"),m=dS(n,"apv");BG(d,m);let f=await VG(l,r,c?t.alg:s,c?t.cekBits:parseInt(s.slice(-5,-2),10),d,m);if(c)return f;r=f;break}case"RSA-OAEP":return nS(r),GG(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,i));case"PBKDF2":{if(typeof n.p2c!="number")throw new F('JOSE Header "p2c" (PBES2 Count) missing or invalid');zwe(o);let u=o??1e4;if(n.p2c>u)throw new F('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new F('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=Wr(n.p2s,"p2s",F);r=await qG(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new F('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new F('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=Wr(n.iv,"iv",F),l=Wr(n.tag,"tag",F);if(u.byteLength!==12)throw new F("Invalid Initialization Vector length");if(l.byteLength!==16)throw new F("Invalid Authentication Tag length");return aS(hc(s.slice(0,-2)),r,i,u,l,new Uint8Array)}}return Uwe(s.slice(-6),r,i)}async function pS(e,t,r,i,n,o={}){let{alg:s,mode:a}=e,c=ni(e);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await ei(a==="direct-encryption"?t:e,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??mc(t):void 0;l&&oS(l,t.cekBits);let d,m;switch(e.subtle.name){case"ECDH":{KG(u);let{apu:f,apv:g}=o;f!==void 0&&nn(f,'"apu"'),g!==void 0&&nn(g,'"apv"');let v=f??dS(i,"apu"),S=g??dS(i,"apv");BG(v,S);let b;o.epk!==void 0?b=await ei(e,o.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let _=crypto.subtle,x=b;if(!x.extractable){if(typeof _.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await _.getPublicKey(b,[])}let{x:T,y:U,crv:N,kty:K}=await _.exportKey("jwk",x),B=a==="direct-key-agreement",de=await VG(u,b,B?t.alg:s,B?t.cekBits:parseInt(s.slice(-5,-2),10),v,S),pe={x:T,crv:N,kty:K};if(K==="EC"&&(pe.y=U),m={epk:pe},f!==void 0&&(m.apu=gt(f)),g!==void 0&&(m.apv=gt(g)),B)return[de,void 0,m];u=de;break}case"RSA-OAEP":{nS(u),GG(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:g=crypto.getRandomValues(new Uint8Array(16))}=o;u=await qG(g,s,f,u),m={p2c:f,p2s:gt(g)};break}case"AES-GCM":{let f=o.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):o.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let g=await sS(hc(s.slice(0,-2)),l,u,f,new Uint8Array);d=g.ciphertext,m={iv:gt(g.iv),tag:gt(g.tag)}}}if(d??=await Nwe(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,m]}function fS(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new dt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new F('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function WG(e){if(typeof globalThis[e]>"u")throw new dt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function JG(e,t,r=1/0){let i=e.writable.getWriter();i.write(t).catch(()=>{}),i.close().catch(()=>{});let n=[],o=0,s=e.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),o+=a.byteLength,r!==1/0&&o>r)throw new F("Decompressed plaintext exceeded the configured limit")}return Or(...n)}async function ZG(e){return WG("CompressionStream"),JG(new CompressionStream("deflate-raw"),e)}async function XG(e,t){return WG("DecompressionStream"),JG(new DecompressionStream("deflate-raw"),e,t)}function YG(e){let{aad:t,ciphertext:r,iv:i,protected:n,tag:o,unprotected:s}=e;if(i!==void 0&&(typeof i!="string"||!i))throw new F("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new F("JWE Ciphertext missing or incorrect type");if(o!==void 0&&(typeof o!="string"||!o))throw new F("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new F("JWE Protected Header incorrect type");if(t!==void 0&&(typeof t!="string"||!t))throw new F("JWE AAD incorrect type");if(s!==void 0&&!Pt(s))throw new F("JWE Shared Unprotected Header incorrect type");return{aad:t,ciphertext:r,iv:i,protected:n,tag:o,unprotected:s===void 0?void 0:{...s}}}function QG(e){let t,r;try{let{header:i}=e;if(Pt(i)){r=i.alg;let o=Object.keys(i);o.includes("alg")||(r=void 0),t=Object.fromEntries(o.map(s=>[s,s==="alg"?r:i[s]]))}else t=i;let{encrypted_key:n}=e;return[{encrypted_key:n,header:t},r]}catch(i){return[void 0,r,i]}}function eq(e){let{encrypted_key:t,header:r}=e;if(t!==void 0&&typeof t!="string")throw new F("JWE Encrypted Key incorrect type");if(r!==void 0&&!Pt(r))throw new F("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected===void 0&&r===void 0&&e.unprotected===void 0)throw new F("JOSE Header missing")}function ND(e){let{protected:t,ciphertext:r,iv:i,tag:n,aad:o}=e,s;return t!==void 0&&(s=il(t,F,"JWE Protected Header is invalid")),[s,Wr(r,"ciphertext",F),i!==void 0?Wr(i,"iv",F):void 0,n!==void 0?Wr(n,"tag",F):void 0,Xv((t??"")+(o!==void 0?`.${o}`:""),"aad",F)]}function mS(e){return[e&&df("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&df("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function UD(e,t,r,i=ND(e)){let[n,o,s,a,c]=i,{header:u,unprotected:l,aad:d}=e,m;if(u!==void 0||l!==void 0){if(!$s(n,u,l))throw new F("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");m={...n,...u,...l}}else m=n??{};let[f,g,v,S,b]=t,{encrypted_key:_}=e;Ps(F,Qv,v,n,m),fS(m,n);let{alg:x,enc:T}=m;if(typeof x!="string"||!x)throw new F("missing JWE Algorithm (alg) in JWE Header");let U=Mo[x];if(_===""&&(!U||!ni(U)))throw new F("JWE Encrypted Key incorrect type");let N=U?.mode==="integrated-encryption";if(!N&&(typeof T!="string"||!T))throw new F("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(x)||!f&&x.startsWith("PBES2"))throw new dc('"alg" (Algorithm) Header Parameter value not allowed');let K;if(N){if(T!==void 0)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new F("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new F("JWE Authentication Tag must be empty for integrated encryption")}else{if(g&&!g.has(T))throw new dc('"enc" (Encryption Algorithm) Header Parameter value not allowed');K=hc(T)}let B;if(_!==void 0)try{B=Wr(_,"encrypted_key",F)}catch(Ne){if(!U||!ni(U))throw Ne;B=new Uint8Array}let de=!1;typeof r=="function"&&(r=await r(n,e),de=!0);let pe=U??ri(x);ni(pe)&&B===void 0&&(B=new Uint8Array);let qe=await ei(pe.mode==="direct-encryption"?K:pe,r,"decrypt"),ee;if(pe.mode==="integrated-encryption")ee=await pe.decrypt(qe,B,o,c,n,m);else{let Ne=K,X;try{X=await HG(pe,Ne,qe,B,m,S),ni(pe)&&X instanceof Uint8Array&&X.byteLength<<3!==Ne.cekBits&&(X=mc(Ne))}catch(mt){if(mt instanceof TypeError||mt instanceof F||mt instanceof dt)throw mt;X=mc(Ne)}ee=await aS(Ne,X,o,s,a,c)}if(m.zip==="DEF"){let Ne=b??25e4;if(Ne===0)throw new dt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ne!==1/0&&(!Number.isSafeInteger(Ne)||Ne<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");ee=await XG(ee,Ne).catch(X=>{throw X instanceof F?X:new F("Failed to decompress plaintext",{cause:X})})}return{plaintext:ee,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:Wr(d,"aad",F)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...de&&{key:qe}}}async function tq(e,t,r){if(e instanceof Uint8Array&&(e=nl.decode(e)),typeof e!="string")throw new F("Compact JWE must be a string or Uint8Array");let{0:i,1:n,2:o,3:s,4:a,length:c}=e.split(".");if(c!==5)throw new F("Invalid Compact JWE");return UD({ciphertext:s,iv:o||void 0,protected:i,tag:a||void 0,encrypted_key:n||void 0},t,r)}async function hS(e,t,r){return tq(e,mS(r),t)}async function LD(e,t,r){if(!Pt(e))throw new F("General JWE must be an object");let i=e.recipients;if(!Array.isArray(i))throw new F("JWE Recipients missing or incorrect type");let n=Array.from(i);if(!n.every(Pt))throw new F("JWE Recipients missing or incorrect type");if(!n.length)throw new F("JWE Recipients has no members");let o,s,a;try{o=mS(r),s=YG(e),a=ND(s)}catch{throw new Is}let c=n.map(u=>QG(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Mo[l]:void 0;if(d&&!ni(d))throw new F(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return eq(l),await UD(l,o,t,a)}catch{}throw new Is}function gS(e,t,r){if(!$s(e,t,r))throw new F("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function MD(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new F("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");t!==void 0&&(e[8]=t?.crit);let[,i,n,o,s,a,c,u,l]=e;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&&i!==void 0&&(i=fc(F,i)[0],e[1]=i),n!==void 0&&(n=fc(F,n)[0],e[2]=n),!r&&o!==void 0&&(o=fc(F,o)[0],e[3]=o),u!==void 0&&!Pt(u))throw new TypeError("JWE Key Management Parameters must be an object");gS(i,n,o);let d={...i,...n,...o};eS(F,i),Ps(F,Qv,l,i,d),fS(d,i);let{alg:m,enc:f}=d;if(typeof m!="string"||!m)throw new F('JWE "alg" (Algorithm) Header Parameter missing or invalid');let g=Mo[m];if(g?.mode==="integrated-encryption"){if(f!==void 0)throw new F('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 ${m}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${m}`);return[d,void 0,g]}if(typeof f!="string"||!f)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,hc(f),g]}async function zD(e,t,r){let[i,n,o]=t,[s,a,c,u,l,d,m,f,,g]=e,v=a,S=c,b=o??ri(i.alg),_,x,T;b.mode==="integrated-encryption"?T=await ei(b,r,"encrypt"):[T,_,x]=await pS(b,n,r,i,d,f),x&&(g?S=S?{...S,...x}:x:v=v?{...v,...x}:x,gS(v,S,u));let U=v?gt(JSON.stringify(v)):"",N=l?.byteLength?gt(l):void 0,K=rr(N?`${U}.${N}`:U),B=s;i.zip==="DEF"&&(B=await ZG(B).catch(Ne=>{throw new F("Failed to compress plaintext",{cause:Ne})}));let de,pe,qe;b.mode==="integrated-encryption"?[_,de]=await b.encrypt(T,B,K,v,i,f):{ciphertext:de,tag:pe,iv:qe}=await sS(n,B,T,m,K);let ee={ciphertext:gt(de)};return qe&&(ee.iv=gt(qe)),pe&&(ee.tag=gt(pe)),_?.byteLength&&(ee.encrypted_key=gt(_)),N&&(ee.aad=N),v&&(ee.protected=U),u&&(ee.unprotected=u),S&&(ee.header=S),ee}async function rq(e,t,r){return zD(e,MD(e,r),t)}function nq(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(".")}var jD=class{#e;state;constructor(t,r,i){this.#e=t,this.state=[void 0,void 0,r,i]}setUnprotectedHeader(t){return En(this.state[0],"setUnprotectedHeader"),this.state[0]=t,this}setKeyManagementParameters(t){return En(this.state[1],"setKeyManagementParameters"),this.state[1]=t,this}addRecipient(...t){return this.#e.addRecipient(...t)}encrypt(...t){return this.#e.encrypt(...t)}done(){return this.#e}},ff=class{#e;#t=[];#r;#n;#i;constructor(t){this.#e=t}addRecipient(t,r){let i=new jD(this,t,r?.crit);return this.#t.push(i),i}setProtectedHeader(t){return En(this.#r,"setProtectedHeader"),this.#r=t,this}setSharedUnprotectedHeader(t){return En(this.#n,"setSharedUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#i=t,this}async encrypt(){if(!this.#t.length)throw new F("at least one recipient must be added");nn(this.#e,"plaintext");let t=this.#t.length>1,r,i=this.#r,n=this.#n,o=[];for(let g of this.#t){let[v,S,b,_]=g.state,x=[this.#e,i,v,n,this.#i,void 0,void 0,S,_,t],T=MD(x,void 0,o.length>0);o.length||(i=x[1],n=x[3]),o.push([x,T,b]);let[{alg:U,enc:N},,K]=T;if(t&&K&&!ni(K))throw new F(`"${U}" alg may only have a single recipient`);if(!r)r=N;else if(r!==N)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,g]of o)g[2]??=ri(g[0].alg);let[s,a,c]=o[0],u=t?mc(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...m}=await zD(s,a,c),f={...m,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let g=1;g<o.length;g++){let[v,[S,b,_],x]=o[g],T=v[2],[,U,N]=await pS(_,b,x,S,u,v[7]),K={encrypted_key:gt(U)};if(T||N){let B={...T,...N};N&&gS(v[1],B,v[3]),K.header=B}f.recipients.push(K)}return f}};var mf=[["verify"],["sign"]];function FD(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:mf}}function ul(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:mf,minRsaBits:2048}}function GD(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:mf}}function iq(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:mf}}function qD(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:mf}}var VD=pf({HS256:FD(256),HS384:FD(384),HS512:FD(512),RS256:ul(256),RS384:ul(384),RS512:ul(512),PS256:ul(256,32),PS384:ul(384,48),PS512:ul(512,64),ES256:GD("P-256",256),ES384:GD("P-384",384),ES512:GD("P-521",512),EdDSA:iq(),Ed25519:iq(),"ML-DSA-44":qD(44),"ML-DSA-65":qD(65),"ML-DSA-87":qD(87)});function yS(e){let t=typeof e=="string"?VD[e]:void 0;if(!t)throw new dt(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function oq(e){return[e&&df("algorithms",e.algorithms),e?.crit]}function jwe(e){return e===void 0?{}:il(e,pt,"JWS Protected Header is invalid")}function Fwe(e){try{return rr(e)}catch{throw new pt("JWS Compact Serialization payload must use only ASCII characters")}}async function Gwe(e,t,r,i,n){let{protected:o,header:s,payload:a}=e,c=n??jwe(o);if(!$s(c,s))throw new pt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=tS(c,Ps(pt,Yv,t[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new pt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(d))throw new dc('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new pt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new pt("JWS Payload must be a string or an Uint8Array instance");let m=l||typeof a!="string"?a:i(a),f=!1;typeof r=="function"&&(r=await r(c,e),f=!0);let g=yS(d),v=Or(o!==void 0?rr(o):new Uint8Array,rr("."),typeof m=="string"?t[2]??=Xv(m,"payload",pt):m),S=Wr(e.signature,"signature",pt),b=await ei(g,r,"verify"),_=await ti(b,g.subtle,"verify");g.minRsaBits&&ol(g.alg,_);let x=!1;try{x=await crypto.subtle.verify(g.signing,_,S,v)}catch{}if(!x)throw new Zv;let T={payload:typeof m=="string"?Wr(m,"payload",pt):m};return o!==void 0&&(T.protectedHeader=c),s!==void 0&&(T.unprotectedHeader=s),f?[{...T,key:b},l]:[T,l]}async function sq(e,t,r){if(e instanceof Uint8Array&&(e=nl.decode(e)),typeof e!="string")throw new pt("Compact JWS must be a string or Uint8Array");let{0:i,1:n,2:o,length:s}=e.split(".");if(s!==3)throw new pt("Invalid Compact JWS");return Gwe({payload:n,protected:i,signature:o},t,r,Fwe)}async function KD(e,t,r){let[i]=await sq(e,oq(r),t);return i}var ll=class{#e;constructor(t){nn(t,"plaintext"),this.#e=[t]}setContentEncryptionKey(t){return En(this.#e[5],"setContentEncryptionKey"),this.#e[5]=t,this}setInitializationVector(t){return En(this.#e[6],"setInitializationVector"),this.#e[6]=t,this}setProtectedHeader(t){return En(this.#e[1],"setProtectedHeader"),this.#e[1]=t,this}setKeyManagementParameters(t){return En(this.#e[7],"setKeyManagementParameters"),this.#e[7]=t,this}async encrypt(t,r){return nq(await rq([...this.#e],t,r))}};async function qwe(e,t,r){let[i,n,o,s]=e,a="";if(n!==void 0){let b=fc(pt,n);n=b[0],a=gt(b[1])}if(o!==void 0&&(o=fc(pt,o)[0]),!n&&!o)throw new pt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!$s(n,o))throw new pt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...o};eS(pt,n);let u=tS(n,Ps(pt,Yv,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new pt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=yS(l),m="",f=i,g;if(u){let b=e[4];b?(m=b[0]??=gt(i),f=b[1]??=rr(m)):(m=gt(i),g=rl.encode(`${a}.${m}`))}g??=Or(rr(a),rr("."),f);let v=await ti(await ei(d,t,"sign"),d.subtle,"sign");d.minRsaBits&&ol(d.alg,v);let S={signature:gt(new Uint8Array(await crypto.subtle.sign(d.signing,v,g))),payload:m};return n&&(S.protected=a),o&&(S.header=o),[S,u]}async function aq(e,t,r,i,n){let[o]=await qwe([e,t,void 0,r],i,n);return`${o.protected}.${o.payload}.${o.signature}`}var hf=class{#e;#t;constructor(t){nn(t,"payload"),this.#e=t}setProtectedHeader(t){return En(this.#t,"setProtectedHeader"),this.#t=t,this}async sign(t,r){return aq(this.#e,this.#t,r?.crit,t,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};function Vwe(e='JWK "alg" (Algorithm) Parameter'){throw new dt(`Invalid or unsupported ${e} value`)}function BD(e,t){return(typeof e=="string"?VD[e]??Mo[e]:void 0)??Vwe(t)}async function vS(e){if($D(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:gt(e)};if(!Ts(e))throw new TypeError(Lo(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let t=await crypto.subtle.exportKey("jwk",e);delete t.ext,delete t.key_ops,delete t.use,t.kty!=="AKP"&&delete t.alg;for(let r of Object.keys(t))t[r]===void 0&&delete t[r];return t}var zo=(e,t)=>{if(typeof e!="string"||!e)throw new lf(`${t} missing or invalid`)};async function HD(e,t){let r;if(Pt(e)){if(r=iS(e),typeof r.kty!="string")throw new TypeError(Lo(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(PD(e))r=iS(await vS(e));else throw new TypeError(Lo(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let i;switch(r.kty){case"AKP":zo(r.alg,'"alg" (Algorithm) Parameter'),zo(r.pub,'"pub" (Public key) Parameter'),i={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":zo(r.crv,'"crv" (Curve) Parameter'),zo(r.x,'"x" (X Coordinate) Parameter'),zo(r.y,'"y" (Y Coordinate) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":zo(r.crv,'"crv" (Subtype of Key Pair) Parameter'),zo(r.x,'"x" (Public Key) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":zo(r.e,'"e" (Exponent) Parameter'),zo(r.n,'"n" (Modulus) Parameter'),i={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new lf('"k" (Key Value) Parameter missing or invalid');i={k:r.k,kty:r.kty};break;default:throw new dt('"kty" (Key Type) Parameter missing or unsupported')}let n=rr(JSON.stringify(i));return gt(await Jv(t,n))}async function An(e,t,r){if(!Pt(e))throw new TypeError("JWK must be an object");let i=kD(e),n=NG(r?.extractable),{alg:o}=i;if(t??=o,i.kty!=="oct"&&!t)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(i.kty){case"oct":if(typeof i.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return pc(i.k);case"AKP":{if(typeof o!="string"||!o)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==o)throw new TypeError("JWK alg and alg option value mismatch");return sl(BD(t),i,n)}case"RSA":case"EC":case"OKP":return sl(BD(t),i,n);default:throw new dt('Unsupported "kty" (Key Type) Parameter value')}}function WD(e){let t;if(typeof e=="string"){let i=e.split(".");(i.length===3||i.length===5)&&([t]=i)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof t!="string"||!t)throw new TypeError(r);return il(t,TypeError,r)}var dq=p.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),pq=p.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),cq=p.string().min(1).max(128),uq=p.string().min(1).max(16384),Kwe=p.discriminatedUnion("kind",[p.object({kind:p.literal("access_key"),accessKeyId:cq,secretAccessKey:uq}).strict(),p.object({kind:p.literal("session"),accessKeyId:cq,secretAccessKey:uq,sessionToken:p.string().min(1).max(16384),expiresAt:p.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),p.object({kind:p.literal("environment")}).strict()]),Bwe=p.object({arn:pq,externalId:p.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),JD=p.object({authentication:Kwe,region:dq,role:Bwe.optional()}).strict(),SS=p.object({accountId:p.string().regex(/^\d{12}$/),principalId:p.string().min(1).max(256),arn:p.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),wS=JD.extend({sourceIdentity:SS.optional(),identity:SS.optional()}).strict();function dl(e){return e.includes(":assumed-role/")?e.slice(0,e.lastIndexOf("/")):e}function lq(e){return{...e,arn:dl(e.arn)}}function fq(e){return{authentication:e.authentication.kind,region:e.region,role:e.role??null,...e.sourceIdentity?{sourceIdentity:lq(e.sourceIdentity)}:{},...e.identity?{identity:lq(e.identity)}:{}}}var bS=p.object({authentication:p.enum(["access_key","session","environment"]),region:dq,sourceAccountId:p.string().regex(/^\d{12}$/).optional(),sourceArn:p.string().max(2e3).optional(),roleArn:pq.optional(),expiresAt:p.number().int().positive().optional()}).strict();function mq(e){return{authentication:e.authentication.kind,region:e.region,...e.sourceIdentity?{sourceAccountId:e.sourceIdentity.accountId,sourceArn:e.sourceIdentity.arn}:{},...e.role?{roleArn:e.role.arn}:{},...e.authentication.kind==="session"?{expiresAt:e.authentication.expiresAt}:{}}}var Hwe=p.object({method:p.enum(["GET","POST","PUT","DELETE","PATCH"]),path:p.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),gf=p.object({account:p.string().min(1),identities:p.array(p.string()),user:p.string().nullable(),description:p.string().nullable(),roles:p.array(p.string()).nullable(),credentialId:p.number().int().positive(),rules:p.array(Hwe),allowedIPs:p.array(p.string()).nullable(),expiresAt:p.number().nullable()}).strict();typeof window<"u"&&p.config({jitless:!0});var P=p.uuid(),be=p.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),ce=p.iso.datetime(),Nr=p.json(),Mt=p.record(p.string(),Nr),gq=p.enum(["ja","en"]),yq=p.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var vq=p.enum(["variable","connection","service","method","app","object","environment","function","keyring"]),Jr=p.object({kty:p.literal("EC"),crv:p.literal("P-256"),x:p.string().min(40).max(50),y:p.string().min(40).max(50)}).strict(),Wwe=p.object({alg:p.literal("dir"),enc:p.literal("A256GCM"),sub:P}).strict(),AS=p.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(e=>{try{return Wwe.safeParse(WD(e)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),jo=p.object({protected:p.string().max(2048),iv:p.string().max(64),ciphertext:p.string().max(2e6),tag:p.string().max(64),aad:p.string().max(2048).optional(),recipients:p.array(p.object({encrypted_key:p.string().max(2048),header:p.object({kid:P,epk:Jr.optional(),alg:p.string().optional()}).passthrough()})).min(1).max(100)}).strict(),k7e=p.object({id:P,name:be,publicKey:Jr}),Cs=p.object({id:P,name:be,owner:p.object({id:P,name:be}).nullable(),createdAt:ce,permissions:p.array(yq),createKinds:p.array(vq),publicKey:Jr.nullable()}),D7e=p.object({id:P,kind:p.enum(["passkey","email","key"]),name:p.string(),createdAt:ce,lastUsedAt:ce.nullable(),expiresAt:ce.nullable(),canOpen:p.boolean()}),Sq=p.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),Jwe=p.object({subjectId:P,relation:Sq,objectId:P}).strict(),O7e=Jwe.extend({objectType:p.enum(["principal",...vq.options]),subjectName:be,objectName:be,createdAt:ce}),N7e=p.object({error:p.object({code:p.string(),message:p.string(),details:Nr.optional()})}),U7e=p.object({ok:p.literal(!0)}),Zwe=p.object({value:p.string().min(1).max(200),label:p.string().min(1).max(200),values:p.record(p.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),p.string()).default({})}).strict(),RS=p.object({name:p.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:p.string(),secret:p.boolean().optional(),inputType:p.enum(["text","password"]).optional(),required:p.boolean().optional(),placeholder:p.string().optional(),note:p.string().optional(),pattern:p.string().optional(),choices:p.array(Zwe).min(1).max(100).optional(),defaultValue:p.string().max(1e3).optional(),when:p.object({field:p.string(),values:p.array(p.string()).min(1)}).strict().optional(),visibility:p.enum(["application","connection"]).optional()}).superRefine((e,t)=>{let r=e.choices??[];new Set(r.map(i=>i.value)).size!==r.length&&t.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),ZD=p.record(p.string().regex(/^[A-Z_][A-Z0-9_]*$/),p.string()),Xwe=p.record(p.string().regex(/^[A-Z_][A-Z0-9_]*$/),p.union([p.string(),p.array(p.union([p.string().max(8192),p.object({pointer:p.string().max(1e3)}).strict()])).min(1).max(32)])),XD=p.object({values:p.array(p.object({id:p.string(),name:p.string(),description:p.string().optional()})).optional(),default:p.array(p.string()).default([]),required:p.array(p.string()).optional(),separator:p.string().default(" "),docs:p.url().optional()}),gc=p.string().min(1).max(4096),xS=p.union([p.string(),p.array(p.string()).min(1)]),Ywe=p.object({browserTokenExchange:p.enum(["available","unavailable","unknown"]).optional(),application:p.enum(["required","implicit"]).default("required"),grantType:p.enum(["authorization_code","client_credentials"]).optional(),issuer:p.url().optional(),registrationUrl:p.url().optional(),authorizeUrl:gc.optional(),tokenUrl:gc,identity:p.object({url:gc.optional(),from:p.enum(["token","app"]).optional(),method:p.enum(["GET","POST"]).default("GET"),id:xS.default("/id"),name:xS.default("/name"),headers:p.record(p.string(),p.string()).default({})}).optional(),revoke:p.object({url:gc,style:p.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:p.enum(["body","basic","none"]).optional(),tokenOnly:p.literal(!0).optional()}).optional(),clientAuth:p.enum(["body","basic","none"]).default("body"),pkce:p.boolean().default(!0),tokenFormat:p.enum(["form","json"]).default("form"),okPointer:p.string().optional(),authorizeParams:p.record(p.string(),p.string()).default({}),tokenParams:p.record(p.string(),p.string()).default({}),defaults:p.record(p.string(),p.string()).default({}),scopes:XD.default({default:[],separator:" "}),fields:p.array(RS).default([]),outputs:ZD.default({ACCESS_TOKEN:"/accessToken"}),adapter:p.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:p.array(p.string()).default([]),hint:p.string().optional()}).refine(e=>e.grantType==="client_credentials"||!!e.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),Qwe=p.object({fields:p.array(RS).min(1),outputs:Xwe,resolver:p.literal("vultr-role").optional(),bindFields:p.boolean().optional(),constants:p.record(p.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),p.string()).optional(),identity:p.object({url:gc,headers:p.record(p.string(),p.string()),id:xS,name:xS}).strict().optional(),console:p.url().optional(),instructions:p.string().optional(),hint:p.string().optional()}),YD=p.enum(["oauth","token","aws","ovh","approval"]),ebe=p.object({hint:p.string().optional()}).strict(),tbe=p.object({authorization:p.enum(["api_key","consumer_key"]),apiBaseUrl:gc,fields:p.array(RS).min(1),scopes:XD.default({default:[],separator:`
122
- `}),outputs:ZD,hint:p.string().optional()}).strict(),pl=p.string().regex(/^[A-Z_][A-Z0-9_]*$/),hq=p.union([p.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),p.object({output:pl}).strict()]),IS=p.object({urlField:p.string().min(1).max(100).optional(),authentication:p.discriminatedUnion("kind",[p.object({kind:p.literal("none")}).strict(),p.object({kind:p.literal("bearer"),token:pl}).strict(),p.object({kind:p.literal("basic"),username:pl,password:pl}).strict(),p.object({kind:p.literal("header"),name:hq,value:pl}).strict(),p.object({kind:p.literal("query"),name:hq,value:pl}).strict()])}).strict(),Sf={name:be,docs:p.url().optional(),console:gc.optional(),http:IS.optional(),preparation:p.object({scopeSelection:p.enum(["optional","required","hidden"]).default("optional"),instructions:p.array(p.union([p.string().max(2e3),p.object({ja:p.string().max(2e3),en:p.string().max(2e3)}).strict()])).max(10).default([]),docs:p.boolean().default(!1)}).strict().optional()},$S=p.object({...Sf,kind:p.literal("oauth"),config:Ywe}).strict(),PS=p.object({...Sf,kind:p.literal("token"),config:Qwe}).strict(),TS=p.object({...Sf,kind:p.literal("aws"),config:ebe}).strict(),CS=p.object({...Sf,kind:p.literal("ovh"),config:tbe}).strict(),kS=p.object({...Sf,kind:p.literal("approval"),config:p.object({adapter:p.literal("runpod-flash"),fields:p.array(RS).default([]),scopes:XD.default({default:[],separator:" "}),outputs:ZD,hint:p.string().optional()}).strict()}).strict(),fl=p.discriminatedUnion("kind",[$S,PS,TS,CS,kS]),yf={id:p.string().min(1),builtin:p.boolean(),availability:p.enum(["ready","app-required","unavailable"]),defaultName:be,registration:p.object({kind:p.enum(["input","authorization"]),device:p.enum(["browser","cli"]),browserExchange:p.enum(["available","unavailable","unknown"]),tokenAlternatives:p.array(p.string())}).strict()},rbe=p.discriminatedUnion("kind",[$S.extend(yf),PS.extend(yf),TS.extend(yf),CS.extend(yf),kS.extend(yf)]),vf=p.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),QD=p.object({name:be,logo:p.string().regex(/^[a-z0-9-]+$/).optional(),api:p.url().optional(),docs:p.url().optional(),console:p.url().optional(),targets:p.array(p.object({id:vf,name:be,api:p.url().optional(),methods:p.array(vf).min(1)}).strict()).max(32).optional()}).strict(),nbe=QD.extend({methods:p.record(vf,p.string().min(1))}).strict(),wq=QD.extend({methods:p.record(vf,p.union([p.string().min(1),fl]))}).strict(),L7e=QD.extend({id:p.string(),builtin:p.boolean(),methods:p.record(vf,rbe)}),bq=p.object({id:P,output:p.string().min(1).max(100).optional()}).strict(),_q=e=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(e),ibe=p.object({name:p.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:bq,format:p.enum(["text","file","json"]).default("text"),pointer:p.string().optional()}).strict(),obe=p.object({pointer:p.string().max(500),parts:p.array(p.union([p.string().max(8192),bq])).min(1).max(32)}).strict(),yc=p.object({url:p.string().min(1).max(4096).optional(),connectionId:P.optional(),method:p.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:p.record(p.string(),p.string().max(8192)).default({}),body:p.string().max(1e6).optional(),json:Nr.optional(),form:p.record(p.string(),p.string()).optional(),bindings:p.array(obe).max(32).default([])}).strict().refine(e=>!!(e.url||e.connectionId),{message:"Choose a connection or enter a destination URL."}),vc=p.object({command:p.array(p.string().max(8192)).min(1).max(100),stdin:p.string().max(1e6).optional(),timeoutSeconds:p.number().int().min(1).max(3600).default(60),inputs:p.array(ibe).max(32).default([])}).strict(),xq=p.discriminatedUnion("kind",[vc.omit({stdin:!0}).extend({kind:p.literal("command")}).strict(),p.object({kind:p.literal("http"),request:yc,responseFormat:p.enum(["text","json"]).default("json")}).strict()]),ks=p.object({description:p.string().max(2e3).default(""),program:xq,parameters:p.array(p.object({name:p.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:p.string().max(100),type:p.enum(["string","number","boolean","json"]).default("string"),required:p.boolean().default(!0),default:Nr.optional()}).strict()).max(32).default([]),result:p.enum(["text","json"]).default("json")}).strict(),wf=p.object({expiresAt:ce.nullable().default(null)}).strict(),M7e=p.object({version:p.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:wf,state:p.enum(["publication_required","unconfigured","configured","approval_required","unavailable","expired"])}).strict(),Fo={id:P,ownerId:P,name:be,createdAt:ce,updatedAt:ce,version:p.number().int().positive(),permissions:p.array(yq)},sbe=p.enum(["starting","running","stopping","stopped","failed"]),abe=p.enum(["manual","idle","timeout","quota","capacity","payment"]),cbe=p.object({state:p.enum(["pending","failed","complete"]),error:p.string().nullable()}),ube=p.object({idleSeconds:p.number().int().min(60).max(2147483647).nullable().default(null),maxSeconds:p.number().int().min(60).max(2147483647).nullable().default(null)}).strict(),Eq=p.object({size:p.enum(["small","medium","large"]).default("small"),lifetime:ube.default({idleSeconds:null,maxSeconds:null}),ssh:Bv.optional()}).strict(),eO={recipients:p.array(P).default([]),executors:p.array(P).default([]),custodyRevision:p.number().int().positive().nullable().default(null)},lbe=p.object({...Fo,kind:p.literal("variable"),data:p.object({...eO,bytes:p.number().int().nonnegative()})}),dbe=p.object({...Fo,kind:p.literal("connection"),data:p.object({...eO,methodId:p.string(),fields:p.record(p.string(),p.string()).default({}),settings:p.array(p.object({name:p.string(),label:p.string(),value:p.string()})).default([]),methodName:p.string(),methodKind:YD,http:IS.optional(),services:p.array(p.object({id:p.string(),name:be})).default([]),account:p.string(),accountId:p.string().nullable().default(null),accountVerified:p.boolean().default(!1),scopes:p.array(p.string()),scopesStatus:p.enum(["unknown","requested","reported"]).default("unknown"),outputs:p.array(p.string()),state:p.enum(["ready","reconnect","review","disconnecting","uncertain"]),revocable:p.boolean().default(!1),appId:P.nullable(),generation:P.optional(),authorizationDigest:p.string().optional(),aws:bS.optional(),ovh:gf.optional()})}),pbe=p.object({...Fo,kind:p.literal("service"),data:nbe}),fbe=p.object({...Fo,kind:p.literal("method"),data:fl}),mbe=p.object({...Fo,kind:p.literal("app"),data:p.object({...eO,methodId:p.string(),clientId:p.string(),fields:p.record(p.string(),p.string()).default({}),generation:P.optional()})}),hbe=p.object({...Fo,kind:p.literal("object"),data:p.object({size:p.number().int().nonnegative(),contentType:p.string()})}),gbe=p.object({...Fo,kind:p.literal("environment"),data:Eq.extend({executorId:P.optional(),operatorId:P.optional(),driver:p.enum(["attached","managed"]).optional(),capabilities:p.array(p.string()).optional(),isolation:p.enum(["process","container"]).optional(),manifestDigest:p.string().optional(),processes:p.object({workingDirectory:p.string()}).optional(),ssh:ED.optional(),awsPrincipal:p.string().optional(),state:sbe,connected:p.boolean(),deletion:cbe.optional(),startedAt:ce.nullable(),stoppedAt:ce.nullable(),stopReason:abe.nullable().default(null),lastActiveAt:ce,error:p.string().nullable()})}),ybe=p.object({...Fo,kind:p.literal("function"),data:ks.omit({program:!0}).extend({program:xq.optional()})}),vbe=p.object({...Fo,kind:p.literal("keyring"),data:p.object({revision:p.number().int().positive(),signature:p.string()})}),ml=p.discriminatedUnion("kind",[lbe,dbe,pbe,fbe,mbe,hbe,gbe,ybe,vbe]),z7e=p.discriminatedUnion("kind",[p.object({kind:p.literal("service"),name:be,definition:wq}).strict(),p.object({kind:p.literal("method"),name:be,definition:fl}).strict(),p.object({kind:p.literal("environment"),name:be.optional(),options:Eq}).strict()]),j7e=p.object({version:p.number().int().positive(),name:be.optional(),definition:p.union([wq,fl]).optional()}).strict(),Sc=p.object({name:p.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Mt}).strict(),DS=Sc.extend({inputs:p.array(p.object({pointer:p.string(),label:p.string().min(1).max(100),secret:p.boolean().default(!1),multiline:p.boolean().default(!1),site:p.url().optional()}).strict()).max(16).default([])}),ES=p.object({ja:p.string(),en:p.string()}).strict(),tO=DS.extend({title:ES,execution:p.enum(["server","keyholder"]),configure:p.array(p.string()),environment:p.object({required:p.boolean(),reason:ES.nullable()}).strict()}),F7e=p.object({to:P.optional(),executionId:P.optional(),message:p.string().max(1e3).default(""),operations:p.array(DS).min(1).max(8).optional(),expiresInMinutes:p.number().int().min(1).max(1440).default(30)}).strict().superRefine((e,t)=>{!!e.executionId==!!e.operations&&t.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),_S=p.object({id:P,name:be}),Aq=p.discriminatedUnion("kind",[p.object({kind:p.literal("line"),subject:_S,relation:Sq,object:_S}),p.object({kind:p.literal("transfer"),item:_S,to:_S})]),G7e=p.object({id:P,executionId:P,from:Cs.pick({id:!0,name:!0}),to:Cs.pick({id:!0,name:!0}).nullable(),message:p.string(),purpose:p.enum(["input","approval"]),state:p.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:ce,expiresAt:ce,url:p.url(),code:p.string().optional(),returnUrl:p.url().nullable(),refreshUrl:p.url().nullable(),canRespond:p.boolean(),canCancel:p.boolean()}),q7e=p.object({id:P,name:be,publicKey:Jr,state:p.enum(["pending","approving","approved"]),principalId:P.nullable(),createdAt:ce,expiresAt:ce}),V7e=p.object({available:p.boolean(),required:p.boolean(),active:p.boolean(),payer:Cs.pick({id:!0,name:!0}).nullable()}),K7e=p.object({storageBytes:p.number().nonnegative(),storageLimit:p.number().positive(),computeSeconds:p.number().nonnegative(),computeLimit:p.number().positive(),month:p.string()}),B7e=p.object({id:p.string(),actorId:P.nullable(),action:p.string(),targetId:P.nullable(),createdAt:ce,details:Mt}),H7e=p.object({returnUrl:p.url().optional(),refreshUrl:p.url().optional()}).strict(),hl=e=>p.object({items:p.array(e),next:p.string().nullable().default(null)}),W7e=p.object({id:P}),J7e=p.object({owner:P}),Sbe=p.object({limit:p.coerce.number().int().min(1).max(200).default(100),after:p.string().optional()}),Z7e=Sbe.extend({object:P.optional(),subject:P.optional()}).refine(e=>!!e.object!=!!e.subject,"Choose the object or the subject of the lines.");var bbe=new TextEncoder,_be=new TextDecoder,OS="ECDH-ES+A256KW",Rq="A256GCM",ft=e=>bbe.encode(e),NS=e=>_be.decode(e);function Ds(e){let t="";for(let r=0;r<e.length;r+=8192)t+=String.fromCharCode(...e.subarray(r,r+8192));return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Iq(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}async function wc(e,t,r){if(!t.length||new Set(t.map(n=>n.id)).size!==t.length)throw new Error("Recipients must be distinct and nonempty.");let i=new ff(e).setProtectedHeader({enc:Rq}).setAdditionalAuthenticatedData(ft(r));for(let n of t)i.addRecipient(await An(n.publicKey,OS)).setUnprotectedHeader({alg:OS,kid:n.id});return jo.parse(await i.encrypt())}async function bc(e,t,r,i){if(e.aad!==Ds(ft(i)))throw new Error("The encrypted content belongs to a different item.");let n=e.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let o=t instanceof CryptoKey?t:await An(t,OS);return(await LD({...e,recipients:[n]},o,{keyManagementAlgorithms:[OS],contentEncryptionAlgorithms:[Rq]})).plaintext}var yt=p.string().regex(/^[A-Za-z0-9_-]{43}$/),_t=p.string().min(100).max(4e6),$q=Jr.extend({d:p.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Tq=p.object({encryption:$q,signing:$q}).strict(),vt=p.object({id:P,principalId:P,generation:p.number().int().positive(),previous:yt.nullable(),encryption:Jr,signing:Jr}).strict();function C(e){if(e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&!/[\uD800-\uDFFF]/u.test(e))return JSON.stringify(e);if(Array.isArray(e))return"["+Array.from(e,C).join(",")+"]";if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype)return"{"+Object.keys(e).sort().map(t=>{if(/[\uD800-\uDFFF]/u.test(t))throw new Error("Use Unicode property names.");return JSON.stringify(t)+":"+C(e[t])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Pq(e){return HD(Jr.parse({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),"sha256")}async function te(e){return Ds(new Uint8Array(await crypto.subtle.digest("SHA-256",ft(C(e)))))}async function US(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",ft(C(e))));return"sha256:"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}async function Tt(e,t,r){let i=t instanceof CryptoKey?t:await An(t,"ES256");return new hf(ft(C(e))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(i)}async function nr(e,t,r,i){if(C(await bf(t,r,i))!==C(e))throw new Error("The signature does not authorize this content.")}async function bf(e,t,r){let i=await KD(e,await An(Jr.parse(t),"ES256"),{algorithms:["ES256"]});if(i.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(i.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(i.payload),o=JSON.parse(n);if(C(o)!==n)throw new Error("Sign canonical JSON content.");return o}var gl=p.object({binding:vt,signature:_t}).strict();async function Mi(e){let t=vt.parse(e);if(t.generation===1!=(t.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Pq(t.encryption)===await Pq(t.signing))throw new Error("Use separate encryption and signing keys.");await An(t.encryption,"ECDH-ES+A256KW"),await An(t.signing,"ES256")}async function LS(e){let{binding:t,signature:r}=gl.parse(e);return await Mi(t),await nr(t,r,t.signing,"key-binding"),t}var Cq=p.object({ownerId:P,name:be,resourceId:P.optional(),version:p.number().int().positive().optional(),environmentIds:p.array(P).max(32).optional()}).strict(),uXe=Cq.extend({value:p.literal("").optional()}),lXe=Cq.extend({methodId:p.string().min(1).max(200),clientId:p.string().max(1e3),fields:p.record(p.string(),p.string()).optional(),clientSecret:p.literal("").optional()}),dXe=p.object({ownerId:P,name:be,definition:ks,resourceId:P.optional(),version:p.number().int().positive().optional()}).strict(),pXe=p.object({functionId:P,functionVersion:p.number().int().positive(),version:p.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:wf.default({expiresAt:null})}).strict(),kq=p.object({ownerId:P,connectionId:P,environmentId:P}).strict(),fXe=p.object({ownerId:P,connectionId:P,version:p.number().int().positive(),users:p.array(P).max(32),expiresAt:p.iso.datetime().optional()}).strict(),mXe=p.object({ownerId:P,methodId:p.string().min(1).max(200),connectionId:P.optional(),name:be.optional(),appId:P.optional(),redirectUri:p.url().optional(),users:p.array(P).max(32).optional(),scopes:p.array(p.string().min(1).max(1e3)).max(200).optional(),methodDigest:p.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:p.string().max(1e3).optional(),fields:p.record(p.string(),p.string()).optional(),clientSecret:p.literal("").optional()}).strict(),Dq=p.object({ownerId:P,environmentId:P.optional(),operation:p.union([p.object({kind:p.literal("http"),request:yc}).strict(),vc.extend({kind:p.literal("command")}),p.object({kind:p.enum(["http","command"]),programId:P,programDigest:p.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:p.record(p.string(),be).default({})}).strict().superRefine((e,t)=>{e.environmentId||t.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),hXe=p.object({name:Sc.shape.name,title:ES,execution:p.enum(["server","keyholder"]),configure:p.array(p.string()),environment:tO.shape.environment,input:Mt}).strict(),gXe=p.object({id:P.optional(),operations:p.array(DS).min(1).max(8),responderId:P.optional(),message:p.string().max(1e3).default(""),expiresInMinutes:p.number().int().min(1).max(1440).default(1440)}).strict(),yXe=p.object({values:p.array(Mt).max(8).default([]),configuration:p.array(Mt).max(8).default([]),code:p.string().max(20).optional()}).strict(),xbe=p.object({index:p.number().int().nonnegative(),invocation:Sc,approval:p.object({id:P,index:p.number().int().nonnegative()}).strict().optional(),continuation:p.object({kind:p.enum(["connection","run"]),id:P}).strict().nullable()}).strict(),Oq=p.object({id:P,actorId:P,ownerId:P,requests:p.array(P),steps:p.array(p.object({index:p.number().int().nonnegative(),name:Sc.shape.name,state:p.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:p.array(p.object({kind:p.enum(["run","function","process"]),id:P}).strict())}).strict()),creator:Cs.pick({id:!0,name:!0}),operations:p.array(tO),approval:p.object({requestId:P.nullable(),proposal:Aq.nullable()}).strict().nullable(),canContinue:p.boolean(),canCancel:p.boolean(),url:p.url(),code:p.string().optional(),error:p.object({code:p.string(),message:p.string()}).strict().nullable(),index:p.number().int().nonnegative(),state:p.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:p.enum(["approval","input","execution"]).nullable(),waiting:xbe.nullable(),results:p.array(Nr.nullable()),createdAt:p.iso.datetime(),expiresAt:p.iso.datetime()}).strict(),Nq=p.object({id:P,index:p.number().int().nonnegative(),invocation:Sc,continuationId:P.optional()}).strict();var yl=p.url().refine(e=>{let t=new URL(e);return t.origin===e&&!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ge={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},Ebe=p.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),Lq=e=>e===ge.executionResult?14e5:1e6,Q={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"},_f=p.enum([Q.http,Q.command,Q.function,Q.connect,Q.refresh,Q.revoke]);var Abe={[ge.value]:[Q.http,Q.command,Q.function],[ge.tokenSet]:[Q.http,Q.command,Q.function,Q.refresh,Q.revoke],[ge.clientCredential]:[Q.connect,Q.refresh,Q.revoke],[ge.executionResult]:[]},rO=e=>Abe[e];var nO=e=>e===ge.tokenSet,Rbe=p.object({id:P,digest:yt}).strict(),Ibe=p.object({actor:vt,executor:vt,operations:p.array(_f).min(1).max(6),functionDigests:p.array(yt).max(100).default([]),origins:p.array(yl).max(100).default([]),callerProgram:p.boolean().default(!1),expiresAt:ce}).strict(),$be=p.object({function:Rbe,executor:vt,operations:p.array(_f).min(1).max(6),expiresAt:ce.nullable()}).strict(),Pbe=p.union([Ibe,$be]);function Go(e,t=Date.now()){return e.expiresAt===null||Date.parse(e.expiresAt)>t}function vl(e){return e.expiresAt===null?1/0:Date.parse(e.expiresAt)}var qo=p.object({format:p.literal(2),origin:yl,id:P,ownerId:P,contentType:Ebe,revision:p.number().int().positive(),authorities:p.array(vt).min(1).max(100),readers:p.array(vt).min(1).max(100),grants:p.array(Pbe).max(100),observers:p.array(P).max(100).optional(),producers:p.array(p.object({executor:vt,runId:P,expiresAt:ce,materialRevision:p.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),Uq=p.object({ownerId:P,authorities:p.array(vt).min(1).max(100)}).strict(),Mq=p.object({origin:yl,id:P,revision:p.number().int().positive(),from:Uq,to:Uq,policyDigest:yt,previous:yt.nullable(),signerId:P}).strict(),Tbe=Mq.extend({signature:_t}),iO=p.array(Tbe).max(16),xf=p.object({policy:qo,authorityId:P,signature:_t,lineage:iO.optional()}).strict(),ir=p.object({policy:qo,authorityId:P,authorization:_t,lineage:iO.optional(),materialRevision:p.number().int().positive(),updatedAt:ce,creationRunId:P.nullable(),metadata:Mt,sealed:jo,signerId:P,signature:_t}).strict(),_c=e=>({ownerId:e.ownerId,authorities:e.authorities});async function zq(e,t=[]){let r;for(let i of t){let{signature:n,...o}=i;if(i.origin!==e.origin||i.id!==e.id||i.revision>e.revision||r&&(i.revision<=r.revision||C(r.to)!==C(i.from))||i.previous!==(r?await te(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=i.from.authorities.find(a=>a.id===i.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await nr(o,n,s.signing,"authority-handoff"),r=i}if(r&&C(r.to)!==C(_c(e)))throw new Error("Use the authorities approved by the latest handoff.")}function oO(e){let t=e.policy.authorities.find(n=>n.id===e.authorityId);if(t)return t;let r=e.lineage?.at(-1),i=r?.revision===e.policy.revision?r.from.authorities.find(n=>n.id===e.authorityId):void 0;if(!i||i.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return i}function MS(e,t){if(e.id!==t.policy.id||e.origin!==t.policy.origin||e.contentType!==t.policy.contentType)return!1;let r=C(_c(e));return r===C(_c(t.policy))?!0:!!t.lineage?.some(i=>i.revision>e.revision&&C(i.from)===r)}async function jq(e,t,r,i){let n=[...e?.lineage??[]];if(e&&C(_c(e.policy))!==C(_c(t))){if(await on(e),!e.policy.authorities.some(s=>C(s)===C(r))||e.policy.id!==t.id||e.policy.origin!==t.origin||e.policy.contentType!==t.contentType||t.revision!==e.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let o=Mq.parse({origin:t.origin,id:t.id,revision:t.revision,from:_c(e.policy),to:_c(t),policyDigest:await te(t),previous:n.length?await te(n.at(-1)):null,signerId:r.id});n.push({...o,signature:await Tt(o,i.signing,"authority-handoff")})}return n.length?{lineage:iO.parse(n)}:{}}async function zS(e){let t=qo.parse(e),r=[...t.authorities,...t.readers,...t.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...t.producers.map(n=>n.executor)],i=new Map;for(let n of r){await Mi(n);let o=C(n);if(i.has(n.id)&&i.get(n.id)!==o)throw new Error("Each key binding must identify the same keys throughout a policy.");i.set(n.id,o)}for(let n of[t.readers,t.authorities])if(new Set(n.map(o=>o.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of t.authorities)if(!t.readers.some(o=>o.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of t.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(o=>!rO(t.contentType).includes(o)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(o=>o!==Q.function&&o!==Q.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(o=>o===Q.http||o===Q.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(Q.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return t}function jS(e){return[...new Map([...e.readers,...e.grants.map(t=>t.executor)].map(t=>[t.id,t])).values()]}async function Ns(e,t){return C({purpose:"resource",policyDigest:await te(e),materialRevision:t})}async function Ef(e,t,r,i,n,o,s){if(e.byteLength>Lq(t.contentType))throw new Error("The content exceeds its storage limit.");let a=await zS(t),c=await jq(s,a,i,n);if(!a.authorities.some(m=>C(m)===C(i))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(a,r)),l={policy:a,...c,authorityId:i.id,authorization:await Tt(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:o??(a.contentType===ge.value?{bytes:e.byteLength}:{}),sealed:u,signerId:i.id},d=ir.parse({...l,signature:await Tt(l,n.signing,"resource")});return await on(d),d}async function on(e){let t=ir.parse(e),{signature:r,...i}=t;await zS(t.policy),await zq(t.policy,t.lineage);let n=oO(t),o=t.lineage?.at(-1);if(o?.revision===t.policy.revision&&o.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");await nr(t.policy,t.authorization,n.signing,"access-policy");let s=(t.signerId===n.id?n:void 0)??t.policy.authorities.find(u=>u.id===t.signerId)??t.policy.producers.find(u=>u.executor.id===t.signerId&&u.runId===t.creationRunId&&u.materialRevision===t.materialRevision&&(t.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(t.updatedAt)))?.executor??(nO(t.policy.contentType)?t.policy.grants.find(u=>u.executor.id===t.signerId&&u.operations.includes(Q.refresh)&&Go(u,Date.parse(t.updatedAt)))?.executor:void 0);if(!s||Date.parse(t.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await nr(i,r,s.signing,"resource");let a=jS(t.policy).map(u=>u.id).sort(),c=t.sealed.recipients.map(u=>u.header.kid).sort();if(C(a)!==C(c)||t.sealed.aad!==Ds(ft(await Ns(t.policy,t.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return t}async function Fq(e,t,r,i,n=e.metadata){let o=await on(e);if(!nO(o.policy.contentType)||!(o.policy.authorities.some(m=>C(m)===C(r))||o.policy.grants.some(m=>C(m.executor)===C(r)&&m.operations.includes(Q.refresh)&&Go(m))))throw new Error("This executor cannot renew this connection.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=o.materialRevision+1,a=await wc(t,jS(o.policy).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(o.policy,s)),{signature:c,...u}=o,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await Tt(l,i.signing,"resource")};return await on(d),d}async function FS(e,t,r,i){let n=await zS(e);if(!n.authorities.some(s=>C(s)===C(t)))throw new Error("Only an authority can approve this policy.");let o={policy:n,...await jq(i,n,t,r),authorityId:t.id,signature:await Tt(n,r.signing,"access-policy")};return await Us(o),o}async function Us(e){let t=xf.parse(e);await zS(t.policy),await zq(t.policy,t.lineage);let r=t.lineage?.at(-1);if(r?.revision===t.policy.revision&&r.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");let i=t.policy.authorities.find(n=>n.id===t.authorityId);if(!i)throw new Error("The policy must be signed by an authority.");return await nr(t.policy,t.signature,i.signing,"access-policy"),t}async function Af(e,t,r,i,n,o){let s=await Us(t),{policy:a}=s,c=a.producers.find(m=>m.runId===r&&C(m.executor)===C(i)&&(a.contentType===ge.executionResult||Date.parse(m.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(e.byteLength>Lq(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(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:o,sealed:u,signerId:i.id},d={...l,signature:await Tt(l,n.signing,"resource")};return await on(d),d}async function Rf(e,t,r){let i=await on(e);if(!i.policy.readers.some(n=>C(n)===C(t)))throw new Error("This identity cannot reveal the content.");return bc(i.sealed,r,t.id,await Ns(i.policy,i.materialRevision))}var Cbe=p.object({id:P,policyDigest:yt,materialRevision:p.number().int().positive(),authorizationDigest:yt.optional()}).strict();async function sO(e,t){return t.id===e.policy.id&&t.policyDigest===await te(e.policy)&&(t.authorizationDigest===void 0||t.authorizationDigest===e.metadata.authorizationDigest)&&(t.materialRevision===e.materialRevision||nO(e.policy.contentType)&&t.authorizationDigest!==void 0&&t.authorizationDigest===e.metadata.authorizationDigest&&e.materialRevision>=t.materialRevision)}var GS=p.object({format:p.literal(2),id:P,origin:yl,ownerId:P,approval:p.object({id:P,index:p.number().int().min(0).max(7)}).strict().optional(),operationContext:Nq.optional(),actor:vt,environmentId:P,executor:vt,environmentDigest:yt,operation:_f,functionDigest:yt.nullable(),functionId:P.optional(),operationDigest:yt,sources:p.array(Cbe).max(100),resultRecipients:p.array(vt).min(1).max(100),resultApproval:xf.optional(),createdAt:ce,expiresAt:ce}).strict(),qS=p.object({intent:GS,signature:_t,sealed:jo}).strict();async function xc(e,t){return C({purpose:"run-"+t,origin:e.origin,id:e.id,intentDigest:await te(e)})}async function Gq(e,t,r){if(GS.parse(e),await te(t)!==e.operationDigest)throw new Error("The operation does not match the execution intent.");let i={intent:e,sealed:await wc(ft(C(t)),[{id:e.executor.id,publicKey:e.executor.encryption}],await xc(e,"input"))};return qS.parse({...i,signature:await Tt(i,r.signing,"run")})}async function kbe(e,t=Date.now()){let r=qS.parse(e),{signature:i,...n}=r;await nr(n,i,r.intent.actor.signing,"run");let{intent:o}=r,s=Date.parse(o.createdAt),a=Date.parse(o.expiresAt);if(s>t+3e4||a<=t||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(o.sources.map(c=>c.id)).size!==o.sources.length||new Set(o.resultRecipients.map(c=>c.id)).size!==o.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(o.resultApproval){let c=await Us(o.resultApproval),u=c.policy;if(c.authorityId!==o.actor.id||u.id!==o.id||u.origin!==o.origin||u.ownerId!==o.ownerId||u.contentType!==ge.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>C(l)===C(o.actor))||C(u.readers)!==C(o.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==o.id||C(u.producers[0].executor)!==C(o.executor)||u.producers[0].materialRevision!==1)throw new Error("Approve this execution result for its readers and selected executor.")}if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==o.executor.id||r.sealed.aad!==Ds(ft(await xc(o,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function qq(e,t,r){let i=await kbe(e);if(C(i.intent.executor)!==C(t))throw new Error("This operation belongs to another executor.");let n=await bc(i.sealed,r.encryption,t.id,await xc(i.intent,"input")),o=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(o);if(C(s)!==o||await te(s)!==i.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:i.intent,operation:s}}async function Os(e,t,r={}){let i=await on(e),n=i.policy,o=t.sources.find(c=>c.id===n.id);if(!o||t.origin!==n.origin||!await sO(i,o))throw new Error("The input changed after this execution was authorized.");if(C(t.actor)===C(t.executor)&&n.readers.some(c=>C(c)===C(t.actor)))return i;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(t.actor):c.function.id===t.functionId&&c.function.digest===t.functionDigest)&&C(c.executor)===C(t.executor)&&c.operations.includes(t.operation)&&Go(c,r.now)&&vl(c)>=Date.parse(t.expiresAt)).some(c=>"function"in c?t.operation===Q.function||t.operation===Q.refresh:t.operation===Q.function&&!c.callerProgram&&(!t.functionDigest||!c.functionDigests.includes(t.functionDigest))||!r.destinationPending&&c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:t.operation!==Q.command&&t.operation!==Q.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return i}async function Ec(e,t,r,i={}){let n=i.destination;await Os(e,t,{now:i.now,...typeof n=="function"?{destinationPending:!0}:{destination:n}});let o=await bc(e.sealed,r.encryption,t.executor.id,await Ns(e.policy,e.materialRevision));return typeof n=="function"&&await Os(e,t,{now:i.now,destination:n(o)}),o}var Ac=5,zi=1,aO=p.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Vq=p.object({format:p.literal(3),id:P,origin:yl,ownerId:P,name:be,executor:vt,operatorId:P,driver:p.literal("attached"),capabilities:p.array(_f).min(1).max(6),functionVersion:p.number().int().positive().optional(),httpVersion:p.number().int().positive().optional(),resultVersion:p.literal(1).optional(),isolation:p.enum(["process","container"]),commandImage:p.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),functionImage:p.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:aO.optional(),revision:p.number().int().positive()}).strict(),cO=p.object({manifest:Vq,signature:_t}).strict();async function uO(e,t){let r=Vq.parse(e),i={manifest:r,signature:await Tt(r,t.signing,"environment")};return await wl(i),i}async function wl(e){let t=cO.parse(e),{manifest:r}=t;if(await Mi(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(Q.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");return await nr(r,t.signature,r.executor.signing,"environment"),t}async function bl(e,t){let{manifest:r}=await wl(e);if(t.environmentId!==r.id||t.origin!==r.origin||t.environmentDigest!==await te(r)||C(t.executor)!==C(r.executor)||!r.capabilities.includes(t.operation)||t.operation===Q.function&&r.functionVersion!==Ac)throw new Error("This environment does not authorize the requested execution.")}var VS=p.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),KS=p.object({ok:p.boolean(),result:Nr.nullable(),error:p.object({code:p.string().max(100),message:p.string().max(1e3)}).nullable()}).strict(),Kq={id:P,intentDigest:yt,executorId:P,state:p.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:ce},Bq=p.object({...Kq,sealed:jo,signature:_t}).strict(),Hq=p.object({...Kq,format:p.literal(2),accessDigest:yt,proofDigest:yt,approval:xf,content:ir,previousDigest:yt.optional(),previous:Bq.optional(),signature:_t}).strict(),If=p.union([Bq,Hq]),Dbe=p.object({result:KS,proof:_t}).strict(),Wq=e=>{let{signature:t,content:r,approval:i,previous:n,...o}=e;return o};async function lO(e,t,r,i,n,o){await Us(n);let s={format:2,id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:o?.finishedAt??new Date().toISOString(),accessDigest:await te(n),...o?{previousDigest:await te(o)}:{}},a=await Tt({...s,resultDigest:await te(r)},i.signing,"execution-result"),c=ft(C({result:KS.parse(r),proof:a}));if(c.byteLength>14e5)throw new Sl;let u=await Af(c,n,e.id,e.executor,i,{bytes:c.byteLength}),l={...s,proofDigest:await te(a)},d=Hq.parse({...l,approval:n,content:u,...o?{previous:o}:{},signature:await Tt(l,i.signing,"receipt")});return await dO(d,e),d}var Sl=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function _l(e,t,r,i){let n=KS.parse(r);if(t==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(e.resultApproval)return lO(e,t,n,i,e.resultApproval);let o=ft(C(n));if(o.byteLength>14e5)throw new Sl;let s=await wc(o,e.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await xc(e,"result")),a={id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:new Date().toISOString(),sealed:s};return If.parse({...a,signature:await Tt(a,i.signing,"receipt")})}async function dO(e,t){let r=If.parse(e);if("content"in r){await nr(Wq(r),r.signature,t.executor.signing,"receipt");let o=await Us(r.approval),s=o.policy;if(r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.accessDigest!==await te(o)||o.authorityId!==t.actor.id||!s.authorities.some(a=>C(a)===C(t.actor))||s.id!==t.id||s.origin!==t.origin||s.ownerId!==t.ownerId||s.contentType!==ge.executionResult||s.grants.length||t.resultApproval&&C(t.resultApproval)!==C(o))throw new Error("The result does not belong to the requested execution.");if(!t.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await te(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await dO(r.previous,t),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await on(r.content),!MS(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(t.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:i,...n}=r;if(await nr(n,i,t.executor.signing,"receipt"),r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.sealed.aad!==Ds(ft(await xc(t,"result")))||C(r.sealed.recipients.map(o=>o.header.kid).sort())!==C(t.resultRecipients.map(o=>o.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function Jq(e,t,r,i){if(await dO(e,t),"content"in e){if(!e.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await bc(e.content.sealed,i.encryption,r,await Ns(e.content.policy,e.content.materialRevision)),a=Dbe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await te(a.proof)!==e.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=Wq(e);if(await nr({...u,resultDigest:await te(a.result)},a.proof,t.executor.signing,"execution-result"),e.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await bc(e.sealed,i.encryption,r,await xc(t,"result")),o=KS.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(e.state==="succeeded"!==o.ok)throw new Error("The encrypted result does not match its completion state.");return o}var Obe=p.enum(["http","command","function","connect","refresh","revoke"]),Rc=p.object({id:P,ownerId:P,actorId:P,environmentId:P,kind:Obe,state:VS,intent:GS,requestSignature:_t,receipt:If.nullable(),error:p.string().nullable(),createdAt:ce,startedAt:ce.nullable(),finishedAt:ce.nullable()}).strict(),BS=p.object({name:be,approval:xf}).strict(),Zq=p.object({kind:p.literal("function"),functionId:P,definition:ks,arguments:Mt.default({}),outputs:p.record(p.string(),BS).default({})}).strict(),Ic=p.discriminatedUnion("kind",[p.object({kind:p.literal("http"),request:yc,save:p.record(p.string(),BS).default({})}).strict(),p.object({kind:p.literal("command"),...vc.shape}).strict(),p.object({kind:p.enum(["connect","refresh","revoke"]),input:Nr}).strict()]);var Nbe=p.object({email:p.boolean(),environments:p.boolean(),ssh:p.boolean(),objects:p.boolean(),payments:p.boolean()}),Xq=p.object({principal:Cs.nullable(),credentialId:P.nullable(),wrappedKey:AS.nullable(),requestId:P.nullable(),server:p.object({name:be}),features:Nbe,principals:p.array(Cs)}),OXe=p.object({email:p.email().max(254),returnTo:p.string().max(2048).optional(),locale:gq.default("ja"),principalId:P.optional()}).strict(),NXe=p.object({intent:p.enum(["register","authenticate"]),name:be.optional(),principalId:P.optional(),credentialId:P.optional(),returnTo:p.string().max(2048).optional()}).strict(),UXe=p.object({challengeId:P,credential:p.json(),publicKey:Jr.optional(),existingPublicKey:Jr.optional(),wrappedKey:AS.optional()}).strict();var HS=class extends Error{constructor(r,i,n){super(n);this.code=r;this.status=i}code;status},WS=class{constructor(t){this.identity=t}identity;async response(t,r={}){if(!t.startsWith("/api/")||t.includes("\\")||/[\u0000-\u001f]/.test(t))throw new Error("Use a path beginning with /api/.");let i=new URL(t,this.identity.origin);if(i.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(i,{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 o;try{o=p.object({error:p.object({code:p.string(),message:p.string()})}).parse(await n.json())}catch{throw new HS("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new HS(o.error.code,n.status,o.error.message)}return n}async json(t,r={},i){let n=await this.response(t,r),o=n.status===204?null:await n.json();return i?i.parse(o):o}async session(){return this.json("/api/session",{},Xq)}};import{chmod as Ube,lstat as Lbe,mkdir as Mbe,open as fO,readFile as zbe,rename as jbe,rm as Fbe}from"node:fs/promises";import{dirname as Gbe,join as mO,resolve as qbe}from"node:path";import{homedir as Vbe}from"node:os";import{randomUUID as Kbe}from"node:crypto";var Qq=p.object({origin:p.url(),principalId:p.uuid(),token:p.string().min(20),keys:Tq.nullable(),binding:vt.nullable()}).strict().refine(e=>!!e.keys==!!e.binding&&(!e.binding||e.binding.principalId===e.principalId),"Use the keys bound to this identity."),Bbe=p.object({current:p.uuid(),identities:p.array(Qq).min(1)}).strict().refine(e=>e.identities.some(t=>t.principalId===e.current),"The current identity is missing.");function hO(){return mO(process.env.XDG_CONFIG_HOME||mO(Vbe(),".config"),"foundation","identity.json")}function pO(e=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let t;try{t=new URL(e)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return t.origin}async function Hbe(){try{let e=hO(),t=await Lbe(e);if(!t.isFile()||t.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&t.mode&63&&await Ube(e,384),Bbe.parse(JSON.parse(await zbe(e,"utf8")))}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function eV(e,t){let r=process.env.FOUNDATION_TOKEN,i=t||(r?void 0:process.env.FOUNDATION_PRINCIPAL_ID),n=await Hbe(),o;if(n){if(o=n.identities.find(a=>a.principalId===(i??n.current)),i&&!o&&!r)throw new Error("No saved identity has principal "+i+". Run foundation identity list.")}else if(i&&!r)throw new Error("Run foundation login to sign in on this machine.");let s=pO(e||process.env.FOUNDATION_ORIGIN||o?.origin);if(r){if(e&&process.env.FOUNDATION_ORIGIN&&s!==pO(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let a=process.env.FOUNDATION_PRINCIPAL_ID,c=process.env.FOUNDATION_PRIVATE_KEYS,u=process.env.FOUNDATION_KEY_BINDING;if(!a)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return Qq.parse({origin:s,principalId:a,token:r,keys:c?JSON.parse(Buffer.from(c,"base64url").toString("utf8")):null,binding:u?JSON.parse(Buffer.from(u,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!o)throw new Error("Run foundation login to sign in on this machine.");if(s!==pO(o.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...o,origin:s}}async function Yq(e){if(process.platform==="win32")return;let t=await fO(e,"r");try{await t.sync()}finally{await t.close()}}async function gO(e,t,r){let i=qbe(e),n=Gbe(i);if(await Mbe(n,{recursive:!0,mode:448}),!r){let s=await fO(i,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await Yq(n);return}let o=mO(n,".foundation-"+Kbe());try{let s=await fO(o,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await jbe(o,i),await Yq(n)}finally{await Fbe(o,{force:!0})}}import{mkdir as Rhe}from"node:fs/promises";import{join as Pj}from"node:path";import{setTimeout as lWe}from"node:timers/promises";import{dirname as RUe,join as P4}from"node:path";function Ls(e){switch(e.kind){case"oauth":let t=e.config.application;return{family:"oauth",application:t,requiresApp:t==="required",browserAuthorization:e.config.grantType!=="client_credentials",revocable:e.config.revoke?.tokenOnly===!0,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"ovh":{let r=e.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function tV(e,t){return[...new Set([...e.required??[],...t??e.default])]}function xl(e){return Ls(e).requiresApp}var Wbe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),rV=Mt.refine(e=>Object.keys(e).every(t=>!Wbe.has(t)),"Keep method-specific facts separate from common facts."),Ms=p.object({accountId:p.string().max(2e3).nullable(),accountName:p.string().max(2e3),accountVerified:p.boolean(),scopes:p.array(p.string().max(1e3)).max(200),scopesStatus:p.enum(["unknown","requested","reported"]),authorization:rV,details:rV}).strict();function yO(e){if(e.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let t="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:e.oauth?.account??"",accountName:e.oauth?.accountName??"",accountVerified:e.oauth?.accountVerified??!1,scopes:t??e.oauth?.scopes??[],scopesStatus:t?"requested":e.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function El(e){if(e.method.kind!=="token"&&e.method.kind!=="approval"||!e.fields)throw new Error("Use input credential material.");return"facts"in e&&e.facts?Ms.parse(e.facts):Ms.parse({accountId:null,accountName:e.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function vO(e){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let t="ovh"in e?e.ovh:void 0;if(!t){let r="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return Ms.parse({accountId:t.user?t.account+"/"+t.user:t.account,accountName:t.account+(t.user?" / "+t.user:""),accountVerified:!0,scopes:t.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:t},details:{ovh:t}})}function SO(e){if(e.method.kind!=="aws"||!e.aws)throw new Error("Use AWS connection material.");return Ms.parse({accountId:e.aws.identity?dl(e.aws.identity.arn):null,accountName:e.aws.identity?e.aws.identity.accountId+" / "+e.aws.identity.arn.split(":").at(-1):"",accountVerified:!!e.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:fq(e.aws)},details:{aws:mq(e.aws)}})}var Jbe={oauth:yO,token:El,aws:SO,ovh:vO,approval:El};function $f(e){return Jbe[e.method.kind](e)}var FV=lt(EV(),1);var Ho=class extends Error{template;position;hint;constructor(e,t,r,i){super(`${i} (at position ${t}): ${r}`),this.template=e,this.position=t,this.hint=r,this.name="TemplateParseError"}},w_e=class extends Ho{constructor(e,t){super(e,t,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},b_e=class extends Ho{constructor(e,t){super(e,t,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},__e=class extends Ho{constructor(e,t){super(e,t,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},x_e=class extends Ho{char;constructor(e,t,r){super(e,t,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},E_e=class extends Ho{constructor(e,t){super(e,t,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},A_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},R_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},ow=class extends Ho{varSpec;constructor(e,t,r,i,n){super(e,t,r,i),this.varSpec=n,this.name="InvalidVarSpecError"}},$O=class extends ow{constructor(e,t){super(e,t,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},I_e=class extends ow{offendingChar;constructor(e,t,r,i){super(e,t,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${i}' or pct-encode it.`,`Invalid character '${i}' in varname`,r),this.offendingChar=i,this.name="InvalidVarNameError"}},$_e=class extends ow{prefix;constructor(e,t,r,i){super(e,t,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${i}'`,r),this.prefix=i,this.name="InvalidPrefixError"}},AV=class extends ow{constructor(e,t){super(e,t,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},P_e=class extends Ho{char;constructor(e,t,r){super(e,t,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},T_e=class extends Error{variableName;hint;constructor(e,t,r){super(`${r} for '${e}': ${t}`),this.variableName=e,this.hint=t,this.name="TemplateExpansionError"}},C_e=class extends T_e{prefix;valueType;constructor(e,t,r){super(e,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${t}' is not applicable to ${r} values`),this.prefix=t,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},k_e=["","+",".","/",";","?","&","#"],kV={"":{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}},D_e=new TextEncoder,RV="0123456789ABCDEF",IV=e=>Fs(wr(48,57),wr(65,70),wr(97,102))(e.charCodeAt(0)),kf=(e,t)=>e[t]==="%"&&t+2<e.length&&IV(e[t+1])&&IV(e[t+2]);function PO(e,t){let r=e[t];return r==null?0:Fs(DV,OV,Pc("_"))(r)?1:kf(e,t)?3:0}function O_e(e,t){if(kf(e,t))return 3;let{char:r,size:i}=Df(e,t);return U_e(r)?i:0}function Df(e,t){let r=e.codePointAt(t);if(r==null)return{char:"",size:0};let i=r>65535?2:1;return{char:e.slice(t,t+i),size:i}}var DO=e=>t=>{let r="";for(let i=0;i<t.length;){if(e&&kf(t,i)){r+=t.slice(i,i+3),i+=3;continue}let{char:n,size:o}=Df(t,i);r+=Fs(NV,s=>e&&N_e(s))(n)?n:UV(n),i+=o}return r};function Il(e){let t="";for(let r=0;r<e.length;){if(kf(e,r)){t+=e.slice(r,r+3),r+=3;continue}let{char:i,size:n}=Df(e,r);t+=NV(i)?i:UV(i),r+=n}return t}function Tf(e,t){let r="",i=0;for(let n=0;n<e.length&&i<t;i++){if(kf(e,n)){r+=e.slice(n,n+3),n+=3;continue}let{char:o,size:s}=Df(e,n);r+=o,n+=s}return r}var DV=e=>Fs(wr(65,90),wr(97,122))(e.charCodeAt(0)),OV=e=>wr(48,57)(e.charCodeAt(0)),NV=e=>Fs(DV,OV,t=>"-._~".includes(t))(e),N_e=e=>":/?#[]@!$&'()*+,;=".includes(e),U_e=e=>L_e(e.codePointAt(0)),L_e=e=>e!=null&&Fs(Pc(33),wr(35,36),Pc(38),wr(40,59),Pc(61),wr(63,91),Pc(93),Pc(95),wr(97,122),Pc(126),M_e,z_e)(e);function M_e(e){if(e<65536)return Fs(wr(160,55295),wr(63744,64975),wr(65008,65519))(e);if(e>983037)return!1;let t=e%65536;return t<=65533&&(e<917504||t>=4096)}var z_e=e=>Fs(wr(57344,63743),wr(983040,1048573),wr(1048576,1114109))(e),UV=e=>Array.from(D_e.encode(e)).map(t=>`%${RV[t>>4]}${RV[t&15]}`).join(""),wr=(e,t)=>r=>e<=r&&r<=t,Pc=e=>t=>e===t,Fs=(...e)=>t=>e.some(r=>r(t));function LV(e,t,r){return e.map(i=>i.kind==="literal"?i.text:j_e(i.vars,i.operator,t,r)).join("")}function j_e(e,t,r,i){let n=kV[t],o=e.flatMap(s=>F_e(s,r[s.name],n,i));return o.length<1?"":`${n.first}${o.join(n.sep)}`}function F_e(e,t,r,i){if(t==null)return[];if(J_e(t)){let n=K_e(t,r.allowReserved);return n.length<1?[]:$V(e,"list",i)?q_e(e,n,r):[]}if(W_e(t)){let n=B_e(t,r.allowReserved);return n.length<1?[]:$V(e,"associative",i)?V_e(e,n,r):[]}return G_e(e,t,r)}function G_e(e,t,r){let i=String(t),n=e.prefix==null?i:Tf(i,e.prefix),o=DO(r.allowReserved)(n);return r.named?[Cf(Il(e.name),o,r)]:[o]}function q_e(e,t,r){let i=Il(e.name);if(e.explode)return r.named?t.map(o=>Cf(i,o,r)):[...t];let n=t.join(",");return r.named?[Cf(i,n,r)]:[n]}function V_e(e,t,r){if(e.explode)return t.map(([n,o])=>Cf(n,o,r));let i=t.flat(1).join(",");return r.named?[Cf(Il(e.name),i,r)]:[i]}var Cf=(e,t,r)=>t===""?`${e}${r.ifEmpty}`:`${e}=${t}`,K_e=(e,t)=>e.filter(r=>r!=null).map(String).map(DO(t)),B_e=(e,t)=>Object.entries(e).map(([r,i])=>[r,H_e(i)]).filter(([,r])=>r!=null).map(r=>r.map(DO(t)));function H_e(e){if(e==null)return null;if(!Array.isArray(e))return String(e);let t=e.filter(r=>r!=null).map(String);return t.length<1?null:t.join(",")}var W_e=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),J_e=e=>Array.isArray(e);function $V(e,t,{report:r,strict:i}){if(e.prefix==null)return!0;let n=new C_e(e.name,e.prefix,t);if(r(n),i)throw n;return!1}function Z_e(e,t,r){return TO(e,t,r,0,0,{})}function TO(e,t,r,i,n,o){if(i>=e.length){if(n!==t.length)return null;let a=xxe(o);return LV(e,a,r)===t?a:null}let s=e[i];if(s.kind==="literal")return t.startsWith(s.text,n)?TO(e,t,r,i+1,n+s.text.length,o):null;for(let a of X_e(e,t,i,n)){let c=t.slice(n,a);for(let u of Q_e(s.vars,s.operator,c)){let l=OO(o,u);if(l==null)continue;let d=TO(e,t,r,i+1,a,l);if(d!=null)return d}}return null}function*X_e(e,t,r,i){let n=e.slice(r+1).find(o=>o.kind==="literal"&&o.text!=="");if(n==null||n.kind!=="literal"){yield*Y_e(t.length,i);return}for(let o=t.indexOf(n.text,i);o>=0;o=t.indexOf(n.text,o+1))yield o}function*Y_e(e,t){for(let r=e;r>=t;r--)yield r}function*Q_e(e,t,r){if(r===""){yield*exe(e,t);return}let i=kV[t];if(!r.startsWith(i.first))return;let n=r.slice(i.first.length);yield*i.named?uxe(e,i,n):txe(e,i,n)}var exe=(e,t)=>(t===""||t==="+")&&e.length===1?[js(e[0],"")]:[{}],txe=(e,t,r)=>CO(e,t,NO(r,t.sep),0,0);function*CO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of rxe(o,t,r,n))for(let a of CO(e,t,r,i+1,s.index)){let c=OO(s.bindings,a);c!=null&&(yield c)}yield*CO(e,t,r,i+1,n)}function*rxe(e,t,r,i){if(i>=r.length)return;let n=r.length-i;for(let o=1;o<=n;o++){let s=r.slice(i,i+o);for(let a of nxe(e,t,s))yield{bindings:a,index:i+o}}}function*nxe(e,t,r){let i=MV(e,t,r.join(t.sep));if(e.prefix!=null){yield*i;return}e.explode&&r.length>0&&(yield*ixe(e,t,r)),yield*i}function*ixe(e,t,r){let i=zV(r,t.allowReserved);if(i==null)return;let n=oxe(r,t);n!=null&&(yield js(e,n)),yield js(e,i)}var oxe=(e,t)=>sxe(e.join(t.sep),t);function sxe(e,t){let r=[];for(let i=0;i<e.length;){let n=e.indexOf("=",i);if(n<0)return null;let o=n+1,s=axe(e,o,t.sep),a=Bo(e.slice(i,n),t.allowReserved),c=Bo(e.slice(o,s),t.allowReserved);if(a==null||c==null)return null;r.push([a,c]),i=s+t.sep.length}return r.length<1?null:Object.fromEntries(r)}function axe(e,t,r){for(let i=t;i<e.length;i++)if(cxe(e,i,r))return i;return e.length}var cxe=(e,t,r)=>{if(!e.startsWith(r,t))return!1;let i=t+r.length;for(let n=i;n<e.length;n++){if(e[n]==="=")return n>i;if(e.startsWith(r,n))return!1}return!1};function*MV(e,t,r){let i=Bo(r,t.allowReserved);if(i==null)return;let n=js(e,i);if(e.prefix!=null){yield n;return}let o=NO(r,",");if(o.length<2){yield n;return}let s=zV(o,t.allowReserved);if(s==null){yield n;return}let a=o.length%2===0?vxe(o,t.allowReserved):null;a!=null&&(yield js(e,a)),yield js(e,s),yield n}var uxe=(e,t,r)=>kO(e,t,NO(r,t.sep).map(yxe),0,0);function*kO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of lxe(o,t,r,n,e))for(let a of kO(e,t,r,i+1,s.index)){let c=OO(s.bindings,a);c!=null&&(yield c)}yield*kO(e,t,r,i+1,n)}function*lxe(e,t,r,i,n){if(!(i>=r.length)){if(e.explode&&e.prefix==null){yield*pxe(e,t,r,i,n);return}yield*dxe(e,t,r,i)}}function*dxe(e,t,r,i){let n=r[i];if(n.name===Il(e.name))for(let o of MV(e,t,n.value))yield{bindings:o,index:i+1}}function*pxe(e,t,r,i,n){yield*fxe(e,t,r,i),yield*hxe(e,t,r,i,n)}function*fxe(e,t,r,i){let n=[...mxe(Il(e.name),t,r,i)];n.length>0&&(yield{bindings:js(e,n),index:i+n.length})}function*mxe(e,t,r,i){for(let n=i;n<r.length&&r[n].name===e;n++){let o=Bo(r[n].value,t.allowReserved);if(o==null)return;yield o}}function*hxe(e,t,r,i,n){let o=[...gxe(t,r,i,new Set(n.map(s=>Il(s.name))))];o.length>0&&(yield{bindings:js(e,Object.fromEntries(o)),index:i+o.length})}function*gxe(e,t,r,i){for(let n=r;n<t.length;n++){let o=t[n];if(n>r&&i.has(o.name))return;let s=Bo(o.name,e.allowReserved),a=Bo(o.value,e.allowReserved);if(s==null||a==null)return;yield[s,a]}}function yxe(e){let t=e.indexOf("=");return t<0?{name:e,value:""}:{name:e.slice(0,t),value:e.slice(t+1)}}function vxe(e,t){let r=[];for(let i=0;i<e.length;i+=2){let n=Bo(e[i],t),o=Bo(e[i+1],t);if(n==null||o==null)return null;r.push([n,o])}return Object.fromEntries(r)}function zV(e,t){let r=[];for(let i of e){let n=Bo(i,t);if(n==null)return null;r.push(n)}return r}function Bo(e,t){if(t)return e;try{return decodeURIComponent(e)}catch{return null}}var js=({name:e,prefix:t},r)=>({[e]:{value:r,prefix:t}});function OO(e,t){let r={...e};for(let[i,n]of Object.entries(t)){let o=r[i];if(o==null){r[i]=n;continue}let s=Sxe(o,n);if(s==null)return null;r[i]=s}return r}var Sxe=(e,t)=>iw(e)||iw(t)?wxe(e,t):bxe(e.value,t.value)?e:null;function wxe(e,t){let r=PV(e.value),i=PV(t.value);if(r==null||i==null)return null;let n=iw(e),o=iw(t);if(!n&&!o)return null;if(n&&!o)return Tf(i,e.prefix)===r?t:null;if(!n&&o)return Tf(r,t.prefix)===i?e:null;let s=e.prefix,a=t.prefix;return s<=a?Tf(i,s)===r?t:null:Tf(r,a)===i?e:null}var iw=e=>e.prefix!=null,PV=e=>typeof e=="string"?e:null;function bxe(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,i)=>r===t[i]):TV(e)?TV(t)&&_xe(Object.entries(e),Object.entries(t)):e===t}var _xe=(e,t)=>e.length===t.length&&e.every(([r,i],n)=>{let[o,s]=t[n];return r===o&&i===s}),TV=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xxe=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value])),NO=(e,t)=>t===""?[e]:e.split(t),Exe=["=",",","!","@","|"];function Axe(e,t,r){let i=a=>{throw a};if(e.length<1)return i(new E_e(t,r));let n=e[0];if(Pxe(n))return i(new A_e(t,r+1,n));if(!CV(n)&&PO(e,0)<1)return i(new R_e(t,r+1,n));let o=CV(n)?n:"",s=o===""?0:1;return{kind:"expression",operator:o,vars:Rxe(e,t,r+1,s)}}function Rxe(e,t,r,i){if(i>=e.length)throw new $O(t,r+i);let n=[];for(let o=i;o<e.length;){if(e[o]===",")throw o===e.length-1?new AV(t,r+o):new $O(t,r+o);let s=o,a=Ixe(e,o);if(a===s)throw new $O(t,r+o);let c=e.slice(s,a);o=a;let u=$xe(e,t,r,o,c);if(o=u.index,o<e.length&&e[o]!==",")throw u.used?new P_e(t,r+o,e[o]):new I_e(t,r+o,c,e[o]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),o<e.length&&(o++,o>=e.length))throw new AV(t,r+o-1)}return n}function Ixe(e,t){let r=t,i=!0;for(;r<e.length;){let n=PO(e,r);if(n>0){r+=n,i=!1;continue}if(e[r]!=="."||i||PO(e,r+1)<1)break;r++,i=!0}return r}function $xe(e,t,r,i,n){if(e[i]==="*")return{explode:!0,index:i+1,used:!0};if(e[i]!==":")return{explode:!1,index:i,used:!1};let o=i+1,s=o;for(;s<e.length&&Txe(e[s]);)s++;let a=e.slice(o,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new $_e(t,r+i,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function CV(e){return k_e.includes(e)&&e!==""}function Pxe(e){return Exe.includes(e)}function Txe(e){let t=e.charCodeAt(0);return t>=48&&t<=57}function Cxe(e,t){let{report:r}=t,i=[],n=o=>{let s=i.at(-1);s?.kind==="literal"?i[i.length-1]={kind:"literal",text:s.text+o}:i.push({kind:"literal",text:o})};for(let o=0;o<e.length;){let s=e[o];if(s==="{"){let l=e.indexOf("}",o+1);if(l<0){r(new w_e(e,o)),n(e.slice(o));break}let d=e.indexOf("{",o+1);if(d>=0&&d<l){r(new __e(e,d)),n(e.slice(o,l+1)),o=l+1;continue}let m=e.slice(o+1,l);try{i.push(Axe(m,e,o))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(e.slice(o,l+1))}o=l+1;continue}if(s==="}"){r(new b_e(e,o)),n(s),o++;continue}let a=O_e(e,o);if(a>0){n(e.slice(o,o+a)),o+=a;continue}let{char:c,size:u}=Df(e,o);r(new x_e(e,o,c)),n(c),o+=u}return i}var sw=class jV{uriTemplate;options;#e;#t;constructor(t,r={}){this.uriTemplate=t,this.options=r,this.#t=Uxe(r),this.#e=kxe(Cxe(t,this.#t)),Object.freeze(this)}static parse(t,r={}){return new jV(t,r)}get tokens(){return this.#e}expand=t=>LV(this.#e,t,this.#t);match=t=>Z_e(this.#e,t,this.#t);toString=()=>this.uriTemplate},kxe=e=>Object.freeze(e.map(Dxe)),Dxe=e=>e.kind==="literal"?Object.freeze({kind:"literal",text:e.text}):Object.freeze({kind:"expression",operator:e.operator,vars:Object.freeze(e.vars.map(Oxe))}),Oxe=e=>Object.freeze({name:e.name,explode:e.explode,...e.prefix==null?{}:{prefix:e.prefix}}),Nxe=()=>{},Uxe=({strict:e,report:t})=>(t??=Nxe,e??=!0,t=e?Lxe(t):t,{strict:e,report:t}),Lxe=e=>t=>{throw e(t),t};var Gs=class extends Error{constructor(r,i){super(i);this.code=r}code};function Mxe(e,t){return!e.when||t[e.when.field]===void 0||e.when.values.includes(t[e.when.field])}function GV(e,t,r={}){let i=(o,s)=>{throw new Gs(o,s)},n={...r,...t};for(let o of e)n[o.name]===void 0&&o.defaultValue!==void 0&&(n[o.name]=o.defaultValue);for(let o of e){if(!Mxe(o,n)){delete n[o.name];continue}o.required!==!1&&!n[o.name]&&i("missing_field","Complete the required service fields."),n[o.name]?.includes("\0")&&i("invalid_field","Check the service fields."),o.choices&&n[o.name]&&!o.choices.some(s=>s.value===n[o.name])&&i("invalid_field","Choose an available service setting."),o.pattern&&(o.pattern.length>200||!(0,FV.default)(o.pattern))&&i("invalid_pattern","Use a simple field validation pattern."),o.pattern&&n[o.name]&&!new RegExp(o.pattern,"u").test(n[o.name].slice(0,1e3))&&i("invalid_field","Check the service fields.")}return Object.keys(t).some(o=>!e.some(s=>s.name===o))&&i("invalid_field","Remove unrecognized service fields."),n}function qs(e,t,r={}){let i=GV(e,t,r),n={};for(let o of e){let s=o.choices?.find(a=>a.value===i[o.name]);for(let[a,c]of Object.entries(s?.values??{})){if(e.some(u=>u.name===a)||a in n&&n[a]!==c)throw new Gs("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...i,...n}}function UO(e,t){for(let[r,i]of Object.entries(t)){let n=e.find(o=>o.name===r);if(!n)throw new Gs("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&i!=="")throw new Gs("encrypted_input_required","Supply private material directly with your encryption keys.")}return GV(e.map(r=>({...r,required:!1,defaultValue:void 0})),t)}function $l(e,t){return UO(e,Object.fromEntries(e.filter(r=>r.secret===!1&&t[r.name]).map(r=>[r.name,t[r.name]])))}function qV(e,t=$f(e)){return t.accountVerified?t.accountId:null}function VV(e,t=$f(e)){let i=(e.method.kind==="oauth"||e.method.kind==="ovh"||e.method.kind==="token"&&!!(e.method.config.identity||e.method.config.resolver||e.method.config.bindFields))&&e.method.kind!=="aws"?$l(e.method.config.fields,e.fields??{}):{};return{format:e.format,generation:e.generation,methodId:e.methodId,method:e.method,appId:e.appId,appGeneration:e.appGeneration,..."implicitApp"in e&&e.implicitApp?{implicitApp:{clientId:e.implicitApp.clientId,generation:e.implicitApp.generation,fields:e.implicitApp.fields}}:{},account:t.accountId,accountVerified:t.accountVerified,scopes:[...t.scopes].sort(),...Object.keys(i).length?{fields:i}:{},...t.authorization,...e.state?{state:e.state}:{}}}var Vs=p.record(p.string().max(100),p.string().max(16384)),aw=p.object({format:p.literal(1),methodId:p.string().min(1),generation:P,clientId:p.string().max(1e3),clientSecret:p.string().max(16384).optional(),fields:Vs}).strict(),LO=p.object({accessToken:p.string().min(1).max(16384),refreshToken:p.string().min(1).max(16384).optional(),expiresAt:p.number().nullable(),refreshExpiresAt:p.number().optional(),scopes:p.array(p.string()),requestedScopes:p.array(p.string()).optional(),account:p.string(),accountName:p.string(),accountVerified:p.boolean().optional(),scopesStatus:p.enum(["unknown","requested","reported"]).optional(),extra:Vs,facts:Mt}).strict(),Of={format:p.literal(2),methodId:p.string().min(1),method:fl,generation:P,appId:P.nullable(),appGeneration:P.nullable(),state:p.literal("reconnect").optional()},Wo=p.never().optional(),Pl=p.union([p.object({...Of,method:$S,oauth:LO.optional(),requestedScopes:p.array(p.string()).optional(),implicitApp:aw.optional(),fields:Vs.optional(),aws:Wo}).strict(),p.object({...Of,method:PS,fields:Vs,facts:Ms.optional(),oauth:Wo,aws:Wo}).strict(),p.object({...Of,method:kS,fields:Vs,oauth:Wo,aws:Wo}).strict(),p.object({...Of,method:CS,fields:Vs,ovh:gf.optional(),requestedScopes:p.array(p.string()).optional(),oauth:Wo,aws:Wo}).strict(),p.object({...Of,method:TS,aws:wS,oauth:Wo,fields:Wo}).strict()]).superRefine((e,t)=>{if("implicitApp"in e&&e.implicitApp&&(e.method.kind!=="oauth"||e.method.config.application!=="implicit"||e.implicitApp.methodId!==e.methodId)&&t.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),e.method.kind==="oauth"&&e.fields)try{UO(e.method.config.fields,e.fields)}catch{t.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}xl(e.method)&&(!e.appId||!e.appGeneration)&&t.addIssue({code:"custom",message:"Bind the application required by this connection."}),!xl(e.method)&&e.appId!==null&&t.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!e.appId!=!!e.appGeneration&&t.addIssue({code:"custom",message:"Bind the application and its generation together."}),e.method.kind==="oauth"&&e.method.config.grantType==="client_credentials"&&!("requestedScopes"in e&&e.requestedScopes)&&!e.oauth?.requestedScopes&&t.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),jYe=p.object({methodId:p.string().min(1).max(200),clientId:p.string().max(1e3),generation:P,fields:Vs.optional()}).strict(),zxe=p.object({methodId:p.string().min(1).max(200),methodKind:YD,http:IS.optional(),generation:P,authorizationDigest:yt,appId:P.nullable(),accountId:p.string().max(2e3).nullable(),accountVerified:p.boolean(),scopes:p.array(p.string().max(1e3)).max(200),scopesStatus:p.enum(["unknown","requested","reported"]),outputs:p.array(p.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:p.enum(["ready","reconnect"]),revocable:p.literal(!0).optional(),fields:Vs.optional(),aws:bS.optional(),ovh:gf.optional()}).strict();async function KV(e,t=$f(e)){let{outputs:r,revocable:i}=Ls(e.method),n=e.method.kind!=="aws"&&e.fields?$l(e.method.config.fields,e.fields):{},o=await te(VV(e,t));return zxe.parse({methodId:e.methodId,methodKind:e.method.kind,...e.method.http?{http:e.method.http}:{},generation:e.generation,authorizationDigest:o,appId:e.appId,accountId:qV(e,t),accountVerified:t.accountVerified,scopes:t.scopes,scopesStatus:t.scopesStatus,outputs:r,state:e.state??"ready",...i?{revocable:i}:{},...Object.keys(n).length?{fields:n}:{},...t.details})}var jxe=p.array(p.object({name:p.string(),label:p.string(),value:p.string()}).strict()),BV=p.object({methodName:be,account:p.string().max(2e3),settings:jxe.optional()}).strict();var MO=p.discriminatedUnion("action",[p.object({action:p.literal("refresh"),id:P}).strict(),p.object({action:p.literal("revoke"),id:P}).strict()]);var zO=gl.extend({name:be}),JYe=gl.extend({previousSignature:_t.optional()}).strict(),ZYe=p.object({name:be,content:ir,labels:BV.optional(),version:p.number().int().positive().optional()}).strict(),jO=p.object({content:ir,version:p.number().int().positive()}).strict(),HV=p.object({id:P,reason:p.enum(["grantExpired","recipients"]),remove:p.array(P).max(1e3).default([])}).strict(),XYe=p.record(P,p.object({version:p.number().int().positive(),content:ir}).strict()),WV=p.object({id:P,name:be,version:p.number().int().positive(),content:ir,policy:qo}).strict(),JV=p.object({registration:cO,stoppedAt:p.iso.datetime().nullable(),heartbeatAt:p.iso.datetime().nullable()}).strict(),ZV=p.object({lease:P,request:qS,sources:p.array(ir).max(100)}).strict().nullable(),Fxe=p.object({lease:P}).strict(),YYe=Fxe.extend({receipt:If}).strict(),Nf=p.object({id:P,resource_id:P,executor_id:P,expected_revision:p.number().int().positive(),state:p.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:p.string().regex(/^\d+$/),result:ir.nullable()}),QYe=p.object({id:P,resourceId:P,expectedRevision:p.number().int().positive()}).strict(),Gxe=p.object({fence:p.string().regex(/^\d+$/)}).strict(),eQe=Gxe.extend({content:ir}).strict(),tQe=p.object({id:P,executionId:P,index:p.number().int().nonnegative(),stateDigest:yt,expiresAt:ce}).strict(),rQe=p.object({id:P,executionId:P,context:p.string(),sealed:jo.nullable(),expiresAt:ce,receivedAt:ce.nullable()}).strict();var qxe=p.object({binding:vt,verifiedAt:ce}).strict(),FO=p.object({origin:p.url(),ownerId:P,signerId:P,revision:p.number().int().positive(),keys:p.array(qxe).max(1e3)}).strict(),Vxe=p.object({version:p.number().int().positive(),signature:_t}).strict(),GO=p.object({keyring:Vxe.nullable()}).strict(),cQe=p.object({version:p.number().int().positive().nullable(),signature:_t}).strict();function XV(e,t){return Tt(FO.parse(e),t,"keyring")}function YV(e){return FO.parse(JSON.parse(NS(Iq(e.split(".")[1]??""))))}async function QV(e,t){let r=FO.parse(await bf(e,t.signing,"keyring"));if(r.signerId!==t.id)throw new Error("Another identity signed this keyring.");return r}var Tl=lt(t3(),1);var Me=class extends Error{constructor(r,i,n,o){super(n);this.status=r;this.code=i;this.details=o}status;code;details};function M(e,t,r,i){throw new Me(e,t,r,i)}var Kxe=Tl.default.IPv6.parseCIDR("2000::/3"),Bxe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function uw(e){if(!Tl.default.isValid(e)||e.includes("%"))return!1;let t=Tl.default.parse(e);return Bxe.has(t.range())&&(!(t instanceof Tl.default.IPv6)||t.match(Kxe))}function Pn(e,t){let r;try{r=new URL(e)}catch{M(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===t)&&M(400,"invalid_url","Choose a public HTTPS destination.");let i=r.hostname.replace(/^\[|\]$/g,"");return(i==="localhost"||i.endsWith(".localhost")||i.endsWith(".local")||Tl.default.isValid(i)&&!uw(i))&&M(400,"private_destination","Choose a public HTTPS destination."),r}function Cl(e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.body))}catch{M(502,"invalid_response","The service returned an invalid response.")}return(!t||typeof t!="object"||Array.isArray(t))&&M(502,"invalid_response","The service returned an invalid response."),t}function Uf(e){return[...e.connectionId?[{id:e.connectionId}]:[],...e.bindings.flatMap(t=>t.parts.filter(r=>typeof r!="string"))]}function qO(e,t,r){e.method.http||M(400,"invalid_http_connection","This connection does not provide HTTP authentication.");let i=e.method.http.urlField,n=i&&e.fields?.[i];i&&!n&&M(409,"reconnect_required","Reconnect with a destination URL.");let o=Pn(t.url??n??"",r);return n&&o.origin!==Pn(n,r).origin&&M(400,"invalid_destination","Use this connection only at its configured destination host."),o.href}function r3(e,t,r,i){let n=new URL(e),o={...t},s=[];Object.keys(t).some(l=>["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase()))&&M(400,"invalid_authentication","Use HTTP headers that do not override routing or transport settings.");let a=(l,d=!0)=>{Object.hasOwn(i,l)||M(400,"invalid_authentication","Choose an available authentication output.");let m=i[l];return d&&s.push(m),m},c=(l,d)=>{(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(l)||["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase())||/[\r\n\0]/.test(d))&&M(400,"invalid_authentication","Use a valid authentication header."),Object.keys(o).some(m=>m.toLowerCase()===l.toLowerCase())&&M(400,"invalid_authentication","Let the selected connection supply its authentication header."),o[l]=d,s.push(d)},u=r.authentication;if(u.kind==="bearer")c("Authorization","Bearer "+a(u.token));else if(u.kind==="basic"){let l=a(u.username),d=a(u.password);l.includes(":")&&M(400,"invalid_authentication","A Basic authentication username cannot contain a colon.");let m=new TextEncoder().encode(l+":"+d),f=btoa(Array.from(m,g=>String.fromCharCode(g)).join(""));c("Authorization","Basic "+f),s.push(f)}else if(u.kind==="header"||u.kind==="query"){let l=typeof u.name=="string"?u.name:a(u.name.output,!1),d=a(u.value);u.kind==="header"?c(l,d):((!l||/[\r\n\0]/.test(l)||n.searchParams.has(l))&&M(400,"invalid_authentication","Let the selected connection supply its authentication query parameter."),n.searchParams.set(l,d))}return s.push(n.href),{url:n.href,headers:o,sensitive:s}}var sn=class extends Error{constructor(r,i){super(i);this.code=r}code},KO=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},VO=(e,...t)=>!!e&&typeof e=="object"&&("code"in e&&t.includes(String(e.code))||"status"in e&&t.includes(Number(e.status))),lw=class{constructor(t,r,i,n,o){this.api=t;this.origin=r;this.binding=i;this.keys=n;this.trust=o}api;origin;binding;keys;trust;verifiedKeys;async trusted(t){if(!await this.verifies(t))throw new sn("identity_untrusted","Verify and trust the encryption and signing keys for identity "+t.principalId+" before sharing.");return t}async verifies(t){if(t.principalId===this.binding.principalId)return C(this.binding)===C(t);let r=(await this.keyring()).get(t.principalId)?.binding??await this.trust.binding(t.principalId);return!!r&&C(r)===C(t)}async verifiedIdentity(t){return this.verifies((await this.inspectIdentity(t)).binding)}keyring(){return this.verifiedKeys??=this.loadKeyring().catch(t=>{throw this.verifiedKeys=void 0,t})}async loadKeyring(){let t;try{t=(await this.readKeyring()).keyring?.keys??[]}catch(o){if(VO(o,401,403))return new Map;throw o}let r=new Set(t.map(o=>o.binding.principalId)),i=new Date().toISOString(),n=(await this.trust.bindings()).filter(o=>o.principalId!==this.binding.principalId&&!r.has(o.principalId));if(n.length)try{t=(await this.changeKeyring(o=>[...o,...n.filter(s=>!o.some(a=>a.binding.principalId===s.principalId)).map(s=>({binding:s,verifiedAt:i}))])).keys}catch(o){if(o instanceof sn)throw o}return new Map(t.map(o=>[o.binding.principalId,o]))}async readKeyring(){let t="/api/principals/"+this.binding.principalId+"/keyring",{keyring:r}=await this.api.json(t,{},GO),i=await this.trust.keyring(),n=()=>new sn("keyring_conflict","The list of verified public keys does not match what this device saw before.");if(!r){if(i)throw n();return{version:null,revision:0,keyring:null}}let o=YV(r.signature);if(o.signerId!==this.binding.id)return{version:r.version,revision:o.revision,keyring:null};let s=await QV(r.signature,this.binding).catch(()=>{throw n()}),a=await te(s);if(s.ownerId!==this.binding.principalId||s.origin!==this.origin||i&&(s.revision<i.revision||s.revision===i.revision&&a!==i.digest))throw n();return(!i||s.revision>i.revision)&&await this.trust.rememberKeyring({revision:s.revision,digest:a}),{version:r.version,revision:s.revision,keyring:s}}async changeKeyring(t){for(let r=1;;r++){let i=await this.readKeyring(),n={origin:this.origin,ownerId:this.binding.principalId,signerId:this.binding.id,revision:i.revision+1,keys:t(i.keyring?.keys??[])};try{await this.api.json("/api/principals/"+this.binding.principalId+"/keyring",{method:"PUT",body:{version:i.version,signature:await XV(n,this.keys.signing)}},GO)}catch(o){if(r<3&&VO(o,"changed"))continue;throw o}return await this.trust.rememberKeyring({revision:n.revision,digest:await te(n)}),n}}async inspectIdentity(t){let r=await this.api.json("/api/identities/"+P.parse(t)+"/binding",{},gl);return await LS(r),{...r,fingerprint:await US(r.binding)}}async trustIdentity(t,r){let i=await this.inspectIdentity(t);if(i.fingerprint!==r)throw new sn("fingerprint_mismatch","The identity fingerprint does not match.");if(t===this.binding.principalId||C((await this.keyring()).get(t)?.binding??null)===C(i.binding))return i;let n=new Date().toISOString();try{let o=await this.changeKeyring(s=>[...s.filter(a=>a.binding.principalId!==t),{binding:i.binding,verifiedAt:n}]);this.verifiedKeys=Promise.resolve(new Map(o.keys.map(s=>[s.binding.principalId,s])))}catch(o){if(!VO(o,401,403))throw o;await this.trust.rememberBinding(i.binding)}return i}async environment(t,r=!0){let{registration:i,stoppedAt:n}=await this.api.json("/api/environments/"+P.parse(t)+"/registration",{},JV);if(await wl(i),i.manifest.origin!==this.origin||i.manifest.id!==t||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(i.manifest.executor),i}async recipients(t){let{items:r}=await this.api.json("/api/principals/"+P.parse(t)+"/bound-recipients",{},hl(zO));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...s}of r)await LS(s),await this.trusted(s.binding);let i=await this.api.json("/api/principals/"+P.parse(t)+"/bound-agents",{},hl(zO)),n=[];for(let{name:o,...s}of i.items){await LS(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof sn&&a.code==="identity_untrusted"))throw a}}return[...r.map(o=>o.binding),...n]}async read(t){let r=await this.api.json("/api/custody/"+P.parse(t),{},jO);return await this.observe(r.content,t),r}async observe(t,r=t.policy.id){let i=await on(t);if(i.policy.id!==r||i.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=oO(i);await this.trusted(n);let o=await this.trust.checkpoint(i);if(o&&qo.parse(o.policy),o){if(i.policy.revision<o.policy.revision||i.materialRevision<o.materialRevision||i.policy.revision===o.policy.revision&&C(i.policy)!==C(o.policy)||i.materialRevision===o.materialRevision&&await te(i)!==o.digest)throw new sn("content_conflict","The encrypted content is older than this device has already observed.");if(i.policy.revision>o.policy.revision&&!MS(o.policy,i))throw new sn("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(i),i}async reveal(t){return Rf((await this.read(t)).content,this.binding,this.keys.encryption)}async sharing(t){let r=typeof t=="string"?(await this.api.json(t,{},hl(WV))).items:t,i={};for(let n of r){let o=await this.read(n.id);if(o.version!==n.version||C(o.content)!==C(n.content))throw new sn("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);i[n.id]={version:n.version,content:await Ef(await Rf(o.content,this.binding,this.keys.encryption),n.policy,o.content.materialRevision+1,this.binding,this.keys,o.content.metadata,o.content)}}return i}async policy(t,r,i=[],n={}){let o=n.previous?.readers??[...new Map([...await this.recipients(t),this.binding].map(c=>[c.id,c])).values()];if(!o.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Go(c)):[];for(let c of i)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...rO(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return qo.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:t,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??o,readers:o,grants:a,producers:[]})}async save(t,r,i,n={}){let o=n.previous;o&&C(i)===C({...o.content.policy,revision:i.revision})&&(i={...i,revision:o.content.policy.revision});let s=await Ef(r,i,(o?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,o?.content),a={name:t,content:s,...n.labels?{labels:n.labels}:{},...o?{version:o.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:a},ml);return await this.trust.rememberContent(s),c}async pass(t,r,i,n){let o=await Ef(r,i,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:{name:t,content:o,version:n.version}},p.union([ml,Oq]));return"kind"in s&&await this.trust.rememberContent(o),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},hl(HV))).items}async reprotect(t,r="grantExpired",i=[]){let n=await this.read(t),{policy:o}=n.content,s=Date.now(),a=new Set(i),c=r==="recipients"?await this.recipients(o.ownerId):[],u=_=>!a.has(_.principalId)&&!c.some(x=>x.principalId===_.principalId&&x.id!==_.id),l=o.grants.filter(_=>Go(_,s)&&u(_.executor)&&(!("actor"in _)||u(_.actor))),d=o.readers.filter(u),m=o.authorities.filter(u),f=c.filter(_=>!d.some(x=>x.id===_.id)),g={...o,revision:o.revision+1,grants:l,producers:[],readers:[...d,...f],authorities:[...m,...f.filter(_=>!m.some(x=>x.id===_.id))],...o.observers?{observers:o.observers.filter(_=>!a.has(_))}:{}},v=o.contentType!==ge.executionResult&&o.producers.some(_=>Date.parse(_.expiresAt)>s);if(C({...g,revision:o.revision})===C(o)||v)return null;let S=await Rf(n.content,this.binding,this.keys.encryption);if(o.contentType===ge.executionResult){let _=await Ef(S,g,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content);return await this.api.json("/api/custody/"+t,{method:"PUT",body:{name:"Execution result",content:_,version:n.version}},jO),await this.trust.rememberContent(_),t}let b=await this.api.json("/api/resources/"+o.id,{},ml);return this.save(b.name,S,g,{metadata:n.content.metadata,previous:n})}async reprotectPending(){let t=[],r=[];for(let i of await this.pendingProtection())try{await this.reprotect(i.id,i.reason,i.remove)&&t.push(i.id)}catch(n){r.push({id:i.id,code:n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:"failure"})}return{done:t,failed:r}}async sourceContents(t){let r=new Map;for(let i of new Set(t))r.set(i,(await this.read(i)).content);for(let i of[...r.values()])i.policy.contentType===ge.tokenSet&&typeof i.metadata.appId=="string"&&!r.has(i.metadata.appId)&&r.set(i.metadata.appId,(await this.read(i.metadata.appId)).content);return[...r.values()]}async output(t,r,i,n,o){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+t+"/resources?"+l,{},hl(ml));s=d.items.find(m=>m.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(t,ge.value);return u.producers=[{executor:n.manifest.executor,runId:i,expiresAt:o,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await FS(u,this.binding,this.keys,c)}}async prepare(t,r,i,n={}){let o=Ic.parse(i),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=o,l=u.kind==="http"?u.request:null;if(l?.connectionId&&s.manifest.httpVersion!==zi)throw new sn("http_runtime_required","Update this execution environment to use HTTP connections.");if(o.kind==="http"){let S=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(S).map(async([_,x])=>[_,await this.output(t,x,a,s,c)])));o.save=b}let d=u.kind==="command"?u.inputs.map(S=>S.source.id):l?Uf(l).map(S=>S.id):[],m=await this.sourceContents([...d,...n.sourceIds??[]]);for(let S=0;S<m.length;S++){let b=m[S],_=b.policy.contentType===ge.clientCredential,x=_&&o.kind!=="revoke"?Q.refresh:Q[o.kind],T=_||!l?.url?void 0:new URL(l.url).origin;if(b.policy.grants.some(ee=>"actor"in ee&&C(ee.actor)===C(this.binding)&&C(ee.executor)===C(s.manifest.executor)&&ee.operations.includes(x)&&vl(ee)>=Date.parse(c)&&(!T||!ee.origins.length||ee.origins.includes(T))&&(_||ee.callerProgram))||!b.policy.authorities.some(ee=>C(ee)===C(this.binding)))continue;let N=await this.read(b.policy.id),K=await this.api.json("/api/resources/"+b.policy.id,{},ml),B={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===ge.tokenSet?[Q.refresh]:[]])],origins:T?[T]:[],functionDigests:[],callerProgram:!_,expiresAt:c},de=ee=>C({...ee,expiresAt:null}),pe=N.content.policy.grants.filter(ee=>de(ee)===de(B)),qe=qo.parse({...N.content.policy,revision:N.content.policy.revision+1,grants:[...N.content.policy.grants.filter(ee=>Go(ee)&&de(ee)!==de(B)),{...B,expiresAt:new Date(Math.max(Date.parse(c),...pe.map(ee=>vl(ee)))).toISOString()}]});await this.save(K.name,await Rf(N.content,this.binding,this.keys.encryption),qe,{previous:N,metadata:N.content.metadata}),m[S]=(await this.read(b.policy.id)).content}let f=await this.policy(t,ge.executionResult,[],{id:a});f.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let g={format:2,id:a,origin:this.origin,ownerId:t,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await te(s.manifest),operation:Q[o.kind],operationDigest:await te(o),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(m.map(async S=>({id:S.policy.id,materialRevision:S.materialRevision,policyDigest:await te(S.policy),...S.policy.contentType===ge.tokenSet&&typeof S.metadata.authorizationDigest=="string"?{authorizationDigest:S.metadata.authorizationDigest}:{}}))),resultRecipients:f.readers,...s.manifest.resultVersion?{resultApproval:await FS(f,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await bl(s,g);let v=S=>S.policy.contentType===ge.clientCredential;for(let S of m)await Os(S,v(S)&&g.operation!==Q.connect&&g.operation!==Q.revoke?{...g,operation:Q.refresh}:g,v(S)?{}:{destination:l?.url,destinationPending:!!(l?.connectionId&&!l.url)});return Gq(g,o,this.keys)}async submit(t,r,i,n={}){return this.submitPrepared(await this.prepare(t,r,i,n))}async submitPrepared(t){await this.trust.rememberRun(t);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:t},Rc)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new KO(t.intent.id)}}async resume(t){let r=await this.trust.run(P.parse(t));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let i=await this.api.json("/api/runtime/runs/"+t,{},Rc);if(C(i.intent)!==C(r.intent)||i.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return i}catch(i){if(!i||typeof i!="object"||!("code"in i)||i.code!=="not_found")throw i}return this.submitPrepared(r)}async result(t){if(t.intent.origin!==this.origin||t.intent.id!==t.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(t.intent.actor);let r=await bf(t.requestSignature,t.intent.actor.signing,"run");if(C(r.intent)!==C(t.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(t.intent.executor),!(t.receipt&&"content"in t.receipt?t.receipt.content.policy.readers:t.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new sn("not_recipient","This identity is not a reader of the execution result.");return t.receipt&&"content"in t.receipt&&await this.observe(t.receipt.content,t.id),t.receipt?Jq(t.receipt,t.intent,this.binding.id,this.keys):null}async shareLegacyResult(t){if(!t.receipt||"content"in t.receipt)return t;if(C(t.intent.actor)!==C(this.binding)||C(t.intent.executor)!==C(this.binding))throw new sn("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(t);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let i=await this.policy(t.ownerId,ge.executionResult,[],{id:t.id});i.producers=[{executor:this.binding,runId:t.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await lO(t.intent,t.receipt.state,r,this.keys,await FS(i,this.binding,this.keys),t.receipt);return this.api.json("/api/runtime/runs/"+t.id+"/result",{method:"PUT",body:{receipt:n}},Rc)}};import{lstat as Hxe,mkdir as n3,readFile as Wxe,readdir as i3,rm as Jxe}from"node:fs/promises";import{join as kl}from"node:path";var dw=p.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Tc=class{constructor(t,r,i,n){this.directory=t;this.origin=r;this.binding=i;this.privateKeys=n}directory;origin;binding;privateKeys;indexing;context(t){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:dw.parse(t)})}async read(t){let r=this.context(t),i=kl(this.directory,t+".json");try{let n=await Hxe(i);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let o=p.string().max(32e6).parse(JSON.parse(await Wxe(i,"utf8"))),s=await hS(o,await An(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(NS(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await nr({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async writeEntry(t,r){let i=this.context(t),n={context:i,value:r},o=await Tt(n,this.privateKeys.signing,"journal"),s=ft(C({...n,signature:o}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new ll(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:i}).encrypt(await An(this.binding.encryption,"ECDH-ES+A256KW"));await n3(this.directory,{recursive:!0,mode:448}),await gO(kl(this.directory,t+".json"),C(a),!0)}delivery(t){return/^(run|process|invocation|refresh)_/.test(t)}delivered(t){return!!t&&typeof t=="object"&&"delivered"in t&&t.delivered===!0}async markPending(t){await n3(kl(this.directory,"pending"),{recursive:!0,mode:448}),await gO(kl(this.directory,"pending",dw.parse(t)),"",!0)}index(){return this.indexing??=(async()=>{let t="checkpoint_pending_index";if(!await this.read(t)){for(let r of await this.keys("")){if(!this.delivery(r))continue;let i=await this.read(r);i&&!this.delivered(i)&&await this.markPending(r)}await this.writeEntry(t,{version:1})}})()}async write(t,r){await this.index();let i=this.delivered(r);this.delivery(t)&&!i&&await this.markPending(t),await this.writeEntry(t,r),this.delivery(t)&&i&&await Jxe(kl(this.directory,"pending",t),{force:!0})}async pending(t){await this.index();let r;try{r=await i3(kl(this.directory,"pending"),{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)).map(i=>dw.parse(i.name))}async keys(t){let r;try{r=await i3(this.directory,{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)&&i.name.endsWith(".json")).map(i=>dw.parse(i.name.slice(0,-5)))}};var pw=class{constructor(t){this.journal=t}journal;binding(t){return this.journal.read("identity_"+t)}async bindings(){return(await Promise.all((await this.journal.keys("identity_")).map(r=>this.journal.read(r)))).filter(r=>r!==null)}async rememberBinding(t){await Mi(t),await this.journal.write("identity_"+t.principalId,t)}keyring(){return this.journal.read("checkpoint_keyring")}async rememberKeyring(t){await this.journal.write("checkpoint_keyring",t)}checkpoint(t){return this.journal.read("checkpoint_"+t.policy.format+"_"+t.policy.id)}async rememberContent(t){await this.journal.write("checkpoint_"+t.policy.format+"_"+t.policy.id,{policy:t.policy,materialRevision:t.materialRevision,digest:await te(t)})}run(t){return this.journal.read("run_"+t)}async rememberRun(t){let r=await this.run(t.intent.id);if(r&&C(r)!==C(t))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+t.intent.id,t)}};var fw=class{api;constructor(t){this.api={async json(r,i={},n){try{return await t.json(r,i,n)}catch(o){throw o instanceof Error&&"status"in o&&typeof o.status=="number"&&"code"in o&&typeof o.code=="string"?new Me(o.status,o.code,o.message):o}}}}claim(t){return this.api.json("/api/environments/"+t+"/claim",{method:"POST",body:{}},ZV)}renew(t,r){return this.api.json("/api/runtime/runs/"+t+"/renew",{method:"POST",body:{lease:r}},p.object({active:p.boolean()}))}dispatch(t,r){return this.api.json("/api/runtime/runs/"+t+"/dispatch",{method:"POST",body:{lease:r}})}finish(t,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:t,receipt:r}},Rc)}capture(t,r,i){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:t,content:r,...i?{labels:i}:{}}},p.object({id:P}))}connections(){let t=this.api;return{prepare:(r,i,n)=>t.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:i,expectedRevision:n}},Nf),dispatch:(r,i)=>t.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:i}},Nf),commit:(r,i,n)=>t.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:i,content:n}},ir),uncertain:(r,i)=>t.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:i}}),abort:(r,i)=>t.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:i}},Nf),state:r=>t.json("/api/connections/"+r+"/operation",{},Nf.nullable())}}};import{randomUUID as wUe}from"node:crypto";var cs=lt(u4(),1);import{randomUUID as mNe}from"node:crypto";function Gte(e){let t=SS.safeParse({accountId:e.Account,arn:e.Arn,principalId:e.Arn?.includes(":assumed-role/")?e.UserId?.split(":")[0]:e.UserId});return(!t.success||t.data.arn.split(":")[4]!==t.data.accountId)&&M(502,"invalid_response","The AWS account could not be verified."),t.data}function qte(e,t){return e.accountId===t.accountId&&e.principalId===t.principalId&&dl(e.arn)===dl(t.arn)}function l4(e){e&&(!Number.isFinite(e.getTime())||e.getTime()<=Date.now())&&M(409,"reconnect_required","Reconnect with current AWS credentials.")}var OE=class{async obtain(t,r,i){let n=JD.parse({authentication:t.authentication,region:t.region,...t.role?{role:t.role}:{}}),o=n.authentication,s=o.kind==="environment"?void 0:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.kind==="session"?{sessionToken:o.sessionToken,expiration:new Date(o.expiresAt)}:{}};l4(s?.expiration);let a=new cs.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...i?[i]:[]]),l=!1;try{let d=s??await a.config.credentials();l4(d.expiration),c=new cs.STSClient({region:n.region,credentials:d});let m=r?.sourceIdentity?Gte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&m&&!qte(m,r.sourceIdentity)&&M(409,"account_changed","Reconnect to approve the current AWS authentication source.");let f=d,g=m;if(n.role){l=!0;let b=(await c.send(new cs.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+mNe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&M(502,"invalid_response","AWS did not return credentials."),f={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},l4(f.expiration),r?.identity&&(c.destroy(),c=new cs.STSClient({region:n.region,credentials:f}),g=Gte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&g&&!qte(g,r.identity)&&M(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:wS.parse({...n,sourceIdentity:m,identity:g}),credentials:{AWS_ACCESS_KEY_ID:f.accessKeyId,AWS_SECRET_ACCESS_KEY:f.secretAccessKey,AWS_SESSION_TOKEN:f.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof Me)throw d;i?.aborted&&M(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&M(409,"reconnect_required","Reconnect with current AWS credentials."),l&&M(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),M(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var NE=class{constructor(t){this.aws=t}aws;facts=SO;needsRenewal(){return!1}async outputs(t,r,i){return(await this.aws.obtain(t.aws,t.aws,i)).credentials}};var d4;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(d4="oauth4webapi/v3.8.8");function GE(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var Io="ERR_INVALID_ARG_VALUE",us="ERR_INVALID_ARG_TYPE";function Ft(e,t,r){let i=new TypeError(e,{cause:r});return Object.assign(i,{code:t}),i}var Bte=Symbol(),hNe=Symbol(),gNe=Symbol(),w4=Symbol();var UE=Symbol();var yNe=new TextEncoder,vNe=new TextDecoder;function p4(e){return typeof e=="string"?yNe.encode(e):vNe.decode(e)}var f4;Uint8Array.prototype.toBase64?f4=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):f4=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let i=0;i<t.byteLength;i+=32768)r.push(String.fromCharCode.apply(null,t.subarray(i,i+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var m4;Uint8Array.fromBase64?m4=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}}:m4=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}};function h4(e){return typeof e=="string"?m4(e):f4(e)}var tp=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=ZNe,Error.captureStackTrace?.(this,this.constructor)}},Fh=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function ve(e,t,r){return new Fh(e,{code:t,cause:r})}function LE(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Hte(e){GE(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(d4&&!t.has("user-agent")&&t.set("user-agent",d4),t.has("authorization"))throw Ft('"options.headers" must not include the "authorization" header name',Io);return t}function SNe(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw Ft('"options.signal" must return or be an instance of AbortSignal',us);return t}}function ME(e,t,r,i,n){try{if(typeof e!="number"||!Number.isFinite(e))throw Ft(`${r} must be a number`,us,n);if(e>0)return;if(t){if(e!==0)throw Ft(`${r} must be a non-negative number`,Io,n);return}throw Ft(`${r} must be a positive number`,Io,n)}catch(o){throw i?ve(o.message,i,n):o}}function $r(e,t,r,i){try{if(typeof e!="string")throw Ft(`${t} must be a string`,us,i);if(e.length===0)throw Ft(`${t} must not be empty`,Io,i)}catch(n){throw r?ve(n.message,r,i):n}}function Wte(e){bNe(e,"application/json")}function wNe(e,...t){let r='"response" content-type must be ';if(t.length>2){let i=t.pop();r+=`${t.join(", ")}, or ${i}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return ve(r,YNe,e)}function bNe(e,t){if(NNe(e)!==t)throw wNe(e,t)}async function Jte(e){return $r(e,"codeVerifier"),h4(await crypto.subtle.digest("SHA-256",p4(e)))}function Zte(e){let t=e?.[hNe];return typeof t=="number"&&Number.isFinite(t)?t:0}function Xte(e){let t=e?.[gNe];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Yte(){return Math.floor(Date.now()/1e3)}function np(e){if(typeof e!="object"||e===null)throw Ft('"as" must be an object',us);$r(e.issuer,'"as.issuer"')}function ip(e){if(typeof e!="object"||e===null)throw Ft('"client" must be an object',us);$r(e.client_id,'"client.client_id"')}function Vte(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Qte(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{i.set("client_id",r.client_id),i.set("client_secret",e)}}function ere(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{let o=Vte(r.client_id),s=Vte(e),a=btoa(`${o}:${s}`);n.set("authorization",`Basic ${a}`)}}function tre(){return(e,t,r,i)=>{r.set("client_id",t.client_id)}}var _Ne=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function xNe(e,t){if(t&&e.protocol!=="https:")throw ve("only requests to HTTPS are allowed",eUe,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw ve("only HTTP and HTTPS requests are allowed",tUe,e)}function Kte(e,t,r,i){let n;if(typeof e!="string"||!(n=_Ne(e)))throw ve(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?rUe:nUe,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return xNe(n,i),n}function rre(e,t,r,i){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Kte(e.mtls_endpoint_aliases[t],t,r,i):Kte(e[t],t,r,i)}var g4=class extends Error{cause;code;error;status;error_description;response;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=JNe,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)}},Gh=class extends Error{cause;code;error;error_description;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=XNe,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)}},y4=class extends Error{cause;code;response;status;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=WNe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},zE="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",ENe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",ANe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',RNe="("+zE+")\\s*=\\s*"+ANe,INe="("+zE+")\\s*=\\s*("+zE+")",$Ne=new RegExp("^[,\\s]*("+zE+")"),PNe=new RegExp("^[,\\s]*"+RNe+"[,\\s]*(.*)"),TNe=new RegExp("^[,\\s]*"+INe+"[,\\s]*(.*)"),CNe=new RegExp("^("+ENe+")(?:$|[,\\s])(.*)");function kNe(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);let t=e.headers.get("www-authenticate");if(t===null)return;let r=[],i=t;for(;i;){let n=i.match($Ne),o=n?.[1].toLowerCase();if(!o)return;let s=i.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;i=a?a[1]:void 0;let u={},l;if(c)for(;i;){let m,f;if(n=i.match(PNe)){[,m,f,i]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[m.toLowerCase()]=f;continue}if(n=i.match(TNe)){[,m,f,i]=n,u[m.toLowerCase()]=f;continue}if(n=i.match(CNe)){if(Object.keys(u).length)break;[,l,i]=n;break}return}else i=s||void 0;let d={scheme:o,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function DNe(e){if(e.status>399&&e.status<500){Sre(e),Wte(e);try{let t=await e.clone().json();if(LE(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function nre(e,t,r){if(e.status!==t){LNe(e);let i;throw(i=await DNe(e))?(await e.body?.cancel(),new g4("server responded with an error in the response body",{cause:i,response:e})):ve(`"response" is not a conform ${r} response (unexpected HTTP status code)`,QNe,e)}}function ONe(e){if(!_4.has(e))throw Ft('"options.DPoP" is not a valid DPoPHandle',Io)}function NNe(e){return e.headers.get("content-type")?.split(";")[0]}async function ire(e,t,r,i,n,o,s){return await r(e,t,n,o),o.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[w4]||fetch)(i.href,{body:n,headers:Object.fromEntries(o.entries()),method:"POST",redirect:"manual",signal:SNe(i,s?.signal)})}async function b4(e,t,r,i,n,o){let s=rre(e,"token_endpoint",t.use_mtls_endpoint_aliases,o?.[Bte]!==!0);n.set("grant_type",i);let a=Hte(o?.headers);a.set("accept","application/json"),o?.DPoP!==void 0&&(ONe(o.DPoP),await o.DPoP.addProof(s,a,"POST"));let c=await ire(e,t,r,s,n,a,o);return o?.DPoP?.cacheNonce(c,s),c}async function ore(e,t,r,i,n){np(e),ip(t),$r(i,'"refreshToken"');let o=new URLSearchParams(n?.additionalParameters);return o.set("refresh_token",i),b4(e,t,r,"refresh_token",o,n)}var sre=new WeakMap,UNe=new WeakMap;function are(e){if(!e.id_token)return;let t=sre.get(e);if(!t)throw Ft('"ref" was already garbage collected or did not resolve from the proper sources',Io);return t}async function qE(e,t,r,i,n,o){if(np(e),ip(t),!GE(r,Response))throw Ft('"response" must be an instance of Response',us);await nre(r,200,"Token Endpoint"),Sre(r);let s=await cUe(r);if($r(s.access_token,'"response" body "access_token" property',tt,{body:s}),$r(s.token_type,'"response" body "token_type" property',tt,{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;ME(a,!0,'"response" body "expires_in" property',tt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&$r(s.refresh_token,'"response" body "refresh_token" property',tt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw ve('"response" body "scope" property must be a string',tt,{body:s});if(s.id_token!==void 0){$r(s.id_token,'"response" body "id_token" property',tt,{body:s});let a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(ME(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),i?.length&&a.push(...i);let{claims:c,jwt:u}=await qNe(e,t,s.id_token,a,n);KNe(t,c),VNe(c),UNe.set(r,u),sre.set(s,c)}if(o?.[s.token_type]!==void 0)o[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new tp("unsupported `token_type` value",{cause:{body:s}});return s}function LNe(e){let t;if(t=kNe(e))throw new y4("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function cre(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}function MNe(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"});return t}function zNe(e,t){let r=e[uUe]?.(t)??e.issuer;if(t.claims.iss!==r)throw ve('unexpected JWT "iss" (issuer) claim value',rp,{expected:r,claims:t.claims,claim:"iss"});return t}var _4=new WeakSet;function jNe(e){return _4.add(e),e}var x4=Symbol();async function ure(e,t,r,i,n,o,s){if(np(e),ip(t),!_4.has(i))throw Ft('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Io);$r(n,'"redirectUri"');let a=du(i,"code");if(!a)throw ve('no authorization code in "callbackParameters"',tt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),o!==x4&&($r(o,'"codeVerifier"'),c.set("code_verifier",o)),b4(e,t,r,"authorization_code",c,s)}var lre={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 FNe(e,t){for(let r of e)if(t.claims[r]===void 0)throw ve(`JWT "${r}" (${lre[r]}) claim missing`,tt,{claims:t.claims});return t}function GNe(e,t){if(typeof t.claims[e]!="string")throw ve(`unexpected JWT "${e}" (${lre[e]}) claim type`,tt,{claims:t.claims});return t}function qNe(e,t,r,i,n){return iUe(r,oUe.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Zte(t),Xte(t),n).then(FNe.bind(void 0,["aud","exp","iat","iss","sub",...i])).then(zNe.bind(void 0,e)).then(MNe.bind(void 0,t.client_id)).then(GNe.bind(void 0,"sub"))}function dre(e,t){if(t===FE)return t;let r=t===void 0;return r&&(t=e.default_max_age),t===void 0?FE:(ME(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function VNe(e){e.auth_time!==void 0&&ME(e.auth_time,!0,'ID Token "auth_time" (authentication time)',tt,{claims:e})}function pre(e,t,r){if(r===FE)return;let i=Yte()+Zte(e),n=Xte(e);if(t.auth_time+r<i-n)throw ve("too much time has elapsed since the last End-User authentication",S4,{claims:t,now:i,tolerance:n,claim:"auth_time"})}function fre(e,t){let r=t===jE?void 0:t;if(e.nonce!==r)throw ve('unexpected ID Token "nonce" claim value',rp,{expected:r,claims:e,claim:"nonce"})}function KNe(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw ve('ID Token "aud" (audience) claim includes additional untrusted audiences',rp,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw ve('unexpected ID Token "azp" (authorized party) claim value',rp,{expected:e.client_id,claims:t,claim:"azp"})}}var jE=Symbol(),FE=Symbol();async function mre(e,t,r,i){return typeof i?.expectedNonce=="string"||typeof i?.maxAge=="number"||i?.requireIdToken?BNe(e,t,r,i.expectedNonce,i.maxAge,i[UE],i.recognizedTokenTypes):HNe(e,t,r,i?.maxAge,i?.[UE],i?.recognizedTokenTypes)}async function BNe(e,t,r,i,n,o,s){let a=[];switch(i){case void 0:i=jE;break;case jE:break;default:$r(i,'"expectedNonce" argument'),a.push("nonce")}n=dre(t,n),n!==FE&&a.push("auth_time");let c=await qE(e,t,r,a,o,s);$r(c.id_token,'"response" body "id_token" property',tt,{body:c});let u=are(c);return pre(t,u,n),fre(u,i),c}async function HNe(e,t,r,i,n,o){let s=await qE(e,t,r,void 0,n,o),a=are(s);return a&&(pre(t,a,dre(t,i)),fre(a,jE)),s}var WNe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",JNe="OAUTH_RESPONSE_BODY_ERROR",ZNe="OAUTH_UNSUPPORTED_OPERATION",XNe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var v4="OAUTH_PARSE_ERROR",tt="OAUTH_INVALID_RESPONSE";var YNe="OAUTH_RESPONSE_IS_NOT_JSON",QNe="OAUTH_RESPONSE_IS_NOT_CONFORM",eUe="OAUTH_HTTP_REQUEST_FORBIDDEN",tUe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",S4="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",rp="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var rUe="OAUTH_MISSING_SERVER_METADATA",nUe="OAUTH_INVALID_SERVER_METADATA";async function hre(e,t,r,i,n){return np(e),ip(t),b4(e,t,r,"client_credentials",new URLSearchParams(i),n)}async function gre(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}async function yre(e,t,r,i,n){np(e),ip(t),$r(i,'"token"');let o=rre(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,n?.[Bte]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",i);let a=Hte(n?.headers);return a.delete("accept"),ire(e,t,r,o,s,a,n)}async function vre(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);await nre(e,200,"Revocation Endpoint")}function Sre(e){if(e.bodyUsed)throw Ft('"response" body has been used already',Io)}async function iUe(e,t,r,i,n){let{0:o,1:s,length:a}=e.split(".");if(a===5)if(n!==void 0)e=await n(e),{0:o,1:s,length:a}=e.split(".");else throw new tp("JWE decryption is not configured",{cause:e});if(a!==3)throw ve("Invalid JWT",tt,e);let c;try{c=JSON.parse(p4(h4(o)))}catch(d){throw ve("failed to parse JWT Header body as base64url encoded JSON",v4,d)}if(!LE(c))throw ve("JWT Header must be a top level object",tt,e);if(t(c),c.crit!==void 0)throw new tp('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(p4(h4(s)))}catch(d){throw ve("failed to parse JWT Payload body as base64url encoded JSON",v4,d)}if(!LE(u))throw ve("JWT Payload must be a top level object",tt,e);let l=Yte()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw ve('unexpected JWT "exp" (expiration time) claim type',tt,{claims:u});if(u.exp<=l-i)throw ve('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',S4,{claims:u,now:l,tolerance:i,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw ve('unexpected JWT "iat" (issued at) claim type',tt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw ve('unexpected JWT "iss" (issuer) claim type',tt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw ve('unexpected JWT "nbf" (not before) claim type',tt,{claims:u});if(u.nbf>l+i)throw ve('unexpected JWT "nbf" (not before) claim value',S4,{claims:u,now:l,tolerance:i,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw ve('unexpected JWT "aud" (audience) claim type',tt,{claims:u});return{header:c,claims:u,jwt:e}}function oUe(e,t,r,i){if(e!==void 0){if(typeof e=="string"?i.alg!==e:!e.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?i.alg!==r:typeof r=="function"?!r(i.alg):!r.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:r,reason:"default value"});return}throw ve('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function du(e,t){let{0:r,length:i}=e.getAll(t);if(i>1)throw ve(`"${t}" parameter must be provided only once`,tt);return r}var sUe=Symbol(),aUe=Symbol();function wre(e,t,r,i){if(np(e),ip(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Ft('"parameters" must be an instance of URLSearchParams, or URL',us);if(du(r,"response"))throw ve('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',tt,{parameters:r});let n=du(r,"iss"),o=du(r,"state");if(!n&&e.authorization_response_iss_parameter_supported)throw ve('response parameter "iss" (issuer) missing',tt,{parameters:r});if(n&&n!==e.issuer)throw ve('unexpected "iss" (issuer) response parameter value',tt,{expected:e.issuer,parameters:r});switch(i){case void 0:case aUe:if(o!==void 0)throw ve('unexpected "state" response parameter encountered',tt,{expected:void 0,parameters:r});break;case sUe:break;default:if($r(i,'"expectedState" argument'),o!==i)throw ve(o===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',tt,{expected:i,parameters:r})}if(du(r,"error"))throw new Gh("authorization response from the server is an error",{cause:r});let a=du(r,"id_token"),c=du(r,"token");if(a!==void 0||c!==void 0)throw new tp("implicit and hybrid flows are not supported");return jNe(new URLSearchParams(r))}async function cUe(e,t=Wte){let r;try{r=await e.json()}catch(i){throw t(e),ve('failed to parse "response" body as JSON',v4,i)}if(!LE(r))throw ve('"response" body must be a top level object',tt,{body:r});return r}var uUe=Symbol();function qh(e){if(e==="")return[];if(!e.startsWith("/")||/~(?![01])/u.test(e))throw new Error("Invalid JSON pointer.");let t=e.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(t.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return t}function Wn(e,t){for(let r of qh(t)){if(e===null||typeof e!="object"||!Object.hasOwn(e,r))return;e=e[r]}return e}function E4(e,t,r){let i=qh(t),n=i.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let o of i){if(e===null||typeof e!="object"||!Object.hasOwn(e,o))throw new Error("JSON pointer target does not exist.");e=e[o]}if(e===null||typeof e!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(e)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=e.length))throw new Error("Invalid array index.");e[n]=r}function La(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);throw new Error("The selected value is not text.")}function VE(e,t){return typeof t=="string"?La(Wn(e,t)):t.map(r=>typeof r=="string"?r:La(Wn(e,r.pointer))).join("")}function op(e,t){let r=new Set;for(let i of t)i&&(r.add(i),r.add(encodeURIComponent(i)),r.add(JSON.stringify(i).slice(1,-1)));for(let i of[...r].sort((n,o)=>o.length-n.length))e=e.split(i).join("[redacted]");return e}function A4(e,t){return btoa(Array.from(new TextEncoder().encode(e+":"+t),r=>String.fromCharCode(r)).join(""))}var bre=Object.assign(Object.create(null),{dpop:()=>M(502,"invalid_response","The service returned an unsupported token.")}),dUe={redirectUri:e=>e.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),bre,{"user access token":()=>{}})},pUe={authorize(e,t){delete e.response_type,delete e.client_id,delete e.redirect_uri,e.callback_url=t,e.key_label="Foundation"},async exchange({spec:e,transport:t,url:r,authorization:i,verifier:n}){let o=i.parameters;return(o.getAll("state").length!==1||o.get("state")!==i.state||o.getAll("code").length!==1||!o.get("code"))&&M(400,"invalid_state","Start the connection again."),t.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:o.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},fUe={revokeRequest({app:e,url:t,current:r}){return{url:t,method:"DELETE",headers:{authorization:"Basic "+A4(e.clientId,e.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},mUe={tokenParameters(e){let t=e.get("redirect_uri");t!==null&&(e.set("redirect_url",t),e.delete("redirect_uri"))}};function $o(e,t){let r=t?new URL(t):void 0;return{recognizedTokenTypes:bre,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(i){i.token_type===void 0&&(i.token_type="bearer")},...e.grantType==="client_credentials"?{clientCredentialsParameters(){return{...e.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(i){i.refresh_token===null&&delete i.refresh_token}}:{},...e.adapter==="ebay"?dUe:e.adapter==="openrouter"?pUe:e.adapter==="vultr"?mUe:{},...e.revoke?.style==="github"?fUe:{}}}function pu(e,t){try{return Pn(new sw(e).expand(t)).href}catch{M(400,"invalid_service_url","Check the service URL and its required fields.")}}var _re=(e,t=" ")=>typeof e=="string"?[...new Set(e.split(t).filter(Boolean))].sort():[],KE=e=>{let t=typeof e=="number"||typeof e=="string"?Number(e):NaN;return(!Number.isSafeInteger(t)||t<=0||t>315576e3)&&M(502,"invalid_response","The service returned an invalid expiry."),t};var BE=class{constructor(t){this.transport=t}transport;appValues(t,r){try{return{...qs(t.fields,r.fields,t.defaults),clientId:r.clientId}}catch(i){throw i instanceof Gs&&M(400,i.code,i.message),i}}async authorize(t,r,i,n,o,s){(t.grantType==="client_credentials"||!t.authorizeUrl)&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(pu(t.authorizeUrl,this.appValues(t,r))),c={...t.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:$o(t).redirectUri?.(r,o)??o,state:i};s.length&&(c.scope=s.join(t.scopes.separator)),t.pkce&&(c.code_challenge=await Jte(n),c.code_challenge_method="S256"),$o(t).authorize?.(c,o);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(t,r){let i={issuer:t.issuer??new URL(pu(t.grantType==="client_credentials"?t.tokenUrl:t.authorizeUrl,this.appValues(t,r))).origin,token_endpoint:pu(t.tokenUrl,this.appValues(t,r))};return t.issuer&&Pn(t.issuer),{server:i,client:{client_id:r.clientId}}}authentication(t,r){return r==="none"?tre():(t.clientSecret||M(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?ere(t.clientSecret):Qte(t.clientSecret))}options(t){let r=t?.tokenFormat??"form";return{[w4]:async(i,{body:n,headers:o,method:s,signal:a})=>{let c=new URLSearchParams(n);t&&$o(t).tokenParameters?.(c);let u=await this.transport.send({url:i,method:s,headers:r==="json"?{...o,"content-type":"application/json"}:o,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(t){return Cl({status:t.status,headers:{},body:new Uint8Array(await t.arrayBuffer())})}checkResponse(t,r,i,n=!1){return(r>=400||i.error||t.okPointer&&Wn(i,t.okPointer)!==!0)&&(n&&(i.error==="invalid_grant"||i.error==="invalid_token")&&M(409,"reconnect_required","Reconnect this service to renew access."),r===429&&M(503,"service_rate_limit","The service is busy. Try again later."),M(502,"authorization_failed","The service did not authorize this connection.")),i}async tokenResponse(t,r,i,n=!1){i.status===429&&M(503,"service_rate_limit","The service is busy. Try again later.");let o=this.checkResponse(t,i.status,await this.json(i),n),{server:s,client:a}=this.configuration(t,r),c=new URL(s.token_endpoint),u={...o};delete u.id_token,$o(t,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=KE(u.expires_in));try{let d=await(n?cre:t.grantType==="client_credentials"?gre:mre)(s,a,Response.json(u,{status:i.status}),{recognizedTokenTypes:$o(t,c.href).recognizedTokenTypes});return{...o,...d}}catch(l){if(l instanceof Me)throw l;M(502,"invalid_response","The service did not return a valid access token.")}}token(t,r,i,n,o=!1){let s=r[$o(t).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&M(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+KE(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&M(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of t.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?_re(r.scope,t.scopes.separator):o?n?.scopes??i:i,scopesStatus:r.scope!==void 0?"reported":o?n?.scopesStatus??"unknown":i.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()+KE(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(t,r,i,n,o,s,a,c){t.grantType==="client_credentials"&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=$o(t);if(l.exchange){let m=await l.exchange({spec:t,app:r,transport:this.transport,url:()=>pu(t.tokenUrl,this.appValues(t,r)),authorization:i,verifier:n});u=this.checkResponse(t,m.status,Cl(m))}else{let{server:m,client:f}=this.configuration(t,r),g;try{let v=wre(m,f,i.parameters,i.state);g=await ure(m,f,this.authentication(r,t.clientAuth),v,l.redirectUri?.(r,o)??o,t.pkce?n:x4,{...this.options(t),additionalParameters:t.tokenParams})}catch(v){throw(v instanceof Fh||v instanceof Gh)&&M(400,"invalid_state","Start the connection again."),v}u=await this.tokenResponse(t,r,g)}let d=this.token(t,u,s,a);return await c?.(d,u),d}async clientCredentials(t,r,i,n,o){t.grantType!=="client_credentials"&&M(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(t,r),c=$o(t,s.token_endpoint),u={...t.tokenParams,...i.length?{scope:i.join(t.scopes.separator)}:{}},l=await hre(s,a,this.authentication(r,t.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(t)),d=await this.tokenResponse(t,r,l),m={...this.token(t,d,i,n,!!n),requestedScopes:i};return await o?.(m,d),m}async refresh(t,r,i,n){let o=i;if(i.expiresAt!==null&&i.expiresAt<Date.now()+6e4){if(t.grantType==="client_credentials")return i.requestedScopes||M(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(t,r,i.requestedScopes,i,n);(!i.refreshToken||i.refreshExpiresAt&&i.refreshExpiresAt<=Date.now())&&M(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(t,r),c=await ore(s,a,this.authentication(r,t.clientAuth),i.refreshToken,{...this.options(t),additionalParameters:t.tokenParams}),u=await this.tokenResponse(t,r,c,!0);o=this.token(t,u,i.scopes,i,!0),await n?.(o,u)}return o}async revoke(t,r,i){if(!t.revoke?.tokenOnly)throw new Error("Revoke only with an endpoint that invalidates this token alone.");let n=pu(t.revoke.url,{...this.appValues(t,r),accessToken:i.accessToken,refreshToken:i.refreshToken??""});if(t.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(t,r),l=t.revoke.auth==="none"&&t.clientAuth!=="none"?()=>{}:this.authentication(r,t.revoke.auth??t.clientAuth),d=await yre({...c,revocation_endpoint:n},u,l,i.refreshToken??i.accessToken,this.options());try{await vre(d)}catch{M(502,"revoke_failed","The service did not revoke the token.")}return}let o={},s=t.revoke.auth??t.clientAuth;t.revoke.style==="bearer"?o.authorization="Bearer "+i.accessToken:s==="basic"&&(o.authorization="Basic "+A4(r.clientId,r.clientSecret??"")),(await this.transport.send($o(t).revokeRequest?.({spec:t,app:r,transport:this.transport,url:n,current:i})??{url:n,method:t.revoke.style==="bearer"?"POST":"DELETE",headers:o})).status>=300&&M(502,"revoke_failed","The service did not revoke the token.")}outputs(t,r,i){let n={...this.appValues(t,r),...i.extra,...i,expiresAt:i.expiresAt===null?"":String(i.expiresAt)};return Object.fromEntries(Object.entries(t.outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};function R4(e){if(e.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return e.method.config}function I4(e){return e||M(409,"app_required","Choose an OAuth application."),e}function hUe(e){return{token:LO.parse(e.token),response:Mt.parse(e.response)}}var HE=class{constructor(t){this.transport=t}transport;facts=yO;oauth(t){return new BE({send:r=>this.transport.send({...r,...t?{signal:AbortSignal.any([t,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(t){return!t.oauth||t.oauth.expiresAt!==null&&t.oauth.expiresAt<Date.now()+6e4}async renew(t){let r=t.material,i=R4(r),n=I4(t.app),o=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>t.receive({token:c,response:u}),a=i.grantType==="client_credentials"?await this.oauth(t.signal).clientCredentials(i,n,o??tV(i.scopes),r.oauth,s):await this.oauth(t.signal).refresh(i,n,r.oauth,s);return Pl.parse({...t.material,oauth:a})}async recover(t,r,i){let o=hUe(i).token;return Pl.parse({...t,oauth:o})}async outputs(t,r){return this.oauth().outputs(R4(t),I4(r),t.oauth)}async revoke(t,r,i){t.oauth&&await this.oauth(i).revoke(R4(t),I4(r),t.oauth)}};function gUe(e){if(e.method.kind!=="token"&&e.method.kind!=="approval")throw new Error("Use an input credential provider.");return e.method.config}var Vh=class{facts=El;needsRenewal(){return!1}async outputs(t){let r=gUe(t),i=qs(r.fields,t.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,o])=>[n,VE(i,o)]))}};function WE(e){if(e.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return e.method.config}var JE=class{facts=vO;values(t,r){let i=WE(t),n=i.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&M(409,"app_required","Choose an OVHcloud API application with its key and secret.");let o=n?r.fields:t.fields;return qs(i.fields,o)}credentials(t,r){if(WE(t).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:t.fields.consumerKey};let i=this.values(t,r);return{applicationKey:i.applicationKey,applicationSecret:i.applicationSecret,consumerKey:i.consumerKey}}needsRenewal(){return!1}async outputs(t,r){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let i="ovh"in t?t.ovh:void 0;i&&i.expiresAt!==null&&i.expiresAt<=Date.now()&&M(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=WE(t).authorization==="consumer_key"?{...this.values(t,r),...this.credentials(t,r)}:this.values(t,r);return Object.fromEntries(Object.entries(WE(t).outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};import{readFile as yUe}from"node:fs/promises";var vUe=p.object({accessToken:p.string().min(1).max(16384).regex(/^\S+$/),expiresAt:p.number().int().positive()}).strict();async function SUe(e,t){if(e==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,o=n?await yUe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!o||o.length>16384)&&M(409,"authentication_required","Provide the current OIDC token to this executor."),o.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([t,AbortSignal.timeout(3e3)])});r.ok||M(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let i=(await r.text()).trim();return(!i||i.length>16384)&&M(502,"invalid_response","The instance did not return a valid identity token."),i}function xre(e){if(e.method.kind!=="token"||e.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return e.method.config}var ZE=class{constructor(t,r=SUe){this.transport=t;this.identityToken=r}transport;identityToken;facts=El;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(t,r){let i=qs(xre(t).fields,t.fields),n=i.authentication;["api_key","oidc","instance"].includes(n)||M(400,"invalid_field","Choose a Vultr authentication source.");let o=n==="api_key"?i.token:i.credential||await this.identityToken(n,r);(!o||o.length>16384||/\s/.test(o))&&M(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(i.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&M(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+o},signal:r,body:JSON.stringify({role_id:i.roleId,session_name:i.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:i.userId}:{},...n==="oidc"?{oidc_issuer_id:i.issuerId}:{}})});a.status>=400&&M(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=Cl(a);(c.role_id!==void 0&&c.role_id!==i.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==i.userId)&&M(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=vUe.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&M(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(t,r,i){let n=xre(t);i.throwIfAborted();let o=await te(t),s=this.sessions.get(o);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(o);a||(a=this.obtain(t,i),this.pending.set(o,a));try{s=await a,this.sessions.set(o,s)}finally{this.pending.get(o)===a&&this.pending.delete(o)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,VE(s,c)]))}};function Ere(e,t){let r={oauth:new HE(e),token:new Vh,aws:new NE(t),approval:new Vh,ovh:new JE},i=new ZE(e);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?i:r[n.kind]}function Ci(e){return new TextDecoder("utf-8",{fatal:!0}).decode(e)}async function $4(e,t){let r={},i={},n=[],o=new Set;for(let s of e){if(o.has(s.name)||!_q(s.name))throw new Error("Use distinct, unreserved environment variable names.");o.add(s.name);let a=await t(s.source);if(s.format==="json"&&(a=ft(La(Wn(JSON.parse(Ci(a)),s.pointer??"")))),s.format==="file")i[s.name]=Buffer.from(a).toString("base64");else{let c=Ci(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:i,sensitive:n}}var sp=class{constructor(t,r,i,n,o,s=new OE){this.binding=t;this.keys=r;this.broker=i;this.journal=n;this.providers=Ere(o,s)}binding;keys;broker;journal;active=new Set;providers;provider(t){return this.providers(t)}metadata(t){return KV(t,this.provider(t.method).facts(t))}source(t,r,i){let n=i.find(o=>o.policy.id===t&&o.policy.contentType===r);return n||M(409,"input_required","Include the connection and its application in this execution."),n}async material(t,r,i){let n=typeof i=="function"?a=>i(Pl.parse(JSON.parse(Ci(a)))):i,o=Pl.safeParse(JSON.parse(Ci(await Ec(t,r,this.keys,{destination:n}))));o.success||M(409,"reconnect_required","Reconnect this service with the current connection format.");let s=o.data;return(await this.metadata(s)).authorizationDigest!==t.metadata.authorizationDigest&&M(409,"connection_changed","Approve the current service account and permissions before using this connection."),s.state==="reconnect"&&r.operation!==Q.revoke&&M(409,"reconnect_required","Reconnect this service before using it."),s}async app(t,r,i,n){let o=this.source(t,ge.clientCredential,n),s=aw.parse(JSON.parse(Ci(await Ec(o,i,this.keys))));return s.methodId!==r&&M(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(t,r,i){if(Ls(t.method).application==="none")return null;if(!xl(t.method))return"implicitApp"in t&&t.implicitApp?t.implicitApp:aw.parse({format:1,methodId:t.methodId,generation:t.generation,clientId:"",fields:{}});let n=r.operation===Q.revoke?Q.revoke:Q.refresh,o=await this.app(t.appId,t.methodId,{...r,operation:n},i);return o.generation!==t.appGeneration&&M(409,"app_changed","Reconnect this service with the current application."),Ls(t.method).requiresApp&&t.method.kind!=="aws"&&Object.entries($l(t.method.config.fields,t.fields??{})).some(([s,a])=>o.fields[s]!==a)&&M(409,"app_changed","Reconnect this service with the current application settings."),o}async validate(t,r,i){let n=MO.parse(t);r.operation!==Q[n.action]&&M(400,"wrong_operation","Use the approved connection operation.");let o=await this.material(this.source(n.id,ge.tokenSet,i),r);(n.action==="refresh"||Ls(o.method).revocable)&&await this.connectionApp(o,r,i)}async execute(t,r,i,n){let o=MO.parse(t);this.active.has(o.id)&&M(409,"connection_busy","Another operation is updating this connection."),this.active.add(o.id);try{n.throwIfAborted();let s=this.source(o.id,ge.tokenSet,i),a=await this.material(s,r);if(o.action==="refresh"){let l=await this.refresh(s,a,r,i,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(l)}}let c=this.provider(a.method),u=Ls(a.method).revocable&&!!c.revoke;return u&&await c.revoke(a,await this.connectionApp(a,r,i),n),{kind:"disconnected",id:s.policy.id,revoked:u}}finally{this.active.delete(o.id)}}async outputs(t,r,i,n,o){let s=await this.material(t,r,o);return this.provider(s.method).renew&&await this.broker.state(t.policy.id)&&M(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(t,s,r,i,n,o),this.provider(s.method).outputs(s,await this.connectionApp(s,r,i),n)}async httpDestination(t,r,i){let n=await this.material(t,r,o=>qO(o,i,r.origin));return qO(n,i,r.origin)}async http(t,r,i,n,o){let s=await this.httpDestination(t,r,o),a=await this.material(t,r,s),c=await this.outputs(t,r,i,n,s);return r3(s,o.headers,a.method.http,c)}async refreshed(t,r){let i=await this.metadata(r);return i.authorizationDigest!==t.previous.metadata.authorizationDigest&&M(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),t.material=r,t.content=await Fq(t.previous,ft(C(r)),this.binding,this.keys,i),t.phase="settled",await this.journal.write("refresh_"+t.operation.id,t),await this.broker.commit(t.operation.id,t.operation.fence,t.content),t.delivered=!0,await this.journal.write("refresh_"+t.operation.id,t),r}async refresh(t,r,i,n,o,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||M(409,"reconnect_required","Reconnect this service to renew access.");try{await Os(t,{...i,operation:Q.refresh},{destination:s})}catch{M(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,i,n),u=wUe(),l=await this.broker.prepare(u,t.policy.id,t.materialRevision),d={operation:l,previous:t,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{o.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),o.throwIfAborted();let m=await a.renew({material:r,app:c,signal:o,receive:async f=>{d.checkpoint=f,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,m)}catch(m){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),m instanceof Me&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(m.code))throw m;M(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let t=[];for(let r of await this.journal.pending("refresh_"))try{let i=await this.journal.read(r);if(i.delivered)continue;if(i.content){await this.broker.commit(i.operation.id,i.operation.fence,i.content),i.delivered=!0,await this.journal.write(r,i);continue}let n=await this.broker.state(i.operation.resource_id);if(!n||n.id!==i.operation.id||n.state==="prepared")n?.id===i.operation.id&&n.state==="prepared"&&await this.broker.abort(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i);else if(i.checkpoint&&this.provider(i.material.method).recover){let o=await this.provider(i.material.method).recover(i.material,i.app,i.checkpoint);await this.refreshed(i,o)}else await this.broker.uncertain(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i)}catch{t.push(r.slice(8))}return t}};import{lookup as bUe}from"node:dns/promises";import{request as _Ue}from"node:https";import{brotliDecompressSync as xUe,gunzipSync as EUe,inflateSync as AUe}from"node:zlib";var XE=class{constructor(t){this.origin=t}origin;async send(t){let r=Pn(t.url,this.origin),i=r.hostname.replace(/^\[|\]$/g,""),n=t.maxBytes??1048576;t.body&&Buffer.byteLength(t.body)>n&&M(413,"body_limit","The request body is too large.");let o={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(t.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&M(400,"invalid_header","Choose a valid request header."),o[c]=a}try{let s=await bUe(i,{all:!0,verbatim:!0});(!s.length||s.some(u=>!uw(u.address)))&&M(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]]);return await new Promise((u,l)=>{let d={method:t.method??"GET",headers:o,signal:c,agent:!1,lookup:(f,g,v)=>{g.all?v(null,[a]):v(null,a.address,a.family)}},m=_Ue(r,d,f=>{let g=[],v=0;f.on("data",S=>{v+=S.length,v>n?f.destroy(new Me(413,"body_limit","The response body is too large.")):g.push(S)}),f.on("error",l),f.on("end",()=>{try{let S=Buffer.concat(g),b=f.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?EUe:b==="deflate"?AUe:b==="br"?xUe:null;if(!x)throw new Me(502,"invalid_response","The service returned an unsupported response.");S=x(S,{maxOutputLength:n})}let _={};for(let[x,T]of Object.entries(f.headers))T!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(_[x]=Array.isArray(T)?T.join(", "):T);u({status:f.statusCode??502,headers:_,body:new Uint8Array(S)})}catch(S){l(S)}})});m.on("error",l),m.end(t.body)})}catch(s){if(s instanceof Me)throw s;t.signal?.aborted&&M(409,"cancelled","The operation was cancelled."),M(502,"service_unavailable","The service could not be reached. Try again.")}}};function Are(e){let{keys:t,binding:r,origin:i}=e.identity;if(!t||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=P4(RUe(hO()),"custody",r.id),o=new Tc(P4(n,"client"),i,r,t),s=new lw(e,i,r,t,new pw(o)),a=new fw(e),c=new XE(i),u=new sp(r,t,a.connections(),new Tc(P4(n,"connections"),i,r,t),c);return{custody:s,journal:o,directory:n,keys:t,binding:r,broker:a,transport:c,connections:u}}function IUe(e,t){let r={};if(Object.keys(t).some(i=>!e.parameters.some(n=>n.name===i)))throw new Error("Use the parameters this function declares.");for(let i of e.parameters){let n=Object.hasOwn(t,i.name)?t[i.name]:i.default;if(n===void 0){if(i.required)throw new Error("Complete the required function parameters.");continue}if(i.type!=="json"&&typeof n!==i.type||i.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(i.required&&i.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[i.name]=n}return r}function YE(e,t){let r=IUe(e,t);if(e.program.kind==="command"){let{kind:c,...u}=e.program;return{kind:c,...vc.parse({...u,stdin:JSON.stringify(r)})}}if(e.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");let i=e.program.request,n=c=>typeof c=="string"?c:JSON.stringify(c),o=(c,u=!1)=>{if(u&&typeof c=="string"){let l=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(c)?.[1];if(l){if(!e.parameters.some(d=>d.name===l))throw new Error("Declare every function parameter.");return Object.hasOwn(r,l)?r[l]:null}}return typeof c=="string"?c.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(l,d)=>{if(!e.parameters.some(m=>m.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?n(r[d]):""}):Array.isArray(c)?c.map(l=>o(l,u)):c&&typeof c=="object"?Object.fromEntries(Object.entries(c).map(([l,d])=>[l,o(d,u)])):c},s=i.url===void 0?void 0:new sw(i.url).expand(Object.fromEntries(Object.entries(r).map(([c,u])=>[c,n(u)]))),a=yc.parse({...o(i),...s===void 0?{}:{url:s},connectionId:i.connectionId,bindings:i.bindings,...i.json===void 0?{}:{json:o(i.json,!0)}});if(i.url!==void 0){let c=new URL(i.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.")}return{kind:"http",request:a,responseFormat:e.program.responseFormat}}var kPt=p.object({operation:Ic,save:p.record(p.string(),be)}).strict();function $Ue(e){return e.kind==="http"?{kind:e.kind,request:e.request}:e}async function Rre(e,t){let r=e.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=kq.parse(r.invocation.input);if(t.kind!=="revoke"||C(t.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==e.ownerId||n.environmentId!==e.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let i=Dq.parse(r.invocation.input);if(i.ownerId!==e.ownerId||i.environmentId!==e.environmentId||i.operation.kind!==t.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in i.operation){if(await te($Ue(t))!==i.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(t.kind==="http"&&i.operation.kind==="http"){if(C(t.request)!==C(i.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(t)!==C(Ic.parse(i.operation)))throw new Error("Run the reviewed command.");if(t.kind==="http"&&C(Object.fromEntries(Object.entries(t.save).map(([n,o])=>[n,o.name])))!==C(i.save))throw new Error("Use the reviewed output destinations.")}function PUe(e,t){return e.policy.contentType===ge.value?t.output===void 0:e.policy.contentType===ge.tokenSet&&t.output!==void 0}var Po=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}};function T4(e){return!(e instanceof Me)||["service_unavailable","connection_uncertain","lease_lost"].includes(e.code)}var QE=class{constructor(t,r,i,n,o,s,a,c=s){this.environment=t;this.keys=r;this.broker=i;this.journal=n;this.transport=o;this.commands=s;this.extension=a;this.functionCommands=c}environment;keys;broker;journal;transport;commands;extension;functionCommands;get binding(){return this.environment.manifest.executor}async reconcile(){let t=[];for(let r of await this.journal.pending("run_"))try{let i=await this.journal.read(r);if(!i||i.delivered)continue;if(!i.receipt&&i.phase==="dispatched"){let n=i.operation?.kind==="connect"?await this.extension?.recover?.(i.operation.input,i.request.intent):null;i.receipt=n?await _l(i.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await _l(i.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),i.phase="settled",await this.journal.write(r,i)}i.receipt&&(await this.broker.finish(i.lease,i.receipt),i.delivered=!0,await this.journal.write(r,i))}catch{t.push(r.slice(4))}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:i}=r.request,n="run_"+i.id,o=await te(r.request),s=await this.journal.read(n);if(s&&s.digest!==o)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 m=await _l(i,"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:m,delivered:!1}),await this.broker.finish(r.lease,m),!0}s={digest:o,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([t,a.signal]),u=setInterval(()=>{this.broker.renew(i.id,r.lease).then(m=>{m.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let m=await qq(r.request,this.binding,this.keys);await bl(this.environment,m.intent);let f=Ic.parse(m.operation);if(Q[f.kind]!==i.operation)throw new Error("Use the operation authorized by this intent.");await Rre(i,f),await this.validateOperation(f,i,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(i.id,r.lease),c.throwIfAborted();let g=await this.executeOperation(f,i,r.sources,c);d=await _l(i,"succeeded",{ok:!0,result:g,error:null},this.keys)}catch(m){if(m instanceof Po)throw m;m instanceof Sl&&(m=new Me(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||T4(m));d=await _l(i,f?"uncertain":"failed",{ok:!1,result:null,error:m instanceof Me?{code:m.code,message:m.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(t){let r=t.kind==="function"?YE(t.definition,t.arguments):t;return r.kind==="http"?r.request:null}async validateOperation(t,r,i){if(new Set(i.map(u=>u.policy.id)).size!==i.length||i.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let u of i){await on(u);let l=r.sources.find(f=>f.id===u.policy.id);if(!l||!await sO(u,l))throw new Error("An execution input changed.");let d="checkpoint_"+u.policy.format+"_"+u.policy.id,m=await this.journal.read(d);if(m&&(u.policy.revision<m.policy||u.materialRevision<m.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(d,{policy:u.policy.revision,material:u.materialRevision})}if(t.kind==="function"&&(t.functionId!==r.functionId||await te(t.definition)!==r.functionDigest||!this.environment.manifest.capabilities.includes(Q[t.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(t.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(t),o=n?.url;if(n){if(n.connectionId){let u=i.find(l=>l.policy.id===n.connectionId);if(this.environment.manifest.httpVersion!==zi||!this.extension?.httpDestination||!u||u.policy.contentType!==ge.tokenSet)throw new Error("Choose an HTTP connection and a current execution environment.");o=await this.extension.httpDestination(u,r,n)}if(Pn(o,r.origin),[n.body,n.json,n.form].filter(u=>u!==void 0).length>1)throw new Error("Choose one request body format.");for(let u of n.bindings){let l=qh(u.pointer);if(!l.length||!["headers","body","json","form"].includes(l[0])||l[0]==="body"&&l.length!==1||["headers","form"].includes(l[0])&&l.length!==2)throw new Error("Bind credentials to request headers or the body.");E4(structuredClone(n),u.pointer,"validation")}}let s=t.kind==="function"?t.outputs:t.kind==="http"?t.save:{};for(let[u,l]of Object.entries(s)){if(qh(u),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let d=await Us(l.approval);if(C(d.policy.authorities.find(m=>m.id===d.authorityId))!==C(r.actor)||d.policy.origin!==r.origin||d.policy.contentType!==ge.value||d.policy.ownerId!==r.ownerId||!d.policy.producers.some(m=>m.runId===r.id&&C(m.executor)===C(this.binding)&&Date.parse(m.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let a=t.kind==="function"?YE(t.definition,t.arguments):t,c=a.kind==="command"?a.inputs.map(u=>u.source):n?Uf(n):[];for(let u of c){let l=i.find(m=>m.policy.id===u.id),d=n?.connectionId===u.id&&u.output===void 0;if(!l||!(d?l.policy.contentType===ge.tokenSet:PUe(l,u)))throw new Error("Use the input named in the signed request.");await Os(l,r,{destination:o}),await Ec(l,r,this.keys,{destination:o})}if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(t.input,r,i)}}async executeOperation(t,r,i,n){if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke")return this.extension.execute(t.input,r,i,n);let o=this.request(t),s=t.kind==="function"?YE(t.definition,t.arguments):t,a=o?.connectionId?await this.extension.httpDestination(i.find(v=>v.policy.id===o.connectionId),r,o):o?.url,c=[],u=new Map,l=async v=>{let S=i.find(_=>_.policy.id===v.id);if(S.policy.contentType===ge.value)return Ec(S,r,this.keys,{...o?{destination:a}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");u.has(v.id)||u.set(v.id,this.extension.outputs(S,r,i,n,a));let b=await u.get(v.id);if(!v.output||!Object.hasOwn(b,v.output))throw new Error("Choose an available connection output.");return ft(b[v.output])};if(s.kind==="command"){let v=await $4(s.inputs,l),b=await(t.kind==="function"?this.functionCommands:this.commands).execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:v.environment,files:v.files,...t.kind==="function"?{workspace:"temporary"}:{}},n);if(t.kind==="function"){if(b.timedOut)throw new Me(408,"function_timeout","The function exceeded its time limit.");if(b.truncated)throw new Me(413,"function_output_limit","The function output exceeded its size limit.");if(b.exitCode!==0)throw new Me(422,"function_failed",op(b.stderr,v.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(t,r,b.stdout)}return{...b,stdout:op(b.stdout,v.sensitive),stderr:op(b.stderr,v.sensitive)}}let d=structuredClone(o);for(let v of d.bindings){let S="";for(let b of v.parts)if(typeof b=="string")S+=b;else{let _=Ci(await l(b));c.push(_,Buffer.from(_).toString("base64"),Buffer.from(_).toString("base64url")),S+=_}E4(d,v.pointer,S)}if(d.connectionId){if(!this.extension?.http)throw new Error("This executor cannot use HTTP connections.");let v=await this.extension.http(i.find(S=>S.policy.id===d.connectionId),r,i,n,d);d.url=v.url,d.headers=v.headers,c.push(...v.sensitive)}let m=d.body;d.json!==void 0&&(m=JSON.stringify(d.json),d.headers["content-type"]="application/json"),d.form!==void 0&&(m=new URLSearchParams(d.form).toString(),d.headers["content-type"]="application/x-www-form-urlencoded");let f=await this.transport.send({url:d.url,method:d.method,headers:d.headers,...m===void 0?{}:{body:m},signal:n});if(t.kind==="function"){if(f.status<200||f.status>=300)throw new Me(502,"service_response","The service returned HTTP "+f.status+".");let v=t.definition.program.kind==="http"?t.definition.program.responseFormat:"json",S=Ci(f.body);if(v==="json")try{S=f.body.length===0&&([204,205].includes(f.status)||d.method==="HEAD")?null:Nr.parse(JSON.parse(S))}catch{throw new Me(422,"invalid_function_result","The HTTP response body must contain valid JSON.")}return this.functionResult(t,r,JSON.stringify({status:f.status,headers:f.headers,body:S}))}let g=t.kind==="http"?t.save:{};if(Object.keys(g).length){if(f.status>=400)throw new Me(502,"service_response","The service returned an unsuccessful response.");let v={};for(let[S,b]of Object.entries(g)){let _=f.body;if(S!==""){let T=Wn(JSON.parse(Ci(_)),S);if(T===void 0)throw new Me(400,"invalid_pointer","The response value was not found.");_=ft(typeof T=="string"?T:JSON.stringify(T))}let x=await Af(_,b.approval,r.id,this.binding,this.keys,{bytes:_.length});v[b.name]=(await this.broker.capture(b.name,x)).id}return{status:f.status,saved:v}}return{status:f.status,headers:Object.fromEntries(Object.entries(f.headers).map(([v,S])=>[v,op(S,c)])),body:op(Ci(f.body),c)}}async functionResult(t,r,i){let n;try{n=t.definition.result==="text"?i:Nr.parse(JSON.parse(i))}catch{throw new Me(422,"invalid_function_result","The function must return valid JSON.")}let o={};for(let[s,a]of Object.entries(t.outputs)){let c=s===""?n:Wn(n,s);if(c===void 0)throw new Me(400,"invalid_pointer","The function result value was not found.");let u=ft(typeof c=="string"?c:JSON.stringify(c)),l=await Af(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});o[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(o).length?{saved:o}:n}};import{spawn as Ire}from"node:child_process";import{mkdir as $re,mkdtemp as TUe,rm as CUe,writeFile as Pre}from"node:fs/promises";import{tmpdir as kUe}from"node:os";import{join as Kh}from"node:path";import{StringDecoder as Tre}from"node:string_decoder";function Cre(e={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...e}}var Bh=class{constructor(t){this.options=t;if(t.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(t.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(t,r){r.throwIfAborted();let i=await TUe(Kh(kUe(),"foundation-job-")),n=Kh(i,"files"),o="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=t.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await $re(n,{mode:448});let l={...t.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[m,f]of Object.entries(t.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m))throw new Error("Use valid file variable names.");await Pre(Kh(n,m),Buffer.from(f,"base64"),{mode:384,flag:"wx"}),l[m]=s?"/run/foundation/"+m:Kh(n,m)}let d=t.command;if(s){if(Object.entries(l).some(([g,v])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(g)||v.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let m=Object.entries(l).filter(([,g])=>/[\r\n]/.test(g)),f=Kh(i,"environment");await Pre(f,Object.entries(l).filter(([,g])=>!/[\r\n]/.test(g)).map(([g,v])=>g+"="+v).join(`
122
+ `}),outputs:ZD,hint:p.string().optional()}).strict(),pl=p.string().regex(/^[A-Z_][A-Z0-9_]*$/),hq=p.union([p.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),p.object({output:pl}).strict()]),IS=p.object({urlField:p.string().min(1).max(100).optional(),authentication:p.discriminatedUnion("kind",[p.object({kind:p.literal("none")}).strict(),p.object({kind:p.literal("bearer"),token:pl}).strict(),p.object({kind:p.literal("basic"),username:pl,password:pl}).strict(),p.object({kind:p.literal("header"),name:hq,value:pl}).strict(),p.object({kind:p.literal("query"),name:hq,value:pl}).strict()])}).strict(),Sf={name:be,docs:p.url().optional(),console:gc.optional(),http:IS.optional(),preparation:p.object({scopeSelection:p.enum(["optional","required","hidden"]).default("optional"),instructions:p.array(p.union([p.string().max(2e3),p.object({ja:p.string().max(2e3),en:p.string().max(2e3)}).strict()])).max(10).default([]),docs:p.boolean().default(!1)}).strict().optional()},$S=p.object({...Sf,kind:p.literal("oauth"),config:Ywe}).strict(),PS=p.object({...Sf,kind:p.literal("token"),config:Qwe}).strict(),TS=p.object({...Sf,kind:p.literal("aws"),config:ebe}).strict(),CS=p.object({...Sf,kind:p.literal("ovh"),config:tbe}).strict(),kS=p.object({...Sf,kind:p.literal("approval"),config:p.object({adapter:p.literal("runpod-flash"),fields:p.array(RS).default([]),scopes:XD.default({default:[],separator:" "}),outputs:ZD,hint:p.string().optional()}).strict()}).strict(),fl=p.discriminatedUnion("kind",[$S,PS,TS,CS,kS]),yf={id:p.string().min(1),builtin:p.boolean(),availability:p.enum(["ready","app-required","unavailable"]),defaultName:be,registration:p.object({kind:p.enum(["input","authorization"]),device:p.enum(["browser","cli"]),browserExchange:p.enum(["available","unavailable","unknown"]),tokenAlternatives:p.array(p.string())}).strict()},rbe=p.discriminatedUnion("kind",[$S.extend(yf),PS.extend(yf),TS.extend(yf),CS.extend(yf),kS.extend(yf)]),vf=p.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),QD=p.object({name:be,logo:p.string().regex(/^[a-z0-9-]+$/).optional(),api:p.url().optional(),docs:p.url().optional(),console:p.url().optional(),targets:p.array(p.object({id:vf,name:be,api:p.url().optional(),methods:p.array(vf).min(1)}).strict()).max(32).optional()}).strict(),nbe=QD.extend({methods:p.record(vf,p.string().min(1))}).strict(),wq=QD.extend({methods:p.record(vf,p.union([p.string().min(1),fl]))}).strict(),L7e=QD.extend({id:p.string(),builtin:p.boolean(),methods:p.record(vf,rbe)}),bq=p.object({id:P,output:p.string().min(1).max(100).optional()}).strict(),_q=e=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(e),ibe=p.object({name:p.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:bq,format:p.enum(["text","file","json"]).default("text"),pointer:p.string().optional()}).strict(),obe=p.object({pointer:p.string().max(500),parts:p.array(p.union([p.string().max(8192),bq])).min(1).max(32)}).strict(),yc=p.object({url:p.string().min(1).max(4096).optional(),connectionId:P.optional(),method:p.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:p.record(p.string(),p.string().max(8192)).default({}),body:p.string().max(1e6).optional(),json:Nr.optional(),form:p.record(p.string(),p.string()).optional(),bindings:p.array(obe).max(32).default([])}).strict().refine(e=>!!(e.url||e.connectionId),{message:"Choose a connection or enter a destination URL."}),vc=p.object({command:p.array(p.string().max(8192)).min(1).max(100),stdin:p.string().max(1e6).optional(),timeoutSeconds:p.number().int().min(1).max(3600).default(60),inputs:p.array(ibe).max(32).default([])}).strict(),xq=p.discriminatedUnion("kind",[vc.omit({stdin:!0}).extend({kind:p.literal("command")}).strict(),p.object({kind:p.literal("http"),request:yc,responseFormat:p.enum(["text","json"]).default("json")}).strict()]),ks=p.object({description:p.string().max(2e3).default(""),program:xq,parameters:p.array(p.object({name:p.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:p.string().max(100),type:p.enum(["string","number","boolean","json"]).default("string"),required:p.boolean().default(!0),default:Nr.optional()}).strict()).max(32).default([]),result:p.enum(["text","json"]).default("json")}).strict(),wf=p.object({expiresAt:ce.nullable().default(null)}).strict(),M7e=p.object({version:p.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:wf,state:p.enum(["publication_required","unconfigured","configured","approval_required","unavailable","expired"])}).strict(),Fo={id:P,ownerId:P,name:be,createdAt:ce,updatedAt:ce,version:p.number().int().positive(),permissions:p.array(yq)},sbe=p.enum(["starting","running","stopping","stopped","failed"]),abe=p.enum(["manual","idle","timeout","quota","capacity","payment"]),cbe=p.object({state:p.enum(["pending","failed","complete"]),error:p.string().nullable()}),ube=p.object({idleSeconds:p.number().int().min(60).max(2147483647).nullable().default(null),maxSeconds:p.number().int().min(60).max(2147483647).nullable().default(null)}).strict(),Eq=p.object({size:p.enum(["small","medium","large"]).default("small"),lifetime:ube.default({idleSeconds:null,maxSeconds:null}),ssh:Bv.optional()}).strict(),eO={recipients:p.array(P).default([]),executors:p.array(P).default([]),custodyRevision:p.number().int().positive().nullable().default(null)},lbe=p.object({...Fo,kind:p.literal("variable"),data:p.object({...eO,bytes:p.number().int().nonnegative()})}),dbe=p.object({...Fo,kind:p.literal("connection"),data:p.object({...eO,methodId:p.string(),fields:p.record(p.string(),p.string()).default({}),settings:p.array(p.object({name:p.string(),label:p.string(),value:p.string()})).default([]),methodName:p.string(),methodKind:YD,http:IS.optional(),services:p.array(p.object({id:p.string(),name:be})).default([]),account:p.string(),accountId:p.string().nullable().default(null),accountVerified:p.boolean().default(!1),scopes:p.array(p.string()),scopesStatus:p.enum(["unknown","requested","reported"]).default("unknown"),outputs:p.array(p.string()),state:p.enum(["ready","reconnect","review","disconnecting","uncertain"]),revocable:p.boolean().default(!1),appId:P.nullable(),generation:P.optional(),authorizationDigest:p.string().optional(),aws:bS.optional(),ovh:gf.optional()})}),pbe=p.object({...Fo,kind:p.literal("service"),data:nbe}),fbe=p.object({...Fo,kind:p.literal("method"),data:fl}),mbe=p.object({...Fo,kind:p.literal("app"),data:p.object({...eO,methodId:p.string(),clientId:p.string(),fields:p.record(p.string(),p.string()).default({}),generation:P.optional()})}),hbe=p.object({...Fo,kind:p.literal("object"),data:p.object({size:p.number().int().nonnegative(),contentType:p.string()})}),gbe=p.object({...Fo,kind:p.literal("environment"),data:Eq.extend({executorId:P.optional(),operatorId:P.optional(),driver:p.enum(["attached","managed"]).optional(),capabilities:p.array(p.string()).optional(),isolation:p.enum(["process","container"]).optional(),manifestDigest:p.string().optional(),processes:p.object({workingDirectory:p.string()}).optional(),ssh:ED.optional(),awsPrincipal:p.string().optional(),state:sbe,connected:p.boolean(),deletion:cbe.optional(),startedAt:ce.nullable(),stoppedAt:ce.nullable(),stopReason:abe.nullable().default(null),lastActiveAt:ce,error:p.string().nullable()})}),ybe=p.object({...Fo,kind:p.literal("function"),data:ks.omit({program:!0}).extend({program:xq.optional()})}),vbe=p.object({...Fo,kind:p.literal("keyring"),data:p.object({revision:p.number().int().positive(),signature:p.string()})}),ml=p.discriminatedUnion("kind",[lbe,dbe,pbe,fbe,mbe,hbe,gbe,ybe,vbe]),z7e=p.discriminatedUnion("kind",[p.object({kind:p.literal("service"),name:be,definition:wq}).strict(),p.object({kind:p.literal("method"),name:be,definition:fl}).strict(),p.object({kind:p.literal("environment"),name:be.optional(),options:Eq}).strict()]),j7e=p.object({version:p.number().int().positive(),name:be.optional(),definition:p.union([wq,fl]).optional()}).strict(),Sc=p.object({name:p.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Mt}).strict(),DS=Sc.extend({inputs:p.array(p.object({pointer:p.string(),label:p.string().min(1).max(100),secret:p.boolean().default(!1),multiline:p.boolean().default(!1),site:p.url().optional()}).strict()).max(16).default([])}),ES=p.object({ja:p.string(),en:p.string()}).strict(),tO=DS.extend({title:ES,execution:p.enum(["server","keyholder"]),configure:p.array(p.string()),environment:p.object({required:p.boolean(),reason:ES.nullable()}).strict()}),F7e=p.object({to:P.optional(),executionId:P.optional(),message:p.string().max(1e3).default(""),operations:p.array(DS).min(1).max(8).optional(),expiresInMinutes:p.number().int().min(1).max(1440).default(30)}).strict().superRefine((e,t)=>{!!e.executionId==!!e.operations&&t.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),_S=p.object({id:P,name:be}),Aq=p.discriminatedUnion("kind",[p.object({kind:p.literal("line"),subject:_S,relation:Sq,object:_S}),p.object({kind:p.literal("transfer"),item:_S,to:_S})]),G7e=p.object({id:P,executionId:P,from:Cs.pick({id:!0,name:!0}),to:Cs.pick({id:!0,name:!0}).nullable(),message:p.string(),purpose:p.enum(["input","approval"]),state:p.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:ce,expiresAt:ce,url:p.url(),code:p.string().optional(),returnUrl:p.url().nullable(),refreshUrl:p.url().nullable(),canRespond:p.boolean(),canCancel:p.boolean()}),q7e=p.object({id:P,name:be,publicKey:Jr,state:p.enum(["pending","approving","approved"]),principalId:P.nullable(),createdAt:ce,expiresAt:ce}),V7e=p.object({available:p.boolean(),required:p.boolean(),active:p.boolean(),payer:Cs.pick({id:!0,name:!0}).nullable()}),K7e=p.object({storageBytes:p.number().nonnegative(),storageLimit:p.number().positive(),computeSeconds:p.number().nonnegative(),computeLimit:p.number().positive(),month:p.string()}),B7e=p.object({id:p.string(),actorId:P.nullable(),action:p.string(),targetId:P.nullable(),createdAt:ce,details:Mt}),H7e=p.object({returnUrl:p.url().optional(),refreshUrl:p.url().optional()}).strict(),hl=e=>p.object({items:p.array(e),next:p.string().nullable().default(null)}),W7e=p.object({id:P}),J7e=p.object({owner:P}),Sbe=p.object({limit:p.coerce.number().int().min(1).max(200).default(100),after:p.string().optional()}),Z7e=Sbe.extend({object:P.optional(),subject:P.optional()}).refine(e=>!!e.object!=!!e.subject,"Choose the object or the subject of the lines.");var bbe=new TextEncoder,_be=new TextDecoder,OS="ECDH-ES+A256KW",Rq="A256GCM",ft=e=>bbe.encode(e),NS=e=>_be.decode(e);function Ds(e){let t="";for(let r=0;r<e.length;r+=8192)t+=String.fromCharCode(...e.subarray(r,r+8192));return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Iq(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}async function wc(e,t,r){if(!t.length||new Set(t.map(n=>n.id)).size!==t.length)throw new Error("Recipients must be distinct and nonempty.");let i=new ff(e).setProtectedHeader({enc:Rq}).setAdditionalAuthenticatedData(ft(r));for(let n of t)i.addRecipient(await An(n.publicKey,OS)).setUnprotectedHeader({alg:OS,kid:n.id});return jo.parse(await i.encrypt())}async function bc(e,t,r,i){if(e.aad!==Ds(ft(i)))throw new Error("The encrypted content belongs to a different item.");let n=e.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let o=t instanceof CryptoKey?t:await An(t,OS);return(await LD({...e,recipients:[n]},o,{keyManagementAlgorithms:[OS],contentEncryptionAlgorithms:[Rq]})).plaintext}var yt=p.string().regex(/^[A-Za-z0-9_-]{43}$/),_t=p.string().min(100).max(4e6),$q=Jr.extend({d:p.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Tq=p.object({encryption:$q,signing:$q}).strict(),vt=p.object({id:P,principalId:P,generation:p.number().int().positive(),previous:yt.nullable(),encryption:Jr,signing:Jr}).strict();function C(e){if(e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&!/[\uD800-\uDFFF]/u.test(e))return JSON.stringify(e);if(Array.isArray(e))return"["+Array.from(e,C).join(",")+"]";if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype)return"{"+Object.keys(e).sort().map(t=>{if(/[\uD800-\uDFFF]/u.test(t))throw new Error("Use Unicode property names.");return JSON.stringify(t)+":"+C(e[t])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Pq(e){return HD(Jr.parse({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),"sha256")}async function te(e){return Ds(new Uint8Array(await crypto.subtle.digest("SHA-256",ft(C(e)))))}async function US(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",ft(C(e))));return"sha256:"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}async function Tt(e,t,r){let i=t instanceof CryptoKey?t:await An(t,"ES256");return new hf(ft(C(e))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(i)}async function nr(e,t,r,i){if(C(await bf(t,r,i))!==C(e))throw new Error("The signature does not authorize this content.")}async function bf(e,t,r){let i=await KD(e,await An(Jr.parse(t),"ES256"),{algorithms:["ES256"]});if(i.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(i.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(i.payload),o=JSON.parse(n);if(C(o)!==n)throw new Error("Sign canonical JSON content.");return o}var gl=p.object({binding:vt,signature:_t}).strict();async function Mi(e){let t=vt.parse(e);if(t.generation===1!=(t.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Pq(t.encryption)===await Pq(t.signing))throw new Error("Use separate encryption and signing keys.");await An(t.encryption,"ECDH-ES+A256KW"),await An(t.signing,"ES256")}async function LS(e){let{binding:t,signature:r}=gl.parse(e);return await Mi(t),await nr(t,r,t.signing,"key-binding"),t}var Cq=p.object({ownerId:P,name:be,resourceId:P.optional(),version:p.number().int().positive().optional(),environmentIds:p.array(P).max(32).optional()}).strict(),uXe=Cq.extend({value:p.literal("").optional()}),lXe=Cq.extend({methodId:p.string().min(1).max(200),clientId:p.string().max(1e3),fields:p.record(p.string(),p.string()).optional(),clientSecret:p.literal("").optional()}),dXe=p.object({ownerId:P,name:be,definition:ks,resourceId:P.optional(),version:p.number().int().positive().optional()}).strict(),pXe=p.object({functionId:P,functionVersion:p.number().int().positive(),version:p.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:wf.default({expiresAt:null})}).strict(),kq=p.object({ownerId:P,connectionId:P,environmentId:P}).strict(),fXe=p.object({ownerId:P,connectionId:P,version:p.number().int().positive(),users:p.array(P).max(32),expiresAt:p.iso.datetime().optional()}).strict(),mXe=p.object({ownerId:P,methodId:p.string().min(1).max(200),connectionId:P.optional(),name:be.optional(),appId:P.optional(),redirectUri:p.url().optional(),users:p.array(P).max(32).optional(),scopes:p.array(p.string().min(1).max(1e3)).max(200).optional(),methodDigest:p.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:p.string().max(1e3).optional(),fields:p.record(p.string(),p.string()).optional(),clientSecret:p.literal("").optional()}).strict(),Dq=p.object({ownerId:P,environmentId:P.optional(),operation:p.union([p.object({kind:p.literal("http"),request:yc}).strict(),vc.extend({kind:p.literal("command")}),p.object({kind:p.enum(["http","command"]),programId:P,programDigest:p.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:p.record(p.string(),be).default({})}).strict().superRefine((e,t)=>{e.environmentId||t.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),hXe=p.object({name:Sc.shape.name,title:ES,execution:p.enum(["server","keyholder"]),configure:p.array(p.string()),environment:tO.shape.environment,input:Mt}).strict(),gXe=p.object({id:P.optional(),operations:p.array(DS).min(1).max(8),responderId:P.optional(),message:p.string().max(1e3).default(""),expiresInMinutes:p.number().int().min(1).max(1440).default(1440)}).strict(),yXe=p.object({values:p.array(Mt).max(8).default([]),configuration:p.array(Mt).max(8).default([]),code:p.string().max(20).optional()}).strict(),xbe=p.object({index:p.number().int().nonnegative(),invocation:Sc,approval:p.object({id:P,index:p.number().int().nonnegative()}).strict().optional(),continuation:p.object({kind:p.enum(["connection","run"]),id:P}).strict().nullable()}).strict(),Oq=p.object({id:P,actorId:P,ownerId:P,requests:p.array(P),steps:p.array(p.object({index:p.number().int().nonnegative(),name:Sc.shape.name,state:p.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:p.array(p.object({kind:p.enum(["run","function","process"]),id:P}).strict())}).strict()),creator:Cs.pick({id:!0,name:!0}),operations:p.array(tO),approval:p.object({requestId:P.nullable(),proposal:Aq.nullable()}).strict().nullable(),canContinue:p.boolean(),canCancel:p.boolean(),url:p.url(),code:p.string().optional(),error:p.object({code:p.string(),message:p.string()}).strict().nullable(),index:p.number().int().nonnegative(),state:p.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:p.enum(["approval","input","execution"]).nullable(),waiting:xbe.nullable(),results:p.array(Nr.nullable()),createdAt:p.iso.datetime(),expiresAt:p.iso.datetime()}).strict(),Nq=p.object({id:P,index:p.number().int().nonnegative(),invocation:Sc,continuationId:P.optional()}).strict();var yl=p.url().refine(e=>{let t=new URL(e);return t.origin===e&&!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ge={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},Ebe=p.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),Lq=e=>e===ge.executionResult?14e5:1e6,Q={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"},_f=p.enum([Q.http,Q.command,Q.function,Q.connect,Q.refresh,Q.revoke]);var Abe={[ge.value]:[Q.http,Q.command,Q.function],[ge.tokenSet]:[Q.http,Q.command,Q.function,Q.refresh,Q.revoke],[ge.clientCredential]:[Q.connect,Q.refresh,Q.revoke],[ge.executionResult]:[]},rO=e=>Abe[e];var nO=e=>e===ge.tokenSet,Rbe=p.object({id:P,digest:yt}).strict(),Ibe=p.object({actor:vt,executor:vt,operations:p.array(_f).min(1).max(6),functionDigests:p.array(yt).max(100).default([]),origins:p.array(yl).max(100).default([]),callerProgram:p.boolean().default(!1),expiresAt:ce}).strict(),$be=p.object({function:Rbe,executor:vt,operations:p.array(_f).min(1).max(6),expiresAt:ce.nullable()}).strict(),Pbe=p.union([Ibe,$be]);function Go(e,t=Date.now()){return e.expiresAt===null||Date.parse(e.expiresAt)>t}function vl(e){return e.expiresAt===null?1/0:Date.parse(e.expiresAt)}var qo=p.object({format:p.literal(2),origin:yl,id:P,ownerId:P,contentType:Ebe,revision:p.number().int().positive(),authorities:p.array(vt).min(1).max(100),readers:p.array(vt).min(1).max(100),grants:p.array(Pbe).max(100),observers:p.array(P).max(100).optional(),producers:p.array(p.object({executor:vt,runId:P,expiresAt:ce,materialRevision:p.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),Uq=p.object({ownerId:P,authorities:p.array(vt).min(1).max(100)}).strict(),Mq=p.object({origin:yl,id:P,revision:p.number().int().positive(),from:Uq,to:Uq,policyDigest:yt,previous:yt.nullable(),signerId:P}).strict(),Tbe=Mq.extend({signature:_t}),iO=p.array(Tbe).max(16),xf=p.object({policy:qo,authorityId:P,signature:_t,lineage:iO.optional()}).strict(),ir=p.object({policy:qo,authorityId:P,authorization:_t,lineage:iO.optional(),materialRevision:p.number().int().positive(),updatedAt:ce,creationRunId:P.nullable(),metadata:Mt,sealed:jo,signerId:P,signature:_t}).strict(),_c=e=>({ownerId:e.ownerId,authorities:e.authorities});async function zq(e,t=[]){let r;for(let i of t){let{signature:n,...o}=i;if(i.origin!==e.origin||i.id!==e.id||i.revision>e.revision||r&&(i.revision<=r.revision||C(r.to)!==C(i.from))||i.previous!==(r?await te(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=i.from.authorities.find(a=>a.id===i.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await nr(o,n,s.signing,"authority-handoff"),r=i}if(r&&C(r.to)!==C(_c(e)))throw new Error("Use the authorities approved by the latest handoff.")}function oO(e){let t=e.policy.authorities.find(n=>n.id===e.authorityId);if(t)return t;let r=e.lineage?.at(-1),i=r?.revision===e.policy.revision?r.from.authorities.find(n=>n.id===e.authorityId):void 0;if(!i||i.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return i}function MS(e,t){if(e.id!==t.policy.id||e.origin!==t.policy.origin||e.contentType!==t.policy.contentType)return!1;let r=C(_c(e));return r===C(_c(t.policy))?!0:!!t.lineage?.some(i=>i.revision>e.revision&&C(i.from)===r)}async function jq(e,t,r,i){let n=[...e?.lineage??[]];if(e&&C(_c(e.policy))!==C(_c(t))){if(await on(e),!e.policy.authorities.some(s=>C(s)===C(r))||e.policy.id!==t.id||e.policy.origin!==t.origin||e.policy.contentType!==t.contentType||t.revision!==e.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let o=Mq.parse({origin:t.origin,id:t.id,revision:t.revision,from:_c(e.policy),to:_c(t),policyDigest:await te(t),previous:n.length?await te(n.at(-1)):null,signerId:r.id});n.push({...o,signature:await Tt(o,i.signing,"authority-handoff")})}return n.length?{lineage:iO.parse(n)}:{}}async function zS(e){let t=qo.parse(e),r=[...t.authorities,...t.readers,...t.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...t.producers.map(n=>n.executor)],i=new Map;for(let n of r){await Mi(n);let o=C(n);if(i.has(n.id)&&i.get(n.id)!==o)throw new Error("Each key binding must identify the same keys throughout a policy.");i.set(n.id,o)}for(let n of[t.readers,t.authorities])if(new Set(n.map(o=>o.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of t.authorities)if(!t.readers.some(o=>o.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of t.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(o=>!rO(t.contentType).includes(o)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(o=>o!==Q.function&&o!==Q.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(o=>o===Q.http||o===Q.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(Q.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return t}function jS(e){return[...new Map([...e.readers,...e.grants.map(t=>t.executor)].map(t=>[t.id,t])).values()]}async function Ns(e,t){return C({purpose:"resource",policyDigest:await te(e),materialRevision:t})}async function Ef(e,t,r,i,n,o,s){if(e.byteLength>Lq(t.contentType))throw new Error("The content exceeds its storage limit.");let a=await zS(t),c=await jq(s,a,i,n);if(!a.authorities.some(m=>C(m)===C(i))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(a,r)),l={policy:a,...c,authorityId:i.id,authorization:await Tt(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:o??(a.contentType===ge.value?{bytes:e.byteLength}:{}),sealed:u,signerId:i.id},d=ir.parse({...l,signature:await Tt(l,n.signing,"resource")});return await on(d),d}async function on(e){let t=ir.parse(e),{signature:r,...i}=t;await zS(t.policy),await zq(t.policy,t.lineage);let n=oO(t),o=t.lineage?.at(-1);if(o?.revision===t.policy.revision&&o.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");await nr(t.policy,t.authorization,n.signing,"access-policy");let s=(t.signerId===n.id?n:void 0)??t.policy.authorities.find(u=>u.id===t.signerId)??t.policy.producers.find(u=>u.executor.id===t.signerId&&u.runId===t.creationRunId&&u.materialRevision===t.materialRevision&&(t.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(t.updatedAt)))?.executor??(nO(t.policy.contentType)?t.policy.grants.find(u=>u.executor.id===t.signerId&&u.operations.includes(Q.refresh)&&Go(u,Date.parse(t.updatedAt)))?.executor:void 0);if(!s||Date.parse(t.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await nr(i,r,s.signing,"resource");let a=jS(t.policy).map(u=>u.id).sort(),c=t.sealed.recipients.map(u=>u.header.kid).sort();if(C(a)!==C(c)||t.sealed.aad!==Ds(ft(await Ns(t.policy,t.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return t}async function Fq(e,t,r,i,n=e.metadata){let o=await on(e);if(!nO(o.policy.contentType)||!(o.policy.authorities.some(m=>C(m)===C(r))||o.policy.grants.some(m=>C(m.executor)===C(r)&&m.operations.includes(Q.refresh)&&Go(m))))throw new Error("This executor cannot renew this connection.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=o.materialRevision+1,a=await wc(t,jS(o.policy).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(o.policy,s)),{signature:c,...u}=o,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await Tt(l,i.signing,"resource")};return await on(d),d}async function FS(e,t,r,i){let n=await zS(e);if(!n.authorities.some(s=>C(s)===C(t)))throw new Error("Only an authority can approve this policy.");let o={policy:n,...await jq(i,n,t,r),authorityId:t.id,signature:await Tt(n,r.signing,"access-policy")};return await Us(o),o}async function Us(e){let t=xf.parse(e);await zS(t.policy),await zq(t.policy,t.lineage);let r=t.lineage?.at(-1);if(r?.revision===t.policy.revision&&r.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");let i=t.policy.authorities.find(n=>n.id===t.authorityId);if(!i)throw new Error("The policy must be signed by an authority.");return await nr(t.policy,t.signature,i.signing,"access-policy"),t}async function Af(e,t,r,i,n,o){let s=await Us(t),{policy:a}=s,c=a.producers.find(m=>m.runId===r&&C(m.executor)===C(i)&&(a.contentType===ge.executionResult||Date.parse(m.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(e.byteLength>Lq(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(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:o,sealed:u,signerId:i.id},d={...l,signature:await Tt(l,n.signing,"resource")};return await on(d),d}async function Rf(e,t,r){let i=await on(e);if(!i.policy.readers.some(n=>C(n)===C(t)))throw new Error("This identity cannot reveal the content.");return bc(i.sealed,r,t.id,await Ns(i.policy,i.materialRevision))}var Cbe=p.object({id:P,policyDigest:yt,materialRevision:p.number().int().positive(),authorizationDigest:yt.optional()}).strict();async function sO(e,t){return t.id===e.policy.id&&t.policyDigest===await te(e.policy)&&(t.authorizationDigest===void 0||t.authorizationDigest===e.metadata.authorizationDigest)&&(t.materialRevision===e.materialRevision||nO(e.policy.contentType)&&t.authorizationDigest!==void 0&&t.authorizationDigest===e.metadata.authorizationDigest&&e.materialRevision>=t.materialRevision)}var GS=p.object({format:p.literal(2),id:P,origin:yl,ownerId:P,approval:p.object({id:P,index:p.number().int().min(0).max(7)}).strict().optional(),operationContext:Nq.optional(),actor:vt,environmentId:P,executor:vt,environmentDigest:yt,operation:_f,functionDigest:yt.nullable(),functionId:P.optional(),operationDigest:yt,sources:p.array(Cbe).max(100),resultRecipients:p.array(vt).min(1).max(100),resultApproval:xf.optional(),createdAt:ce,expiresAt:ce}).strict(),qS=p.object({intent:GS,signature:_t,sealed:jo}).strict();async function xc(e,t){return C({purpose:"run-"+t,origin:e.origin,id:e.id,intentDigest:await te(e)})}async function Gq(e,t,r){if(GS.parse(e),await te(t)!==e.operationDigest)throw new Error("The operation does not match the execution intent.");let i={intent:e,sealed:await wc(ft(C(t)),[{id:e.executor.id,publicKey:e.executor.encryption}],await xc(e,"input"))};return qS.parse({...i,signature:await Tt(i,r.signing,"run")})}async function kbe(e,t=Date.now()){let r=qS.parse(e),{signature:i,...n}=r;await nr(n,i,r.intent.actor.signing,"run");let{intent:o}=r,s=Date.parse(o.createdAt),a=Date.parse(o.expiresAt);if(s>t+3e4||a<=t||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(o.sources.map(c=>c.id)).size!==o.sources.length||new Set(o.resultRecipients.map(c=>c.id)).size!==o.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(o.resultApproval){let c=await Us(o.resultApproval),u=c.policy;if(c.authorityId!==o.actor.id||u.id!==o.id||u.origin!==o.origin||u.ownerId!==o.ownerId||u.contentType!==ge.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>C(l)===C(o.actor))||C(u.readers)!==C(o.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==o.id||C(u.producers[0].executor)!==C(o.executor)||u.producers[0].materialRevision!==1)throw new Error("Approve this execution result for its readers and selected executor.")}if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==o.executor.id||r.sealed.aad!==Ds(ft(await xc(o,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function qq(e,t,r){let i=await kbe(e);if(C(i.intent.executor)!==C(t))throw new Error("This operation belongs to another executor.");let n=await bc(i.sealed,r.encryption,t.id,await xc(i.intent,"input")),o=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(o);if(C(s)!==o||await te(s)!==i.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:i.intent,operation:s}}async function Os(e,t,r={}){let i=await on(e),n=i.policy,o=t.sources.find(c=>c.id===n.id);if(!o||t.origin!==n.origin||!await sO(i,o))throw new Error("The input changed after this execution was authorized.");if(C(t.actor)===C(t.executor)&&n.readers.some(c=>C(c)===C(t.actor)))return i;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(t.actor):c.function.id===t.functionId&&c.function.digest===t.functionDigest)&&C(c.executor)===C(t.executor)&&c.operations.includes(t.operation)&&Go(c,r.now)&&vl(c)>=Date.parse(t.expiresAt)).some(c=>"function"in c?t.operation===Q.function||t.operation===Q.refresh:t.operation===Q.function&&!c.callerProgram&&(!t.functionDigest||!c.functionDigests.includes(t.functionDigest))||!r.destinationPending&&c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:t.operation!==Q.command&&t.operation!==Q.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return i}async function Ec(e,t,r,i={}){let n=i.destination;await Os(e,t,{now:i.now,...typeof n=="function"?{destinationPending:!0}:{destination:n}});let o=await bc(e.sealed,r.encryption,t.executor.id,await Ns(e.policy,e.materialRevision));return typeof n=="function"&&await Os(e,t,{now:i.now,destination:n(o)}),o}var Ac=5,zi=1,aO=p.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Vq=p.object({format:p.literal(3),id:P,origin:yl,ownerId:P,name:be,executor:vt,operatorId:P,driver:p.literal("attached"),capabilities:p.array(_f).min(1).max(6),functionVersion:p.number().int().positive().optional(),httpVersion:p.number().int().positive().optional(),resultVersion:p.literal(1).optional(),isolation:p.enum(["process","container"]),commandImage:p.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),functionImage:p.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:aO.optional(),revision:p.number().int().positive()}).strict(),cO=p.object({manifest:Vq,signature:_t}).strict();async function uO(e,t){let r=Vq.parse(e),i={manifest:r,signature:await Tt(r,t.signing,"environment")};return await wl(i),i}async function wl(e){let t=cO.parse(e),{manifest:r}=t;if(await Mi(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(Q.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");return await nr(r,t.signature,r.executor.signing,"environment"),t}async function bl(e,t){let{manifest:r}=await wl(e);if(t.environmentId!==r.id||t.origin!==r.origin||t.environmentDigest!==await te(r)||C(t.executor)!==C(r.executor)||!r.capabilities.includes(t.operation)||t.operation===Q.function&&r.functionVersion!==Ac)throw new Error("This environment does not authorize the requested execution.")}var VS=p.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),KS=p.object({ok:p.boolean(),result:Nr.nullable(),error:p.object({code:p.string().max(100),message:p.string().max(1e3)}).nullable()}).strict(),Kq={id:P,intentDigest:yt,executorId:P,state:p.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:ce},Bq=p.object({...Kq,sealed:jo,signature:_t}).strict(),Hq=p.object({...Kq,format:p.literal(2),accessDigest:yt,proofDigest:yt,approval:xf,content:ir,previousDigest:yt.optional(),previous:Bq.optional(),signature:_t}).strict(),If=p.union([Bq,Hq]),Dbe=p.object({result:KS,proof:_t}).strict(),Wq=e=>{let{signature:t,content:r,approval:i,previous:n,...o}=e;return o};async function lO(e,t,r,i,n,o){await Us(n);let s={format:2,id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:o?.finishedAt??new Date().toISOString(),accessDigest:await te(n),...o?{previousDigest:await te(o)}:{}},a=await Tt({...s,resultDigest:await te(r)},i.signing,"execution-result"),c=ft(C({result:KS.parse(r),proof:a}));if(c.byteLength>14e5)throw new Sl;let u=await Af(c,n,e.id,e.executor,i,{bytes:c.byteLength}),l={...s,proofDigest:await te(a)},d=Hq.parse({...l,approval:n,content:u,...o?{previous:o}:{},signature:await Tt(l,i.signing,"receipt")});return await dO(d,e),d}var Sl=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function _l(e,t,r,i){let n=KS.parse(r);if(t==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(e.resultApproval)return lO(e,t,n,i,e.resultApproval);let o=ft(C(n));if(o.byteLength>14e5)throw new Sl;let s=await wc(o,e.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await xc(e,"result")),a={id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:new Date().toISOString(),sealed:s};return If.parse({...a,signature:await Tt(a,i.signing,"receipt")})}async function dO(e,t){let r=If.parse(e);if("content"in r){await nr(Wq(r),r.signature,t.executor.signing,"receipt");let o=await Us(r.approval),s=o.policy;if(r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.accessDigest!==await te(o)||o.authorityId!==t.actor.id||!s.authorities.some(a=>C(a)===C(t.actor))||s.id!==t.id||s.origin!==t.origin||s.ownerId!==t.ownerId||s.contentType!==ge.executionResult||s.grants.length||t.resultApproval&&C(t.resultApproval)!==C(o))throw new Error("The result does not belong to the requested execution.");if(!t.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await te(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await dO(r.previous,t),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await on(r.content),!MS(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(t.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:i,...n}=r;if(await nr(n,i,t.executor.signing,"receipt"),r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.sealed.aad!==Ds(ft(await xc(t,"result")))||C(r.sealed.recipients.map(o=>o.header.kid).sort())!==C(t.resultRecipients.map(o=>o.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function Jq(e,t,r,i){if(await dO(e,t),"content"in e){if(!e.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await bc(e.content.sealed,i.encryption,r,await Ns(e.content.policy,e.content.materialRevision)),a=Dbe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await te(a.proof)!==e.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=Wq(e);if(await nr({...u,resultDigest:await te(a.result)},a.proof,t.executor.signing,"execution-result"),e.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await bc(e.sealed,i.encryption,r,await xc(t,"result")),o=KS.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(e.state==="succeeded"!==o.ok)throw new Error("The encrypted result does not match its completion state.");return o}var Obe=p.enum(["http","command","function","connect","refresh","revoke"]),Rc=p.object({id:P,ownerId:P,actorId:P,environmentId:P,kind:Obe,state:VS,intent:GS,requestSignature:_t,receipt:If.nullable(),error:p.string().nullable(),createdAt:ce,startedAt:ce.nullable(),finishedAt:ce.nullable()}).strict(),BS=p.object({name:be,approval:xf}).strict(),Zq=p.object({kind:p.literal("function"),functionId:P,definition:ks,arguments:Mt.default({}),outputs:p.record(p.string(),BS).default({})}).strict(),Ic=p.discriminatedUnion("kind",[p.object({kind:p.literal("http"),request:yc,save:p.record(p.string(),BS).default({})}).strict(),p.object({kind:p.literal("command"),...vc.shape}).strict(),p.object({kind:p.enum(["connect","refresh","revoke"]),input:Nr}).strict()]);var Nbe=p.object({email:p.boolean(),environments:p.boolean(),ssh:p.boolean(),storage:p.boolean(),payments:p.boolean()}),Xq=p.object({principal:Cs.nullable(),credentialId:P.nullable(),wrappedKey:AS.nullable(),requestId:P.nullable(),server:p.object({name:be}),features:Nbe,principals:p.array(Cs)}),OXe=p.object({email:p.email().max(254),returnTo:p.string().max(2048).optional(),locale:gq.default("ja"),principalId:P.optional()}).strict(),NXe=p.object({intent:p.enum(["register","authenticate"]),name:be.optional(),principalId:P.optional(),credentialId:P.optional(),returnTo:p.string().max(2048).optional()}).strict(),UXe=p.object({challengeId:P,credential:p.json(),publicKey:Jr.optional(),existingPublicKey:Jr.optional(),wrappedKey:AS.optional()}).strict();var HS=class extends Error{constructor(r,i,n){super(n);this.code=r;this.status=i}code;status},WS=class{constructor(t){this.identity=t}identity;async response(t,r={}){if(!t.startsWith("/api/")||t.includes("\\")||/[\u0000-\u001f]/.test(t))throw new Error("Use a path beginning with /api/.");let i=new URL(t,this.identity.origin);if(i.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(i,{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 o;try{o=p.object({error:p.object({code:p.string(),message:p.string()})}).parse(await n.json())}catch{throw new HS("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new HS(o.error.code,n.status,o.error.message)}return n}async json(t,r={},i){let n=await this.response(t,r),o=n.status===204?null:await n.json();return i?i.parse(o):o}async session(){return this.json("/api/session",{},Xq)}};import{chmod as Ube,lstat as Lbe,mkdir as Mbe,open as fO,readFile as zbe,rename as jbe,rm as Fbe}from"node:fs/promises";import{dirname as Gbe,join as mO,resolve as qbe}from"node:path";import{homedir as Vbe}from"node:os";import{randomUUID as Kbe}from"node:crypto";var Qq=p.object({origin:p.url(),principalId:p.uuid(),token:p.string().min(20),keys:Tq.nullable(),binding:vt.nullable()}).strict().refine(e=>!!e.keys==!!e.binding&&(!e.binding||e.binding.principalId===e.principalId),"Use the keys bound to this identity."),Bbe=p.object({current:p.uuid(),identities:p.array(Qq).min(1)}).strict().refine(e=>e.identities.some(t=>t.principalId===e.current),"The current identity is missing.");function hO(){return mO(process.env.XDG_CONFIG_HOME||mO(Vbe(),".config"),"foundation","identity.json")}function pO(e=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let t;try{t=new URL(e)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return t.origin}async function Hbe(){try{let e=hO(),t=await Lbe(e);if(!t.isFile()||t.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&t.mode&63&&await Ube(e,384),Bbe.parse(JSON.parse(await zbe(e,"utf8")))}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function eV(e,t){let r=process.env.FOUNDATION_TOKEN,i=t||(r?void 0:process.env.FOUNDATION_PRINCIPAL_ID),n=await Hbe(),o;if(n){if(o=n.identities.find(a=>a.principalId===(i??n.current)),i&&!o&&!r)throw new Error("No saved identity has principal "+i+". Run foundation identity list.")}else if(i&&!r)throw new Error("Run foundation login to sign in on this machine.");let s=pO(e||process.env.FOUNDATION_ORIGIN||o?.origin);if(r){if(e&&process.env.FOUNDATION_ORIGIN&&s!==pO(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let a=process.env.FOUNDATION_PRINCIPAL_ID,c=process.env.FOUNDATION_PRIVATE_KEYS,u=process.env.FOUNDATION_KEY_BINDING;if(!a)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return Qq.parse({origin:s,principalId:a,token:r,keys:c?JSON.parse(Buffer.from(c,"base64url").toString("utf8")):null,binding:u?JSON.parse(Buffer.from(u,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!o)throw new Error("Run foundation login to sign in on this machine.");if(s!==pO(o.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...o,origin:s}}async function Yq(e){if(process.platform==="win32")return;let t=await fO(e,"r");try{await t.sync()}finally{await t.close()}}async function gO(e,t,r){let i=qbe(e),n=Gbe(i);if(await Mbe(n,{recursive:!0,mode:448}),!r){let s=await fO(i,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await Yq(n);return}let o=mO(n,".foundation-"+Kbe());try{let s=await fO(o,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await jbe(o,i),await Yq(n)}finally{await Fbe(o,{force:!0})}}import{mkdir as Rhe}from"node:fs/promises";import{join as Pj}from"node:path";import{setTimeout as lWe}from"node:timers/promises";import{dirname as RUe,join as P4}from"node:path";function Ls(e){switch(e.kind){case"oauth":let t=e.config.application;return{family:"oauth",application:t,requiresApp:t==="required",browserAuthorization:e.config.grantType!=="client_credentials",revocable:e.config.revoke?.tokenOnly===!0,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"ovh":{let r=e.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function tV(e,t){return[...new Set([...e.required??[],...t??e.default])]}function xl(e){return Ls(e).requiresApp}var Wbe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),rV=Mt.refine(e=>Object.keys(e).every(t=>!Wbe.has(t)),"Keep method-specific facts separate from common facts."),Ms=p.object({accountId:p.string().max(2e3).nullable(),accountName:p.string().max(2e3),accountVerified:p.boolean(),scopes:p.array(p.string().max(1e3)).max(200),scopesStatus:p.enum(["unknown","requested","reported"]),authorization:rV,details:rV}).strict();function yO(e){if(e.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let t="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:e.oauth?.account??"",accountName:e.oauth?.accountName??"",accountVerified:e.oauth?.accountVerified??!1,scopes:t??e.oauth?.scopes??[],scopesStatus:t?"requested":e.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function El(e){if(e.method.kind!=="token"&&e.method.kind!=="approval"||!e.fields)throw new Error("Use input credential material.");return"facts"in e&&e.facts?Ms.parse(e.facts):Ms.parse({accountId:null,accountName:e.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function vO(e){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let t="ovh"in e?e.ovh:void 0;if(!t){let r="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return Ms.parse({accountId:t.user?t.account+"/"+t.user:t.account,accountName:t.account+(t.user?" / "+t.user:""),accountVerified:!0,scopes:t.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:t},details:{ovh:t}})}function SO(e){if(e.method.kind!=="aws"||!e.aws)throw new Error("Use AWS connection material.");return Ms.parse({accountId:e.aws.identity?dl(e.aws.identity.arn):null,accountName:e.aws.identity?e.aws.identity.accountId+" / "+e.aws.identity.arn.split(":").at(-1):"",accountVerified:!!e.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:fq(e.aws)},details:{aws:mq(e.aws)}})}var Jbe={oauth:yO,token:El,aws:SO,ovh:vO,approval:El};function $f(e){return Jbe[e.method.kind](e)}var FV=lt(EV(),1);var Ho=class extends Error{template;position;hint;constructor(e,t,r,i){super(`${i} (at position ${t}): ${r}`),this.template=e,this.position=t,this.hint=r,this.name="TemplateParseError"}},w_e=class extends Ho{constructor(e,t){super(e,t,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},b_e=class extends Ho{constructor(e,t){super(e,t,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},__e=class extends Ho{constructor(e,t){super(e,t,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},x_e=class extends Ho{char;constructor(e,t,r){super(e,t,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},E_e=class extends Ho{constructor(e,t){super(e,t,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},A_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},R_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},ow=class extends Ho{varSpec;constructor(e,t,r,i,n){super(e,t,r,i),this.varSpec=n,this.name="InvalidVarSpecError"}},$O=class extends ow{constructor(e,t){super(e,t,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},I_e=class extends ow{offendingChar;constructor(e,t,r,i){super(e,t,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${i}' or pct-encode it.`,`Invalid character '${i}' in varname`,r),this.offendingChar=i,this.name="InvalidVarNameError"}},$_e=class extends ow{prefix;constructor(e,t,r,i){super(e,t,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${i}'`,r),this.prefix=i,this.name="InvalidPrefixError"}},AV=class extends ow{constructor(e,t){super(e,t,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},P_e=class extends Ho{char;constructor(e,t,r){super(e,t,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},T_e=class extends Error{variableName;hint;constructor(e,t,r){super(`${r} for '${e}': ${t}`),this.variableName=e,this.hint=t,this.name="TemplateExpansionError"}},C_e=class extends T_e{prefix;valueType;constructor(e,t,r){super(e,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${t}' is not applicable to ${r} values`),this.prefix=t,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},k_e=["","+",".","/",";","?","&","#"],kV={"":{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}},D_e=new TextEncoder,RV="0123456789ABCDEF",IV=e=>Fs(wr(48,57),wr(65,70),wr(97,102))(e.charCodeAt(0)),kf=(e,t)=>e[t]==="%"&&t+2<e.length&&IV(e[t+1])&&IV(e[t+2]);function PO(e,t){let r=e[t];return r==null?0:Fs(DV,OV,Pc("_"))(r)?1:kf(e,t)?3:0}function O_e(e,t){if(kf(e,t))return 3;let{char:r,size:i}=Df(e,t);return U_e(r)?i:0}function Df(e,t){let r=e.codePointAt(t);if(r==null)return{char:"",size:0};let i=r>65535?2:1;return{char:e.slice(t,t+i),size:i}}var DO=e=>t=>{let r="";for(let i=0;i<t.length;){if(e&&kf(t,i)){r+=t.slice(i,i+3),i+=3;continue}let{char:n,size:o}=Df(t,i);r+=Fs(NV,s=>e&&N_e(s))(n)?n:UV(n),i+=o}return r};function Il(e){let t="";for(let r=0;r<e.length;){if(kf(e,r)){t+=e.slice(r,r+3),r+=3;continue}let{char:i,size:n}=Df(e,r);t+=NV(i)?i:UV(i),r+=n}return t}function Tf(e,t){let r="",i=0;for(let n=0;n<e.length&&i<t;i++){if(kf(e,n)){r+=e.slice(n,n+3),n+=3;continue}let{char:o,size:s}=Df(e,n);r+=o,n+=s}return r}var DV=e=>Fs(wr(65,90),wr(97,122))(e.charCodeAt(0)),OV=e=>wr(48,57)(e.charCodeAt(0)),NV=e=>Fs(DV,OV,t=>"-._~".includes(t))(e),N_e=e=>":/?#[]@!$&'()*+,;=".includes(e),U_e=e=>L_e(e.codePointAt(0)),L_e=e=>e!=null&&Fs(Pc(33),wr(35,36),Pc(38),wr(40,59),Pc(61),wr(63,91),Pc(93),Pc(95),wr(97,122),Pc(126),M_e,z_e)(e);function M_e(e){if(e<65536)return Fs(wr(160,55295),wr(63744,64975),wr(65008,65519))(e);if(e>983037)return!1;let t=e%65536;return t<=65533&&(e<917504||t>=4096)}var z_e=e=>Fs(wr(57344,63743),wr(983040,1048573),wr(1048576,1114109))(e),UV=e=>Array.from(D_e.encode(e)).map(t=>`%${RV[t>>4]}${RV[t&15]}`).join(""),wr=(e,t)=>r=>e<=r&&r<=t,Pc=e=>t=>e===t,Fs=(...e)=>t=>e.some(r=>r(t));function LV(e,t,r){return e.map(i=>i.kind==="literal"?i.text:j_e(i.vars,i.operator,t,r)).join("")}function j_e(e,t,r,i){let n=kV[t],o=e.flatMap(s=>F_e(s,r[s.name],n,i));return o.length<1?"":`${n.first}${o.join(n.sep)}`}function F_e(e,t,r,i){if(t==null)return[];if(J_e(t)){let n=K_e(t,r.allowReserved);return n.length<1?[]:$V(e,"list",i)?q_e(e,n,r):[]}if(W_e(t)){let n=B_e(t,r.allowReserved);return n.length<1?[]:$V(e,"associative",i)?V_e(e,n,r):[]}return G_e(e,t,r)}function G_e(e,t,r){let i=String(t),n=e.prefix==null?i:Tf(i,e.prefix),o=DO(r.allowReserved)(n);return r.named?[Cf(Il(e.name),o,r)]:[o]}function q_e(e,t,r){let i=Il(e.name);if(e.explode)return r.named?t.map(o=>Cf(i,o,r)):[...t];let n=t.join(",");return r.named?[Cf(i,n,r)]:[n]}function V_e(e,t,r){if(e.explode)return t.map(([n,o])=>Cf(n,o,r));let i=t.flat(1).join(",");return r.named?[Cf(Il(e.name),i,r)]:[i]}var Cf=(e,t,r)=>t===""?`${e}${r.ifEmpty}`:`${e}=${t}`,K_e=(e,t)=>e.filter(r=>r!=null).map(String).map(DO(t)),B_e=(e,t)=>Object.entries(e).map(([r,i])=>[r,H_e(i)]).filter(([,r])=>r!=null).map(r=>r.map(DO(t)));function H_e(e){if(e==null)return null;if(!Array.isArray(e))return String(e);let t=e.filter(r=>r!=null).map(String);return t.length<1?null:t.join(",")}var W_e=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),J_e=e=>Array.isArray(e);function $V(e,t,{report:r,strict:i}){if(e.prefix==null)return!0;let n=new C_e(e.name,e.prefix,t);if(r(n),i)throw n;return!1}function Z_e(e,t,r){return TO(e,t,r,0,0,{})}function TO(e,t,r,i,n,o){if(i>=e.length){if(n!==t.length)return null;let a=xxe(o);return LV(e,a,r)===t?a:null}let s=e[i];if(s.kind==="literal")return t.startsWith(s.text,n)?TO(e,t,r,i+1,n+s.text.length,o):null;for(let a of X_e(e,t,i,n)){let c=t.slice(n,a);for(let u of Q_e(s.vars,s.operator,c)){let l=OO(o,u);if(l==null)continue;let d=TO(e,t,r,i+1,a,l);if(d!=null)return d}}return null}function*X_e(e,t,r,i){let n=e.slice(r+1).find(o=>o.kind==="literal"&&o.text!=="");if(n==null||n.kind!=="literal"){yield*Y_e(t.length,i);return}for(let o=t.indexOf(n.text,i);o>=0;o=t.indexOf(n.text,o+1))yield o}function*Y_e(e,t){for(let r=e;r>=t;r--)yield r}function*Q_e(e,t,r){if(r===""){yield*exe(e,t);return}let i=kV[t];if(!r.startsWith(i.first))return;let n=r.slice(i.first.length);yield*i.named?uxe(e,i,n):txe(e,i,n)}var exe=(e,t)=>(t===""||t==="+")&&e.length===1?[js(e[0],"")]:[{}],txe=(e,t,r)=>CO(e,t,NO(r,t.sep),0,0);function*CO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of rxe(o,t,r,n))for(let a of CO(e,t,r,i+1,s.index)){let c=OO(s.bindings,a);c!=null&&(yield c)}yield*CO(e,t,r,i+1,n)}function*rxe(e,t,r,i){if(i>=r.length)return;let n=r.length-i;for(let o=1;o<=n;o++){let s=r.slice(i,i+o);for(let a of nxe(e,t,s))yield{bindings:a,index:i+o}}}function*nxe(e,t,r){let i=MV(e,t,r.join(t.sep));if(e.prefix!=null){yield*i;return}e.explode&&r.length>0&&(yield*ixe(e,t,r)),yield*i}function*ixe(e,t,r){let i=zV(r,t.allowReserved);if(i==null)return;let n=oxe(r,t);n!=null&&(yield js(e,n)),yield js(e,i)}var oxe=(e,t)=>sxe(e.join(t.sep),t);function sxe(e,t){let r=[];for(let i=0;i<e.length;){let n=e.indexOf("=",i);if(n<0)return null;let o=n+1,s=axe(e,o,t.sep),a=Bo(e.slice(i,n),t.allowReserved),c=Bo(e.slice(o,s),t.allowReserved);if(a==null||c==null)return null;r.push([a,c]),i=s+t.sep.length}return r.length<1?null:Object.fromEntries(r)}function axe(e,t,r){for(let i=t;i<e.length;i++)if(cxe(e,i,r))return i;return e.length}var cxe=(e,t,r)=>{if(!e.startsWith(r,t))return!1;let i=t+r.length;for(let n=i;n<e.length;n++){if(e[n]==="=")return n>i;if(e.startsWith(r,n))return!1}return!1};function*MV(e,t,r){let i=Bo(r,t.allowReserved);if(i==null)return;let n=js(e,i);if(e.prefix!=null){yield n;return}let o=NO(r,",");if(o.length<2){yield n;return}let s=zV(o,t.allowReserved);if(s==null){yield n;return}let a=o.length%2===0?vxe(o,t.allowReserved):null;a!=null&&(yield js(e,a)),yield js(e,s),yield n}var uxe=(e,t,r)=>kO(e,t,NO(r,t.sep).map(yxe),0,0);function*kO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of lxe(o,t,r,n,e))for(let a of kO(e,t,r,i+1,s.index)){let c=OO(s.bindings,a);c!=null&&(yield c)}yield*kO(e,t,r,i+1,n)}function*lxe(e,t,r,i,n){if(!(i>=r.length)){if(e.explode&&e.prefix==null){yield*pxe(e,t,r,i,n);return}yield*dxe(e,t,r,i)}}function*dxe(e,t,r,i){let n=r[i];if(n.name===Il(e.name))for(let o of MV(e,t,n.value))yield{bindings:o,index:i+1}}function*pxe(e,t,r,i,n){yield*fxe(e,t,r,i),yield*hxe(e,t,r,i,n)}function*fxe(e,t,r,i){let n=[...mxe(Il(e.name),t,r,i)];n.length>0&&(yield{bindings:js(e,n),index:i+n.length})}function*mxe(e,t,r,i){for(let n=i;n<r.length&&r[n].name===e;n++){let o=Bo(r[n].value,t.allowReserved);if(o==null)return;yield o}}function*hxe(e,t,r,i,n){let o=[...gxe(t,r,i,new Set(n.map(s=>Il(s.name))))];o.length>0&&(yield{bindings:js(e,Object.fromEntries(o)),index:i+o.length})}function*gxe(e,t,r,i){for(let n=r;n<t.length;n++){let o=t[n];if(n>r&&i.has(o.name))return;let s=Bo(o.name,e.allowReserved),a=Bo(o.value,e.allowReserved);if(s==null||a==null)return;yield[s,a]}}function yxe(e){let t=e.indexOf("=");return t<0?{name:e,value:""}:{name:e.slice(0,t),value:e.slice(t+1)}}function vxe(e,t){let r=[];for(let i=0;i<e.length;i+=2){let n=Bo(e[i],t),o=Bo(e[i+1],t);if(n==null||o==null)return null;r.push([n,o])}return Object.fromEntries(r)}function zV(e,t){let r=[];for(let i of e){let n=Bo(i,t);if(n==null)return null;r.push(n)}return r}function Bo(e,t){if(t)return e;try{return decodeURIComponent(e)}catch{return null}}var js=({name:e,prefix:t},r)=>({[e]:{value:r,prefix:t}});function OO(e,t){let r={...e};for(let[i,n]of Object.entries(t)){let o=r[i];if(o==null){r[i]=n;continue}let s=Sxe(o,n);if(s==null)return null;r[i]=s}return r}var Sxe=(e,t)=>iw(e)||iw(t)?wxe(e,t):bxe(e.value,t.value)?e:null;function wxe(e,t){let r=PV(e.value),i=PV(t.value);if(r==null||i==null)return null;let n=iw(e),o=iw(t);if(!n&&!o)return null;if(n&&!o)return Tf(i,e.prefix)===r?t:null;if(!n&&o)return Tf(r,t.prefix)===i?e:null;let s=e.prefix,a=t.prefix;return s<=a?Tf(i,s)===r?t:null:Tf(r,a)===i?e:null}var iw=e=>e.prefix!=null,PV=e=>typeof e=="string"?e:null;function bxe(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,i)=>r===t[i]):TV(e)?TV(t)&&_xe(Object.entries(e),Object.entries(t)):e===t}var _xe=(e,t)=>e.length===t.length&&e.every(([r,i],n)=>{let[o,s]=t[n];return r===o&&i===s}),TV=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xxe=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value])),NO=(e,t)=>t===""?[e]:e.split(t),Exe=["=",",","!","@","|"];function Axe(e,t,r){let i=a=>{throw a};if(e.length<1)return i(new E_e(t,r));let n=e[0];if(Pxe(n))return i(new A_e(t,r+1,n));if(!CV(n)&&PO(e,0)<1)return i(new R_e(t,r+1,n));let o=CV(n)?n:"",s=o===""?0:1;return{kind:"expression",operator:o,vars:Rxe(e,t,r+1,s)}}function Rxe(e,t,r,i){if(i>=e.length)throw new $O(t,r+i);let n=[];for(let o=i;o<e.length;){if(e[o]===",")throw o===e.length-1?new AV(t,r+o):new $O(t,r+o);let s=o,a=Ixe(e,o);if(a===s)throw new $O(t,r+o);let c=e.slice(s,a);o=a;let u=$xe(e,t,r,o,c);if(o=u.index,o<e.length&&e[o]!==",")throw u.used?new P_e(t,r+o,e[o]):new I_e(t,r+o,c,e[o]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),o<e.length&&(o++,o>=e.length))throw new AV(t,r+o-1)}return n}function Ixe(e,t){let r=t,i=!0;for(;r<e.length;){let n=PO(e,r);if(n>0){r+=n,i=!1;continue}if(e[r]!=="."||i||PO(e,r+1)<1)break;r++,i=!0}return r}function $xe(e,t,r,i,n){if(e[i]==="*")return{explode:!0,index:i+1,used:!0};if(e[i]!==":")return{explode:!1,index:i,used:!1};let o=i+1,s=o;for(;s<e.length&&Txe(e[s]);)s++;let a=e.slice(o,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new $_e(t,r+i,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function CV(e){return k_e.includes(e)&&e!==""}function Pxe(e){return Exe.includes(e)}function Txe(e){let t=e.charCodeAt(0);return t>=48&&t<=57}function Cxe(e,t){let{report:r}=t,i=[],n=o=>{let s=i.at(-1);s?.kind==="literal"?i[i.length-1]={kind:"literal",text:s.text+o}:i.push({kind:"literal",text:o})};for(let o=0;o<e.length;){let s=e[o];if(s==="{"){let l=e.indexOf("}",o+1);if(l<0){r(new w_e(e,o)),n(e.slice(o));break}let d=e.indexOf("{",o+1);if(d>=0&&d<l){r(new __e(e,d)),n(e.slice(o,l+1)),o=l+1;continue}let m=e.slice(o+1,l);try{i.push(Axe(m,e,o))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(e.slice(o,l+1))}o=l+1;continue}if(s==="}"){r(new b_e(e,o)),n(s),o++;continue}let a=O_e(e,o);if(a>0){n(e.slice(o,o+a)),o+=a;continue}let{char:c,size:u}=Df(e,o);r(new x_e(e,o,c)),n(c),o+=u}return i}var sw=class jV{uriTemplate;options;#e;#t;constructor(t,r={}){this.uriTemplate=t,this.options=r,this.#t=Uxe(r),this.#e=kxe(Cxe(t,this.#t)),Object.freeze(this)}static parse(t,r={}){return new jV(t,r)}get tokens(){return this.#e}expand=t=>LV(this.#e,t,this.#t);match=t=>Z_e(this.#e,t,this.#t);toString=()=>this.uriTemplate},kxe=e=>Object.freeze(e.map(Dxe)),Dxe=e=>e.kind==="literal"?Object.freeze({kind:"literal",text:e.text}):Object.freeze({kind:"expression",operator:e.operator,vars:Object.freeze(e.vars.map(Oxe))}),Oxe=e=>Object.freeze({name:e.name,explode:e.explode,...e.prefix==null?{}:{prefix:e.prefix}}),Nxe=()=>{},Uxe=({strict:e,report:t})=>(t??=Nxe,e??=!0,t=e?Lxe(t):t,{strict:e,report:t}),Lxe=e=>t=>{throw e(t),t};var Gs=class extends Error{constructor(r,i){super(i);this.code=r}code};function Mxe(e,t){return!e.when||t[e.when.field]===void 0||e.when.values.includes(t[e.when.field])}function GV(e,t,r={}){let i=(o,s)=>{throw new Gs(o,s)},n={...r,...t};for(let o of e)n[o.name]===void 0&&o.defaultValue!==void 0&&(n[o.name]=o.defaultValue);for(let o of e){if(!Mxe(o,n)){delete n[o.name];continue}o.required!==!1&&!n[o.name]&&i("missing_field","Complete the required service fields."),n[o.name]?.includes("\0")&&i("invalid_field","Check the service fields."),o.choices&&n[o.name]&&!o.choices.some(s=>s.value===n[o.name])&&i("invalid_field","Choose an available service setting."),o.pattern&&(o.pattern.length>200||!(0,FV.default)(o.pattern))&&i("invalid_pattern","Use a simple field validation pattern."),o.pattern&&n[o.name]&&!new RegExp(o.pattern,"u").test(n[o.name].slice(0,1e3))&&i("invalid_field","Check the service fields.")}return Object.keys(t).some(o=>!e.some(s=>s.name===o))&&i("invalid_field","Remove unrecognized service fields."),n}function qs(e,t,r={}){let i=GV(e,t,r),n={};for(let o of e){let s=o.choices?.find(a=>a.value===i[o.name]);for(let[a,c]of Object.entries(s?.values??{})){if(e.some(u=>u.name===a)||a in n&&n[a]!==c)throw new Gs("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...i,...n}}function UO(e,t){for(let[r,i]of Object.entries(t)){let n=e.find(o=>o.name===r);if(!n)throw new Gs("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&i!=="")throw new Gs("encrypted_input_required","Supply private material directly with your encryption keys.")}return GV(e.map(r=>({...r,required:!1,defaultValue:void 0})),t)}function $l(e,t){return UO(e,Object.fromEntries(e.filter(r=>r.secret===!1&&t[r.name]).map(r=>[r.name,t[r.name]])))}function qV(e,t=$f(e)){return t.accountVerified?t.accountId:null}function VV(e,t=$f(e)){let i=(e.method.kind==="oauth"||e.method.kind==="ovh"||e.method.kind==="token"&&!!(e.method.config.identity||e.method.config.resolver||e.method.config.bindFields))&&e.method.kind!=="aws"?$l(e.method.config.fields,e.fields??{}):{};return{format:e.format,generation:e.generation,methodId:e.methodId,method:e.method,appId:e.appId,appGeneration:e.appGeneration,..."implicitApp"in e&&e.implicitApp?{implicitApp:{clientId:e.implicitApp.clientId,generation:e.implicitApp.generation,fields:e.implicitApp.fields}}:{},account:t.accountId,accountVerified:t.accountVerified,scopes:[...t.scopes].sort(),...Object.keys(i).length?{fields:i}:{},...t.authorization,...e.state?{state:e.state}:{}}}var Vs=p.record(p.string().max(100),p.string().max(16384)),aw=p.object({format:p.literal(1),methodId:p.string().min(1),generation:P,clientId:p.string().max(1e3),clientSecret:p.string().max(16384).optional(),fields:Vs}).strict(),LO=p.object({accessToken:p.string().min(1).max(16384),refreshToken:p.string().min(1).max(16384).optional(),expiresAt:p.number().nullable(),refreshExpiresAt:p.number().optional(),scopes:p.array(p.string()),requestedScopes:p.array(p.string()).optional(),account:p.string(),accountName:p.string(),accountVerified:p.boolean().optional(),scopesStatus:p.enum(["unknown","requested","reported"]).optional(),extra:Vs,facts:Mt}).strict(),Of={format:p.literal(2),methodId:p.string().min(1),method:fl,generation:P,appId:P.nullable(),appGeneration:P.nullable(),state:p.literal("reconnect").optional()},Wo=p.never().optional(),Pl=p.union([p.object({...Of,method:$S,oauth:LO.optional(),requestedScopes:p.array(p.string()).optional(),implicitApp:aw.optional(),fields:Vs.optional(),aws:Wo}).strict(),p.object({...Of,method:PS,fields:Vs,facts:Ms.optional(),oauth:Wo,aws:Wo}).strict(),p.object({...Of,method:kS,fields:Vs,oauth:Wo,aws:Wo}).strict(),p.object({...Of,method:CS,fields:Vs,ovh:gf.optional(),requestedScopes:p.array(p.string()).optional(),oauth:Wo,aws:Wo}).strict(),p.object({...Of,method:TS,aws:wS,oauth:Wo,fields:Wo}).strict()]).superRefine((e,t)=>{if("implicitApp"in e&&e.implicitApp&&(e.method.kind!=="oauth"||e.method.config.application!=="implicit"||e.implicitApp.methodId!==e.methodId)&&t.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),e.method.kind==="oauth"&&e.fields)try{UO(e.method.config.fields,e.fields)}catch{t.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}xl(e.method)&&(!e.appId||!e.appGeneration)&&t.addIssue({code:"custom",message:"Bind the application required by this connection."}),!xl(e.method)&&e.appId!==null&&t.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!e.appId!=!!e.appGeneration&&t.addIssue({code:"custom",message:"Bind the application and its generation together."}),e.method.kind==="oauth"&&e.method.config.grantType==="client_credentials"&&!("requestedScopes"in e&&e.requestedScopes)&&!e.oauth?.requestedScopes&&t.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),jYe=p.object({methodId:p.string().min(1).max(200),clientId:p.string().max(1e3),generation:P,fields:Vs.optional()}).strict(),zxe=p.object({methodId:p.string().min(1).max(200),methodKind:YD,http:IS.optional(),generation:P,authorizationDigest:yt,appId:P.nullable(),accountId:p.string().max(2e3).nullable(),accountVerified:p.boolean(),scopes:p.array(p.string().max(1e3)).max(200),scopesStatus:p.enum(["unknown","requested","reported"]),outputs:p.array(p.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:p.enum(["ready","reconnect"]),revocable:p.literal(!0).optional(),fields:Vs.optional(),aws:bS.optional(),ovh:gf.optional()}).strict();async function KV(e,t=$f(e)){let{outputs:r,revocable:i}=Ls(e.method),n=e.method.kind!=="aws"&&e.fields?$l(e.method.config.fields,e.fields):{},o=await te(VV(e,t));return zxe.parse({methodId:e.methodId,methodKind:e.method.kind,...e.method.http?{http:e.method.http}:{},generation:e.generation,authorizationDigest:o,appId:e.appId,accountId:qV(e,t),accountVerified:t.accountVerified,scopes:t.scopes,scopesStatus:t.scopesStatus,outputs:r,state:e.state??"ready",...i?{revocable:i}:{},...Object.keys(n).length?{fields:n}:{},...t.details})}var jxe=p.array(p.object({name:p.string(),label:p.string(),value:p.string()}).strict()),BV=p.object({methodName:be,account:p.string().max(2e3),settings:jxe.optional()}).strict();var MO=p.discriminatedUnion("action",[p.object({action:p.literal("refresh"),id:P}).strict(),p.object({action:p.literal("revoke"),id:P}).strict()]);var zO=gl.extend({name:be}),JYe=gl.extend({previousSignature:_t.optional()}).strict(),ZYe=p.object({name:be,content:ir,labels:BV.optional(),version:p.number().int().positive().optional()}).strict(),jO=p.object({content:ir,version:p.number().int().positive()}).strict(),HV=p.object({id:P,reason:p.enum(["grantExpired","recipients"]),remove:p.array(P).max(1e3).default([])}).strict(),XYe=p.record(P,p.object({version:p.number().int().positive(),content:ir}).strict()),WV=p.object({id:P,name:be,version:p.number().int().positive(),content:ir,policy:qo}).strict(),JV=p.object({registration:cO,stoppedAt:p.iso.datetime().nullable(),heartbeatAt:p.iso.datetime().nullable()}).strict(),ZV=p.object({lease:P,request:qS,sources:p.array(ir).max(100)}).strict().nullable(),Fxe=p.object({lease:P}).strict(),YYe=Fxe.extend({receipt:If}).strict(),Nf=p.object({id:P,resource_id:P,executor_id:P,expected_revision:p.number().int().positive(),state:p.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:p.string().regex(/^\d+$/),result:ir.nullable()}),QYe=p.object({id:P,resourceId:P,expectedRevision:p.number().int().positive()}).strict(),Gxe=p.object({fence:p.string().regex(/^\d+$/)}).strict(),eQe=Gxe.extend({content:ir}).strict(),tQe=p.object({id:P,executionId:P,index:p.number().int().nonnegative(),stateDigest:yt,expiresAt:ce}).strict(),rQe=p.object({id:P,executionId:P,context:p.string(),sealed:jo.nullable(),expiresAt:ce,receivedAt:ce.nullable()}).strict();var qxe=p.object({binding:vt,verifiedAt:ce}).strict(),FO=p.object({origin:p.url(),ownerId:P,signerId:P,revision:p.number().int().positive(),keys:p.array(qxe).max(1e3)}).strict(),Vxe=p.object({version:p.number().int().positive(),signature:_t}).strict(),GO=p.object({keyring:Vxe.nullable()}).strict(),cQe=p.object({version:p.number().int().positive().nullable(),signature:_t}).strict();function XV(e,t){return Tt(FO.parse(e),t,"keyring")}function YV(e){return FO.parse(JSON.parse(NS(Iq(e.split(".")[1]??""))))}async function QV(e,t){let r=FO.parse(await bf(e,t.signing,"keyring"));if(r.signerId!==t.id)throw new Error("Another identity signed this keyring.");return r}var Tl=lt(t3(),1);var Me=class extends Error{constructor(r,i,n,o){super(n);this.status=r;this.code=i;this.details=o}status;code;details};function M(e,t,r,i){throw new Me(e,t,r,i)}var Kxe=Tl.default.IPv6.parseCIDR("2000::/3"),Bxe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function uw(e){if(!Tl.default.isValid(e)||e.includes("%"))return!1;let t=Tl.default.parse(e);return Bxe.has(t.range())&&(!(t instanceof Tl.default.IPv6)||t.match(Kxe))}function Pn(e,t){let r;try{r=new URL(e)}catch{M(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===t)&&M(400,"invalid_url","Choose a public HTTPS destination.");let i=r.hostname.replace(/^\[|\]$/g,"");return(i==="localhost"||i.endsWith(".localhost")||i.endsWith(".local")||Tl.default.isValid(i)&&!uw(i))&&M(400,"private_destination","Choose a public HTTPS destination."),r}function Cl(e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.body))}catch{M(502,"invalid_response","The service returned an invalid response.")}return(!t||typeof t!="object"||Array.isArray(t))&&M(502,"invalid_response","The service returned an invalid response."),t}function Uf(e){return[...e.connectionId?[{id:e.connectionId}]:[],...e.bindings.flatMap(t=>t.parts.filter(r=>typeof r!="string"))]}function qO(e,t,r){e.method.http||M(400,"invalid_http_connection","This connection does not provide HTTP authentication.");let i=e.method.http.urlField,n=i&&e.fields?.[i];i&&!n&&M(409,"reconnect_required","Reconnect with a destination URL.");let o=Pn(t.url??n??"",r);return n&&o.origin!==Pn(n,r).origin&&M(400,"invalid_destination","Use this connection only at its configured destination host."),o.href}function r3(e,t,r,i){let n=new URL(e),o={...t},s=[];Object.keys(t).some(l=>["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase()))&&M(400,"invalid_authentication","Use HTTP headers that do not override routing or transport settings.");let a=(l,d=!0)=>{Object.hasOwn(i,l)||M(400,"invalid_authentication","Choose an available authentication output.");let m=i[l];return d&&s.push(m),m},c=(l,d)=>{(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(l)||["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase())||/[\r\n\0]/.test(d))&&M(400,"invalid_authentication","Use a valid authentication header."),Object.keys(o).some(m=>m.toLowerCase()===l.toLowerCase())&&M(400,"invalid_authentication","Let the selected connection supply its authentication header."),o[l]=d,s.push(d)},u=r.authentication;if(u.kind==="bearer")c("Authorization","Bearer "+a(u.token));else if(u.kind==="basic"){let l=a(u.username),d=a(u.password);l.includes(":")&&M(400,"invalid_authentication","A Basic authentication username cannot contain a colon.");let m=new TextEncoder().encode(l+":"+d),f=btoa(Array.from(m,g=>String.fromCharCode(g)).join(""));c("Authorization","Basic "+f),s.push(f)}else if(u.kind==="header"||u.kind==="query"){let l=typeof u.name=="string"?u.name:a(u.name.output,!1),d=a(u.value);u.kind==="header"?c(l,d):((!l||/[\r\n\0]/.test(l)||n.searchParams.has(l))&&M(400,"invalid_authentication","Let the selected connection supply its authentication query parameter."),n.searchParams.set(l,d))}return s.push(n.href),{url:n.href,headers:o,sensitive:s}}var sn=class extends Error{constructor(r,i){super(i);this.code=r}code},KO=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},VO=(e,...t)=>!!e&&typeof e=="object"&&("code"in e&&t.includes(String(e.code))||"status"in e&&t.includes(Number(e.status))),lw=class{constructor(t,r,i,n,o){this.api=t;this.origin=r;this.binding=i;this.keys=n;this.trust=o}api;origin;binding;keys;trust;verifiedKeys;async trusted(t){if(!await this.verifies(t))throw new sn("identity_untrusted","Verify and trust the encryption and signing keys for identity "+t.principalId+" before sharing.");return t}async verifies(t){if(t.principalId===this.binding.principalId)return C(this.binding)===C(t);let r=(await this.keyring()).get(t.principalId)?.binding??await this.trust.binding(t.principalId);return!!r&&C(r)===C(t)}async verifiedIdentity(t){return this.verifies((await this.inspectIdentity(t)).binding)}keyring(){return this.verifiedKeys??=this.loadKeyring().catch(t=>{throw this.verifiedKeys=void 0,t})}async loadKeyring(){let t;try{t=(await this.readKeyring()).keyring?.keys??[]}catch(o){if(VO(o,401,403))return new Map;throw o}let r=new Set(t.map(o=>o.binding.principalId)),i=new Date().toISOString(),n=(await this.trust.bindings()).filter(o=>o.principalId!==this.binding.principalId&&!r.has(o.principalId));if(n.length)try{t=(await this.changeKeyring(o=>[...o,...n.filter(s=>!o.some(a=>a.binding.principalId===s.principalId)).map(s=>({binding:s,verifiedAt:i}))])).keys}catch(o){if(o instanceof sn)throw o}return new Map(t.map(o=>[o.binding.principalId,o]))}async readKeyring(){let t="/api/principals/"+this.binding.principalId+"/keyring",{keyring:r}=await this.api.json(t,{},GO),i=await this.trust.keyring(),n=()=>new sn("keyring_conflict","The list of verified public keys does not match what this device saw before.");if(!r){if(i)throw n();return{version:null,revision:0,keyring:null}}let o=YV(r.signature);if(o.signerId!==this.binding.id)return{version:r.version,revision:o.revision,keyring:null};let s=await QV(r.signature,this.binding).catch(()=>{throw n()}),a=await te(s);if(s.ownerId!==this.binding.principalId||s.origin!==this.origin||i&&(s.revision<i.revision||s.revision===i.revision&&a!==i.digest))throw n();return(!i||s.revision>i.revision)&&await this.trust.rememberKeyring({revision:s.revision,digest:a}),{version:r.version,revision:s.revision,keyring:s}}async changeKeyring(t){for(let r=1;;r++){let i=await this.readKeyring(),n={origin:this.origin,ownerId:this.binding.principalId,signerId:this.binding.id,revision:i.revision+1,keys:t(i.keyring?.keys??[])};try{await this.api.json("/api/principals/"+this.binding.principalId+"/keyring",{method:"PUT",body:{version:i.version,signature:await XV(n,this.keys.signing)}},GO)}catch(o){if(r<3&&VO(o,"changed"))continue;throw o}return await this.trust.rememberKeyring({revision:n.revision,digest:await te(n)}),n}}async inspectIdentity(t){let r=await this.api.json("/api/identities/"+P.parse(t)+"/binding",{},gl);return await LS(r),{...r,fingerprint:await US(r.binding)}}async trustIdentity(t,r){let i=await this.inspectIdentity(t);if(i.fingerprint!==r)throw new sn("fingerprint_mismatch","The identity fingerprint does not match.");if(t===this.binding.principalId||C((await this.keyring()).get(t)?.binding??null)===C(i.binding))return i;let n=new Date().toISOString();try{let o=await this.changeKeyring(s=>[...s.filter(a=>a.binding.principalId!==t),{binding:i.binding,verifiedAt:n}]);this.verifiedKeys=Promise.resolve(new Map(o.keys.map(s=>[s.binding.principalId,s])))}catch(o){if(!VO(o,401,403))throw o;await this.trust.rememberBinding(i.binding)}return i}async environment(t,r=!0){let{registration:i,stoppedAt:n}=await this.api.json("/api/environments/"+P.parse(t)+"/registration",{},JV);if(await wl(i),i.manifest.origin!==this.origin||i.manifest.id!==t||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(i.manifest.executor),i}async recipients(t){let{items:r}=await this.api.json("/api/principals/"+P.parse(t)+"/bound-recipients",{},hl(zO));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...s}of r)await LS(s),await this.trusted(s.binding);let i=await this.api.json("/api/principals/"+P.parse(t)+"/bound-agents",{},hl(zO)),n=[];for(let{name:o,...s}of i.items){await LS(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof sn&&a.code==="identity_untrusted"))throw a}}return[...r.map(o=>o.binding),...n]}async read(t){let r=await this.api.json("/api/custody/"+P.parse(t),{},jO);return await this.observe(r.content,t),r}async observe(t,r=t.policy.id){let i=await on(t);if(i.policy.id!==r||i.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=oO(i);await this.trusted(n);let o=await this.trust.checkpoint(i);if(o&&qo.parse(o.policy),o){if(i.policy.revision<o.policy.revision||i.materialRevision<o.materialRevision||i.policy.revision===o.policy.revision&&C(i.policy)!==C(o.policy)||i.materialRevision===o.materialRevision&&await te(i)!==o.digest)throw new sn("content_conflict","The encrypted content is older than this device has already observed.");if(i.policy.revision>o.policy.revision&&!MS(o.policy,i))throw new sn("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(i),i}async reveal(t){return Rf((await this.read(t)).content,this.binding,this.keys.encryption)}async sharing(t){let r=typeof t=="string"?(await this.api.json(t,{},hl(WV))).items:t,i={};for(let n of r){let o=await this.read(n.id);if(o.version!==n.version||C(o.content)!==C(n.content))throw new sn("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);i[n.id]={version:n.version,content:await Ef(await Rf(o.content,this.binding,this.keys.encryption),n.policy,o.content.materialRevision+1,this.binding,this.keys,o.content.metadata,o.content)}}return i}async policy(t,r,i=[],n={}){let o=n.previous?.readers??[...new Map([...await this.recipients(t),this.binding].map(c=>[c.id,c])).values()];if(!o.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Go(c)):[];for(let c of i)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...rO(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return qo.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:t,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??o,readers:o,grants:a,producers:[]})}async save(t,r,i,n={}){let o=n.previous;o&&C(i)===C({...o.content.policy,revision:i.revision})&&(i={...i,revision:o.content.policy.revision});let s=await Ef(r,i,(o?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,o?.content),a={name:t,content:s,...n.labels?{labels:n.labels}:{},...o?{version:o.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:a},ml);return await this.trust.rememberContent(s),c}async pass(t,r,i,n){let o=await Ef(r,i,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:{name:t,content:o,version:n.version}},p.union([ml,Oq]));return"kind"in s&&await this.trust.rememberContent(o),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},hl(HV))).items}async reprotect(t,r="grantExpired",i=[]){let n=await this.read(t),{policy:o}=n.content,s=Date.now(),a=new Set(i),c=r==="recipients"?await this.recipients(o.ownerId):[],u=_=>!a.has(_.principalId)&&!c.some(x=>x.principalId===_.principalId&&x.id!==_.id),l=o.grants.filter(_=>Go(_,s)&&u(_.executor)&&(!("actor"in _)||u(_.actor))),d=o.readers.filter(u),m=o.authorities.filter(u),f=c.filter(_=>!d.some(x=>x.id===_.id)),g={...o,revision:o.revision+1,grants:l,producers:[],readers:[...d,...f],authorities:[...m,...f.filter(_=>!m.some(x=>x.id===_.id))],...o.observers?{observers:o.observers.filter(_=>!a.has(_))}:{}},v=o.contentType!==ge.executionResult&&o.producers.some(_=>Date.parse(_.expiresAt)>s);if(C({...g,revision:o.revision})===C(o)||v)return null;let S=await Rf(n.content,this.binding,this.keys.encryption);if(o.contentType===ge.executionResult){let _=await Ef(S,g,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content);return await this.api.json("/api/custody/"+t,{method:"PUT",body:{name:"Execution result",content:_,version:n.version}},jO),await this.trust.rememberContent(_),t}let b=await this.api.json("/api/resources/"+o.id,{},ml);return this.save(b.name,S,g,{metadata:n.content.metadata,previous:n})}async reprotectPending(){let t=[],r=[];for(let i of await this.pendingProtection())try{await this.reprotect(i.id,i.reason,i.remove)&&t.push(i.id)}catch(n){r.push({id:i.id,code:n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:"failure"})}return{done:t,failed:r}}async sourceContents(t){let r=new Map;for(let i of new Set(t))r.set(i,(await this.read(i)).content);for(let i of[...r.values()])i.policy.contentType===ge.tokenSet&&typeof i.metadata.appId=="string"&&!r.has(i.metadata.appId)&&r.set(i.metadata.appId,(await this.read(i.metadata.appId)).content);return[...r.values()]}async output(t,r,i,n,o){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+t+"/resources?"+l,{},hl(ml));s=d.items.find(m=>m.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(t,ge.value);return u.producers=[{executor:n.manifest.executor,runId:i,expiresAt:o,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await FS(u,this.binding,this.keys,c)}}async prepare(t,r,i,n={}){let o=Ic.parse(i),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=o,l=u.kind==="http"?u.request:null;if(l?.connectionId&&s.manifest.httpVersion!==zi)throw new sn("http_runtime_required","Update this execution environment to use HTTP connections.");if(o.kind==="http"){let S=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(S).map(async([_,x])=>[_,await this.output(t,x,a,s,c)])));o.save=b}let d=u.kind==="command"?u.inputs.map(S=>S.source.id):l?Uf(l).map(S=>S.id):[],m=await this.sourceContents([...d,...n.sourceIds??[]]);for(let S=0;S<m.length;S++){let b=m[S],_=b.policy.contentType===ge.clientCredential,x=_&&o.kind!=="revoke"?Q.refresh:Q[o.kind],T=_||!l?.url?void 0:new URL(l.url).origin;if(b.policy.grants.some(ee=>"actor"in ee&&C(ee.actor)===C(this.binding)&&C(ee.executor)===C(s.manifest.executor)&&ee.operations.includes(x)&&vl(ee)>=Date.parse(c)&&(!T||!ee.origins.length||ee.origins.includes(T))&&(_||ee.callerProgram))||!b.policy.authorities.some(ee=>C(ee)===C(this.binding)))continue;let N=await this.read(b.policy.id),K=await this.api.json("/api/resources/"+b.policy.id,{},ml),B={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===ge.tokenSet?[Q.refresh]:[]])],origins:T?[T]:[],functionDigests:[],callerProgram:!_,expiresAt:c},de=ee=>C({...ee,expiresAt:null}),pe=N.content.policy.grants.filter(ee=>de(ee)===de(B)),qe=qo.parse({...N.content.policy,revision:N.content.policy.revision+1,grants:[...N.content.policy.grants.filter(ee=>Go(ee)&&de(ee)!==de(B)),{...B,expiresAt:new Date(Math.max(Date.parse(c),...pe.map(ee=>vl(ee)))).toISOString()}]});await this.save(K.name,await Rf(N.content,this.binding,this.keys.encryption),qe,{previous:N,metadata:N.content.metadata}),m[S]=(await this.read(b.policy.id)).content}let f=await this.policy(t,ge.executionResult,[],{id:a});f.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let g={format:2,id:a,origin:this.origin,ownerId:t,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await te(s.manifest),operation:Q[o.kind],operationDigest:await te(o),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(m.map(async S=>({id:S.policy.id,materialRevision:S.materialRevision,policyDigest:await te(S.policy),...S.policy.contentType===ge.tokenSet&&typeof S.metadata.authorizationDigest=="string"?{authorizationDigest:S.metadata.authorizationDigest}:{}}))),resultRecipients:f.readers,...s.manifest.resultVersion?{resultApproval:await FS(f,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await bl(s,g);let v=S=>S.policy.contentType===ge.clientCredential;for(let S of m)await Os(S,v(S)&&g.operation!==Q.connect&&g.operation!==Q.revoke?{...g,operation:Q.refresh}:g,v(S)?{}:{destination:l?.url,destinationPending:!!(l?.connectionId&&!l.url)});return Gq(g,o,this.keys)}async submit(t,r,i,n={}){return this.submitPrepared(await this.prepare(t,r,i,n))}async submitPrepared(t){await this.trust.rememberRun(t);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:t},Rc)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new KO(t.intent.id)}}async resume(t){let r=await this.trust.run(P.parse(t));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let i=await this.api.json("/api/runtime/runs/"+t,{},Rc);if(C(i.intent)!==C(r.intent)||i.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return i}catch(i){if(!i||typeof i!="object"||!("code"in i)||i.code!=="not_found")throw i}return this.submitPrepared(r)}async result(t){if(t.intent.origin!==this.origin||t.intent.id!==t.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(t.intent.actor);let r=await bf(t.requestSignature,t.intent.actor.signing,"run");if(C(r.intent)!==C(t.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(t.intent.executor),!(t.receipt&&"content"in t.receipt?t.receipt.content.policy.readers:t.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new sn("not_recipient","This identity is not a reader of the execution result.");return t.receipt&&"content"in t.receipt&&await this.observe(t.receipt.content,t.id),t.receipt?Jq(t.receipt,t.intent,this.binding.id,this.keys):null}async shareLegacyResult(t){if(!t.receipt||"content"in t.receipt)return t;if(C(t.intent.actor)!==C(this.binding)||C(t.intent.executor)!==C(this.binding))throw new sn("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(t);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let i=await this.policy(t.ownerId,ge.executionResult,[],{id:t.id});i.producers=[{executor:this.binding,runId:t.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await lO(t.intent,t.receipt.state,r,this.keys,await FS(i,this.binding,this.keys),t.receipt);return this.api.json("/api/runtime/runs/"+t.id+"/result",{method:"PUT",body:{receipt:n}},Rc)}};import{lstat as Hxe,mkdir as n3,readFile as Wxe,readdir as i3,rm as Jxe}from"node:fs/promises";import{join as kl}from"node:path";var dw=p.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Tc=class{constructor(t,r,i,n){this.directory=t;this.origin=r;this.binding=i;this.privateKeys=n}directory;origin;binding;privateKeys;indexing;context(t){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:dw.parse(t)})}async read(t){let r=this.context(t),i=kl(this.directory,t+".json");try{let n=await Hxe(i);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let o=p.string().max(32e6).parse(JSON.parse(await Wxe(i,"utf8"))),s=await hS(o,await An(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(NS(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await nr({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async writeEntry(t,r){let i=this.context(t),n={context:i,value:r},o=await Tt(n,this.privateKeys.signing,"journal"),s=ft(C({...n,signature:o}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new ll(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:i}).encrypt(await An(this.binding.encryption,"ECDH-ES+A256KW"));await n3(this.directory,{recursive:!0,mode:448}),await gO(kl(this.directory,t+".json"),C(a),!0)}delivery(t){return/^(run|process|invocation|refresh)_/.test(t)}delivered(t){return!!t&&typeof t=="object"&&"delivered"in t&&t.delivered===!0}async markPending(t){await n3(kl(this.directory,"pending"),{recursive:!0,mode:448}),await gO(kl(this.directory,"pending",dw.parse(t)),"",!0)}index(){return this.indexing??=(async()=>{let t="checkpoint_pending_index";if(!await this.read(t)){for(let r of await this.keys("")){if(!this.delivery(r))continue;let i=await this.read(r);i&&!this.delivered(i)&&await this.markPending(r)}await this.writeEntry(t,{version:1})}})()}async write(t,r){await this.index();let i=this.delivered(r);this.delivery(t)&&!i&&await this.markPending(t),await this.writeEntry(t,r),this.delivery(t)&&i&&await Jxe(kl(this.directory,"pending",t),{force:!0})}async pending(t){await this.index();let r;try{r=await i3(kl(this.directory,"pending"),{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)).map(i=>dw.parse(i.name))}async keys(t){let r;try{r=await i3(this.directory,{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)&&i.name.endsWith(".json")).map(i=>dw.parse(i.name.slice(0,-5)))}};var pw=class{constructor(t){this.journal=t}journal;binding(t){return this.journal.read("identity_"+t)}async bindings(){return(await Promise.all((await this.journal.keys("identity_")).map(r=>this.journal.read(r)))).filter(r=>r!==null)}async rememberBinding(t){await Mi(t),await this.journal.write("identity_"+t.principalId,t)}keyring(){return this.journal.read("checkpoint_keyring")}async rememberKeyring(t){await this.journal.write("checkpoint_keyring",t)}checkpoint(t){return this.journal.read("checkpoint_"+t.policy.format+"_"+t.policy.id)}async rememberContent(t){await this.journal.write("checkpoint_"+t.policy.format+"_"+t.policy.id,{policy:t.policy,materialRevision:t.materialRevision,digest:await te(t)})}run(t){return this.journal.read("run_"+t)}async rememberRun(t){let r=await this.run(t.intent.id);if(r&&C(r)!==C(t))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+t.intent.id,t)}};var fw=class{api;constructor(t){this.api={async json(r,i={},n){try{return await t.json(r,i,n)}catch(o){throw o instanceof Error&&"status"in o&&typeof o.status=="number"&&"code"in o&&typeof o.code=="string"?new Me(o.status,o.code,o.message):o}}}}claim(t){return this.api.json("/api/environments/"+t+"/claim",{method:"POST",body:{}},ZV)}renew(t,r){return this.api.json("/api/runtime/runs/"+t+"/renew",{method:"POST",body:{lease:r}},p.object({active:p.boolean()}))}dispatch(t,r){return this.api.json("/api/runtime/runs/"+t+"/dispatch",{method:"POST",body:{lease:r}})}finish(t,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:t,receipt:r}},Rc)}capture(t,r,i){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:t,content:r,...i?{labels:i}:{}}},p.object({id:P}))}connections(){let t=this.api;return{prepare:(r,i,n)=>t.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:i,expectedRevision:n}},Nf),dispatch:(r,i)=>t.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:i}},Nf),commit:(r,i,n)=>t.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:i,content:n}},ir),uncertain:(r,i)=>t.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:i}}),abort:(r,i)=>t.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:i}},Nf),state:r=>t.json("/api/connections/"+r+"/operation",{},Nf.nullable())}}};import{randomUUID as wUe}from"node:crypto";var cs=lt(u4(),1);import{randomUUID as mNe}from"node:crypto";function Gte(e){let t=SS.safeParse({accountId:e.Account,arn:e.Arn,principalId:e.Arn?.includes(":assumed-role/")?e.UserId?.split(":")[0]:e.UserId});return(!t.success||t.data.arn.split(":")[4]!==t.data.accountId)&&M(502,"invalid_response","The AWS account could not be verified."),t.data}function qte(e,t){return e.accountId===t.accountId&&e.principalId===t.principalId&&dl(e.arn)===dl(t.arn)}function l4(e){e&&(!Number.isFinite(e.getTime())||e.getTime()<=Date.now())&&M(409,"reconnect_required","Reconnect with current AWS credentials.")}var OE=class{async obtain(t,r,i){let n=JD.parse({authentication:t.authentication,region:t.region,...t.role?{role:t.role}:{}}),o=n.authentication,s=o.kind==="environment"?void 0:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.kind==="session"?{sessionToken:o.sessionToken,expiration:new Date(o.expiresAt)}:{}};l4(s?.expiration);let a=new cs.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...i?[i]:[]]),l=!1;try{let d=s??await a.config.credentials();l4(d.expiration),c=new cs.STSClient({region:n.region,credentials:d});let m=r?.sourceIdentity?Gte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&m&&!qte(m,r.sourceIdentity)&&M(409,"account_changed","Reconnect to approve the current AWS authentication source.");let f=d,g=m;if(n.role){l=!0;let b=(await c.send(new cs.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+mNe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&M(502,"invalid_response","AWS did not return credentials."),f={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},l4(f.expiration),r?.identity&&(c.destroy(),c=new cs.STSClient({region:n.region,credentials:f}),g=Gte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&g&&!qte(g,r.identity)&&M(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:wS.parse({...n,sourceIdentity:m,identity:g}),credentials:{AWS_ACCESS_KEY_ID:f.accessKeyId,AWS_SECRET_ACCESS_KEY:f.secretAccessKey,AWS_SESSION_TOKEN:f.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof Me)throw d;i?.aborted&&M(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&M(409,"reconnect_required","Reconnect with current AWS credentials."),l&&M(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),M(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var NE=class{constructor(t){this.aws=t}aws;facts=SO;needsRenewal(){return!1}async outputs(t,r,i){return(await this.aws.obtain(t.aws,t.aws,i)).credentials}};var d4;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(d4="oauth4webapi/v3.8.8");function GE(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var Io="ERR_INVALID_ARG_VALUE",us="ERR_INVALID_ARG_TYPE";function Ft(e,t,r){let i=new TypeError(e,{cause:r});return Object.assign(i,{code:t}),i}var Bte=Symbol(),hNe=Symbol(),gNe=Symbol(),w4=Symbol();var UE=Symbol();var yNe=new TextEncoder,vNe=new TextDecoder;function p4(e){return typeof e=="string"?yNe.encode(e):vNe.decode(e)}var f4;Uint8Array.prototype.toBase64?f4=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):f4=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let i=0;i<t.byteLength;i+=32768)r.push(String.fromCharCode.apply(null,t.subarray(i,i+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var m4;Uint8Array.fromBase64?m4=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}}:m4=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}};function h4(e){return typeof e=="string"?m4(e):f4(e)}var tp=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=ZNe,Error.captureStackTrace?.(this,this.constructor)}},Fh=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function ve(e,t,r){return new Fh(e,{code:t,cause:r})}function LE(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Hte(e){GE(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(d4&&!t.has("user-agent")&&t.set("user-agent",d4),t.has("authorization"))throw Ft('"options.headers" must not include the "authorization" header name',Io);return t}function SNe(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw Ft('"options.signal" must return or be an instance of AbortSignal',us);return t}}function ME(e,t,r,i,n){try{if(typeof e!="number"||!Number.isFinite(e))throw Ft(`${r} must be a number`,us,n);if(e>0)return;if(t){if(e!==0)throw Ft(`${r} must be a non-negative number`,Io,n);return}throw Ft(`${r} must be a positive number`,Io,n)}catch(o){throw i?ve(o.message,i,n):o}}function $r(e,t,r,i){try{if(typeof e!="string")throw Ft(`${t} must be a string`,us,i);if(e.length===0)throw Ft(`${t} must not be empty`,Io,i)}catch(n){throw r?ve(n.message,r,i):n}}function Wte(e){bNe(e,"application/json")}function wNe(e,...t){let r='"response" content-type must be ';if(t.length>2){let i=t.pop();r+=`${t.join(", ")}, or ${i}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return ve(r,YNe,e)}function bNe(e,t){if(NNe(e)!==t)throw wNe(e,t)}async function Jte(e){return $r(e,"codeVerifier"),h4(await crypto.subtle.digest("SHA-256",p4(e)))}function Zte(e){let t=e?.[hNe];return typeof t=="number"&&Number.isFinite(t)?t:0}function Xte(e){let t=e?.[gNe];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Yte(){return Math.floor(Date.now()/1e3)}function np(e){if(typeof e!="object"||e===null)throw Ft('"as" must be an object',us);$r(e.issuer,'"as.issuer"')}function ip(e){if(typeof e!="object"||e===null)throw Ft('"client" must be an object',us);$r(e.client_id,'"client.client_id"')}function Vte(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Qte(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{i.set("client_id",r.client_id),i.set("client_secret",e)}}function ere(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{let o=Vte(r.client_id),s=Vte(e),a=btoa(`${o}:${s}`);n.set("authorization",`Basic ${a}`)}}function tre(){return(e,t,r,i)=>{r.set("client_id",t.client_id)}}var _Ne=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function xNe(e,t){if(t&&e.protocol!=="https:")throw ve("only requests to HTTPS are allowed",eUe,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw ve("only HTTP and HTTPS requests are allowed",tUe,e)}function Kte(e,t,r,i){let n;if(typeof e!="string"||!(n=_Ne(e)))throw ve(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?rUe:nUe,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return xNe(n,i),n}function rre(e,t,r,i){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Kte(e.mtls_endpoint_aliases[t],t,r,i):Kte(e[t],t,r,i)}var g4=class extends Error{cause;code;error;status;error_description;response;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=JNe,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)}},Gh=class extends Error{cause;code;error;error_description;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=XNe,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)}},y4=class extends Error{cause;code;response;status;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=WNe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},zE="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",ENe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",ANe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',RNe="("+zE+")\\s*=\\s*"+ANe,INe="("+zE+")\\s*=\\s*("+zE+")",$Ne=new RegExp("^[,\\s]*("+zE+")"),PNe=new RegExp("^[,\\s]*"+RNe+"[,\\s]*(.*)"),TNe=new RegExp("^[,\\s]*"+INe+"[,\\s]*(.*)"),CNe=new RegExp("^("+ENe+")(?:$|[,\\s])(.*)");function kNe(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);let t=e.headers.get("www-authenticate");if(t===null)return;let r=[],i=t;for(;i;){let n=i.match($Ne),o=n?.[1].toLowerCase();if(!o)return;let s=i.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;i=a?a[1]:void 0;let u={},l;if(c)for(;i;){let m,f;if(n=i.match(PNe)){[,m,f,i]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[m.toLowerCase()]=f;continue}if(n=i.match(TNe)){[,m,f,i]=n,u[m.toLowerCase()]=f;continue}if(n=i.match(CNe)){if(Object.keys(u).length)break;[,l,i]=n;break}return}else i=s||void 0;let d={scheme:o,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function DNe(e){if(e.status>399&&e.status<500){Sre(e),Wte(e);try{let t=await e.clone().json();if(LE(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function nre(e,t,r){if(e.status!==t){LNe(e);let i;throw(i=await DNe(e))?(await e.body?.cancel(),new g4("server responded with an error in the response body",{cause:i,response:e})):ve(`"response" is not a conform ${r} response (unexpected HTTP status code)`,QNe,e)}}function ONe(e){if(!_4.has(e))throw Ft('"options.DPoP" is not a valid DPoPHandle',Io)}function NNe(e){return e.headers.get("content-type")?.split(";")[0]}async function ire(e,t,r,i,n,o,s){return await r(e,t,n,o),o.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[w4]||fetch)(i.href,{body:n,headers:Object.fromEntries(o.entries()),method:"POST",redirect:"manual",signal:SNe(i,s?.signal)})}async function b4(e,t,r,i,n,o){let s=rre(e,"token_endpoint",t.use_mtls_endpoint_aliases,o?.[Bte]!==!0);n.set("grant_type",i);let a=Hte(o?.headers);a.set("accept","application/json"),o?.DPoP!==void 0&&(ONe(o.DPoP),await o.DPoP.addProof(s,a,"POST"));let c=await ire(e,t,r,s,n,a,o);return o?.DPoP?.cacheNonce(c,s),c}async function ore(e,t,r,i,n){np(e),ip(t),$r(i,'"refreshToken"');let o=new URLSearchParams(n?.additionalParameters);return o.set("refresh_token",i),b4(e,t,r,"refresh_token",o,n)}var sre=new WeakMap,UNe=new WeakMap;function are(e){if(!e.id_token)return;let t=sre.get(e);if(!t)throw Ft('"ref" was already garbage collected or did not resolve from the proper sources',Io);return t}async function qE(e,t,r,i,n,o){if(np(e),ip(t),!GE(r,Response))throw Ft('"response" must be an instance of Response',us);await nre(r,200,"Token Endpoint"),Sre(r);let s=await cUe(r);if($r(s.access_token,'"response" body "access_token" property',tt,{body:s}),$r(s.token_type,'"response" body "token_type" property',tt,{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;ME(a,!0,'"response" body "expires_in" property',tt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&$r(s.refresh_token,'"response" body "refresh_token" property',tt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw ve('"response" body "scope" property must be a string',tt,{body:s});if(s.id_token!==void 0){$r(s.id_token,'"response" body "id_token" property',tt,{body:s});let a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(ME(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),i?.length&&a.push(...i);let{claims:c,jwt:u}=await qNe(e,t,s.id_token,a,n);KNe(t,c),VNe(c),UNe.set(r,u),sre.set(s,c)}if(o?.[s.token_type]!==void 0)o[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new tp("unsupported `token_type` value",{cause:{body:s}});return s}function LNe(e){let t;if(t=kNe(e))throw new y4("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function cre(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}function MNe(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"});return t}function zNe(e,t){let r=e[uUe]?.(t)??e.issuer;if(t.claims.iss!==r)throw ve('unexpected JWT "iss" (issuer) claim value',rp,{expected:r,claims:t.claims,claim:"iss"});return t}var _4=new WeakSet;function jNe(e){return _4.add(e),e}var x4=Symbol();async function ure(e,t,r,i,n,o,s){if(np(e),ip(t),!_4.has(i))throw Ft('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Io);$r(n,'"redirectUri"');let a=du(i,"code");if(!a)throw ve('no authorization code in "callbackParameters"',tt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),o!==x4&&($r(o,'"codeVerifier"'),c.set("code_verifier",o)),b4(e,t,r,"authorization_code",c,s)}var lre={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 FNe(e,t){for(let r of e)if(t.claims[r]===void 0)throw ve(`JWT "${r}" (${lre[r]}) claim missing`,tt,{claims:t.claims});return t}function GNe(e,t){if(typeof t.claims[e]!="string")throw ve(`unexpected JWT "${e}" (${lre[e]}) claim type`,tt,{claims:t.claims});return t}function qNe(e,t,r,i,n){return iUe(r,oUe.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Zte(t),Xte(t),n).then(FNe.bind(void 0,["aud","exp","iat","iss","sub",...i])).then(zNe.bind(void 0,e)).then(MNe.bind(void 0,t.client_id)).then(GNe.bind(void 0,"sub"))}function dre(e,t){if(t===FE)return t;let r=t===void 0;return r&&(t=e.default_max_age),t===void 0?FE:(ME(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function VNe(e){e.auth_time!==void 0&&ME(e.auth_time,!0,'ID Token "auth_time" (authentication time)',tt,{claims:e})}function pre(e,t,r){if(r===FE)return;let i=Yte()+Zte(e),n=Xte(e);if(t.auth_time+r<i-n)throw ve("too much time has elapsed since the last End-User authentication",S4,{claims:t,now:i,tolerance:n,claim:"auth_time"})}function fre(e,t){let r=t===jE?void 0:t;if(e.nonce!==r)throw ve('unexpected ID Token "nonce" claim value',rp,{expected:r,claims:e,claim:"nonce"})}function KNe(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw ve('ID Token "aud" (audience) claim includes additional untrusted audiences',rp,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw ve('unexpected ID Token "azp" (authorized party) claim value',rp,{expected:e.client_id,claims:t,claim:"azp"})}}var jE=Symbol(),FE=Symbol();async function mre(e,t,r,i){return typeof i?.expectedNonce=="string"||typeof i?.maxAge=="number"||i?.requireIdToken?BNe(e,t,r,i.expectedNonce,i.maxAge,i[UE],i.recognizedTokenTypes):HNe(e,t,r,i?.maxAge,i?.[UE],i?.recognizedTokenTypes)}async function BNe(e,t,r,i,n,o,s){let a=[];switch(i){case void 0:i=jE;break;case jE:break;default:$r(i,'"expectedNonce" argument'),a.push("nonce")}n=dre(t,n),n!==FE&&a.push("auth_time");let c=await qE(e,t,r,a,o,s);$r(c.id_token,'"response" body "id_token" property',tt,{body:c});let u=are(c);return pre(t,u,n),fre(u,i),c}async function HNe(e,t,r,i,n,o){let s=await qE(e,t,r,void 0,n,o),a=are(s);return a&&(pre(t,a,dre(t,i)),fre(a,jE)),s}var WNe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",JNe="OAUTH_RESPONSE_BODY_ERROR",ZNe="OAUTH_UNSUPPORTED_OPERATION",XNe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var v4="OAUTH_PARSE_ERROR",tt="OAUTH_INVALID_RESPONSE";var YNe="OAUTH_RESPONSE_IS_NOT_JSON",QNe="OAUTH_RESPONSE_IS_NOT_CONFORM",eUe="OAUTH_HTTP_REQUEST_FORBIDDEN",tUe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",S4="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",rp="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var rUe="OAUTH_MISSING_SERVER_METADATA",nUe="OAUTH_INVALID_SERVER_METADATA";async function hre(e,t,r,i,n){return np(e),ip(t),b4(e,t,r,"client_credentials",new URLSearchParams(i),n)}async function gre(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}async function yre(e,t,r,i,n){np(e),ip(t),$r(i,'"token"');let o=rre(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,n?.[Bte]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",i);let a=Hte(n?.headers);return a.delete("accept"),ire(e,t,r,o,s,a,n)}async function vre(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);await nre(e,200,"Revocation Endpoint")}function Sre(e){if(e.bodyUsed)throw Ft('"response" body has been used already',Io)}async function iUe(e,t,r,i,n){let{0:o,1:s,length:a}=e.split(".");if(a===5)if(n!==void 0)e=await n(e),{0:o,1:s,length:a}=e.split(".");else throw new tp("JWE decryption is not configured",{cause:e});if(a!==3)throw ve("Invalid JWT",tt,e);let c;try{c=JSON.parse(p4(h4(o)))}catch(d){throw ve("failed to parse JWT Header body as base64url encoded JSON",v4,d)}if(!LE(c))throw ve("JWT Header must be a top level object",tt,e);if(t(c),c.crit!==void 0)throw new tp('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(p4(h4(s)))}catch(d){throw ve("failed to parse JWT Payload body as base64url encoded JSON",v4,d)}if(!LE(u))throw ve("JWT Payload must be a top level object",tt,e);let l=Yte()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw ve('unexpected JWT "exp" (expiration time) claim type',tt,{claims:u});if(u.exp<=l-i)throw ve('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',S4,{claims:u,now:l,tolerance:i,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw ve('unexpected JWT "iat" (issued at) claim type',tt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw ve('unexpected JWT "iss" (issuer) claim type',tt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw ve('unexpected JWT "nbf" (not before) claim type',tt,{claims:u});if(u.nbf>l+i)throw ve('unexpected JWT "nbf" (not before) claim value',S4,{claims:u,now:l,tolerance:i,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw ve('unexpected JWT "aud" (audience) claim type',tt,{claims:u});return{header:c,claims:u,jwt:e}}function oUe(e,t,r,i){if(e!==void 0){if(typeof e=="string"?i.alg!==e:!e.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?i.alg!==r:typeof r=="function"?!r(i.alg):!r.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:r,reason:"default value"});return}throw ve('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function du(e,t){let{0:r,length:i}=e.getAll(t);if(i>1)throw ve(`"${t}" parameter must be provided only once`,tt);return r}var sUe=Symbol(),aUe=Symbol();function wre(e,t,r,i){if(np(e),ip(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Ft('"parameters" must be an instance of URLSearchParams, or URL',us);if(du(r,"response"))throw ve('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',tt,{parameters:r});let n=du(r,"iss"),o=du(r,"state");if(!n&&e.authorization_response_iss_parameter_supported)throw ve('response parameter "iss" (issuer) missing',tt,{parameters:r});if(n&&n!==e.issuer)throw ve('unexpected "iss" (issuer) response parameter value',tt,{expected:e.issuer,parameters:r});switch(i){case void 0:case aUe:if(o!==void 0)throw ve('unexpected "state" response parameter encountered',tt,{expected:void 0,parameters:r});break;case sUe:break;default:if($r(i,'"expectedState" argument'),o!==i)throw ve(o===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',tt,{expected:i,parameters:r})}if(du(r,"error"))throw new Gh("authorization response from the server is an error",{cause:r});let a=du(r,"id_token"),c=du(r,"token");if(a!==void 0||c!==void 0)throw new tp("implicit and hybrid flows are not supported");return jNe(new URLSearchParams(r))}async function cUe(e,t=Wte){let r;try{r=await e.json()}catch(i){throw t(e),ve('failed to parse "response" body as JSON',v4,i)}if(!LE(r))throw ve('"response" body must be a top level object',tt,{body:r});return r}var uUe=Symbol();function qh(e){if(e==="")return[];if(!e.startsWith("/")||/~(?![01])/u.test(e))throw new Error("Invalid JSON pointer.");let t=e.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(t.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return t}function Wn(e,t){for(let r of qh(t)){if(e===null||typeof e!="object"||!Object.hasOwn(e,r))return;e=e[r]}return e}function E4(e,t,r){let i=qh(t),n=i.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let o of i){if(e===null||typeof e!="object"||!Object.hasOwn(e,o))throw new Error("JSON pointer target does not exist.");e=e[o]}if(e===null||typeof e!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(e)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=e.length))throw new Error("Invalid array index.");e[n]=r}function La(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);throw new Error("The selected value is not text.")}function VE(e,t){return typeof t=="string"?La(Wn(e,t)):t.map(r=>typeof r=="string"?r:La(Wn(e,r.pointer))).join("")}function op(e,t){let r=new Set;for(let i of t)i&&(r.add(i),r.add(encodeURIComponent(i)),r.add(JSON.stringify(i).slice(1,-1)));for(let i of[...r].sort((n,o)=>o.length-n.length))e=e.split(i).join("[redacted]");return e}function A4(e,t){return btoa(Array.from(new TextEncoder().encode(e+":"+t),r=>String.fromCharCode(r)).join(""))}var bre=Object.assign(Object.create(null),{dpop:()=>M(502,"invalid_response","The service returned an unsupported token.")}),dUe={redirectUri:e=>e.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),bre,{"user access token":()=>{}})},pUe={authorize(e,t){delete e.response_type,delete e.client_id,delete e.redirect_uri,e.callback_url=t,e.key_label="Foundation"},async exchange({spec:e,transport:t,url:r,authorization:i,verifier:n}){let o=i.parameters;return(o.getAll("state").length!==1||o.get("state")!==i.state||o.getAll("code").length!==1||!o.get("code"))&&M(400,"invalid_state","Start the connection again."),t.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:o.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},fUe={revokeRequest({app:e,url:t,current:r}){return{url:t,method:"DELETE",headers:{authorization:"Basic "+A4(e.clientId,e.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},mUe={tokenParameters(e){let t=e.get("redirect_uri");t!==null&&(e.set("redirect_url",t),e.delete("redirect_uri"))}};function $o(e,t){let r=t?new URL(t):void 0;return{recognizedTokenTypes:bre,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(i){i.token_type===void 0&&(i.token_type="bearer")},...e.grantType==="client_credentials"?{clientCredentialsParameters(){return{...e.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(i){i.refresh_token===null&&delete i.refresh_token}}:{},...e.adapter==="ebay"?dUe:e.adapter==="openrouter"?pUe:e.adapter==="vultr"?mUe:{},...e.revoke?.style==="github"?fUe:{}}}function pu(e,t){try{return Pn(new sw(e).expand(t)).href}catch{M(400,"invalid_service_url","Check the service URL and its required fields.")}}var _re=(e,t=" ")=>typeof e=="string"?[...new Set(e.split(t).filter(Boolean))].sort():[],KE=e=>{let t=typeof e=="number"||typeof e=="string"?Number(e):NaN;return(!Number.isSafeInteger(t)||t<=0||t>315576e3)&&M(502,"invalid_response","The service returned an invalid expiry."),t};var BE=class{constructor(t){this.transport=t}transport;appValues(t,r){try{return{...qs(t.fields,r.fields,t.defaults),clientId:r.clientId}}catch(i){throw i instanceof Gs&&M(400,i.code,i.message),i}}async authorize(t,r,i,n,o,s){(t.grantType==="client_credentials"||!t.authorizeUrl)&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(pu(t.authorizeUrl,this.appValues(t,r))),c={...t.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:$o(t).redirectUri?.(r,o)??o,state:i};s.length&&(c.scope=s.join(t.scopes.separator)),t.pkce&&(c.code_challenge=await Jte(n),c.code_challenge_method="S256"),$o(t).authorize?.(c,o);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(t,r){let i={issuer:t.issuer??new URL(pu(t.grantType==="client_credentials"?t.tokenUrl:t.authorizeUrl,this.appValues(t,r))).origin,token_endpoint:pu(t.tokenUrl,this.appValues(t,r))};return t.issuer&&Pn(t.issuer),{server:i,client:{client_id:r.clientId}}}authentication(t,r){return r==="none"?tre():(t.clientSecret||M(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?ere(t.clientSecret):Qte(t.clientSecret))}options(t){let r=t?.tokenFormat??"form";return{[w4]:async(i,{body:n,headers:o,method:s,signal:a})=>{let c=new URLSearchParams(n);t&&$o(t).tokenParameters?.(c);let u=await this.transport.send({url:i,method:s,headers:r==="json"?{...o,"content-type":"application/json"}:o,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(t){return Cl({status:t.status,headers:{},body:new Uint8Array(await t.arrayBuffer())})}checkResponse(t,r,i,n=!1){return(r>=400||i.error||t.okPointer&&Wn(i,t.okPointer)!==!0)&&(n&&(i.error==="invalid_grant"||i.error==="invalid_token")&&M(409,"reconnect_required","Reconnect this service to renew access."),r===429&&M(503,"service_rate_limit","The service is busy. Try again later."),M(502,"authorization_failed","The service did not authorize this connection.")),i}async tokenResponse(t,r,i,n=!1){i.status===429&&M(503,"service_rate_limit","The service is busy. Try again later.");let o=this.checkResponse(t,i.status,await this.json(i),n),{server:s,client:a}=this.configuration(t,r),c=new URL(s.token_endpoint),u={...o};delete u.id_token,$o(t,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=KE(u.expires_in));try{let d=await(n?cre:t.grantType==="client_credentials"?gre:mre)(s,a,Response.json(u,{status:i.status}),{recognizedTokenTypes:$o(t,c.href).recognizedTokenTypes});return{...o,...d}}catch(l){if(l instanceof Me)throw l;M(502,"invalid_response","The service did not return a valid access token.")}}token(t,r,i,n,o=!1){let s=r[$o(t).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&M(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+KE(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&M(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of t.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?_re(r.scope,t.scopes.separator):o?n?.scopes??i:i,scopesStatus:r.scope!==void 0?"reported":o?n?.scopesStatus??"unknown":i.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()+KE(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(t,r,i,n,o,s,a,c){t.grantType==="client_credentials"&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=$o(t);if(l.exchange){let m=await l.exchange({spec:t,app:r,transport:this.transport,url:()=>pu(t.tokenUrl,this.appValues(t,r)),authorization:i,verifier:n});u=this.checkResponse(t,m.status,Cl(m))}else{let{server:m,client:f}=this.configuration(t,r),g;try{let v=wre(m,f,i.parameters,i.state);g=await ure(m,f,this.authentication(r,t.clientAuth),v,l.redirectUri?.(r,o)??o,t.pkce?n:x4,{...this.options(t),additionalParameters:t.tokenParams})}catch(v){throw(v instanceof Fh||v instanceof Gh)&&M(400,"invalid_state","Start the connection again."),v}u=await this.tokenResponse(t,r,g)}let d=this.token(t,u,s,a);return await c?.(d,u),d}async clientCredentials(t,r,i,n,o){t.grantType!=="client_credentials"&&M(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(t,r),c=$o(t,s.token_endpoint),u={...t.tokenParams,...i.length?{scope:i.join(t.scopes.separator)}:{}},l=await hre(s,a,this.authentication(r,t.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(t)),d=await this.tokenResponse(t,r,l),m={...this.token(t,d,i,n,!!n),requestedScopes:i};return await o?.(m,d),m}async refresh(t,r,i,n){let o=i;if(i.expiresAt!==null&&i.expiresAt<Date.now()+6e4){if(t.grantType==="client_credentials")return i.requestedScopes||M(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(t,r,i.requestedScopes,i,n);(!i.refreshToken||i.refreshExpiresAt&&i.refreshExpiresAt<=Date.now())&&M(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(t,r),c=await ore(s,a,this.authentication(r,t.clientAuth),i.refreshToken,{...this.options(t),additionalParameters:t.tokenParams}),u=await this.tokenResponse(t,r,c,!0);o=this.token(t,u,i.scopes,i,!0),await n?.(o,u)}return o}async revoke(t,r,i){if(!t.revoke?.tokenOnly)throw new Error("Revoke only with an endpoint that invalidates this token alone.");let n=pu(t.revoke.url,{...this.appValues(t,r),accessToken:i.accessToken,refreshToken:i.refreshToken??""});if(t.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(t,r),l=t.revoke.auth==="none"&&t.clientAuth!=="none"?()=>{}:this.authentication(r,t.revoke.auth??t.clientAuth),d=await yre({...c,revocation_endpoint:n},u,l,i.refreshToken??i.accessToken,this.options());try{await vre(d)}catch{M(502,"revoke_failed","The service did not revoke the token.")}return}let o={},s=t.revoke.auth??t.clientAuth;t.revoke.style==="bearer"?o.authorization="Bearer "+i.accessToken:s==="basic"&&(o.authorization="Basic "+A4(r.clientId,r.clientSecret??"")),(await this.transport.send($o(t).revokeRequest?.({spec:t,app:r,transport:this.transport,url:n,current:i})??{url:n,method:t.revoke.style==="bearer"?"POST":"DELETE",headers:o})).status>=300&&M(502,"revoke_failed","The service did not revoke the token.")}outputs(t,r,i){let n={...this.appValues(t,r),...i.extra,...i,expiresAt:i.expiresAt===null?"":String(i.expiresAt)};return Object.fromEntries(Object.entries(t.outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};function R4(e){if(e.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return e.method.config}function I4(e){return e||M(409,"app_required","Choose an OAuth application."),e}function hUe(e){return{token:LO.parse(e.token),response:Mt.parse(e.response)}}var HE=class{constructor(t){this.transport=t}transport;facts=yO;oauth(t){return new BE({send:r=>this.transport.send({...r,...t?{signal:AbortSignal.any([t,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(t){return!t.oauth||t.oauth.expiresAt!==null&&t.oauth.expiresAt<Date.now()+6e4}async renew(t){let r=t.material,i=R4(r),n=I4(t.app),o=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>t.receive({token:c,response:u}),a=i.grantType==="client_credentials"?await this.oauth(t.signal).clientCredentials(i,n,o??tV(i.scopes),r.oauth,s):await this.oauth(t.signal).refresh(i,n,r.oauth,s);return Pl.parse({...t.material,oauth:a})}async recover(t,r,i){let o=hUe(i).token;return Pl.parse({...t,oauth:o})}async outputs(t,r){return this.oauth().outputs(R4(t),I4(r),t.oauth)}async revoke(t,r,i){t.oauth&&await this.oauth(i).revoke(R4(t),I4(r),t.oauth)}};function gUe(e){if(e.method.kind!=="token"&&e.method.kind!=="approval")throw new Error("Use an input credential provider.");return e.method.config}var Vh=class{facts=El;needsRenewal(){return!1}async outputs(t){let r=gUe(t),i=qs(r.fields,t.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,o])=>[n,VE(i,o)]))}};function WE(e){if(e.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return e.method.config}var JE=class{facts=vO;values(t,r){let i=WE(t),n=i.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&M(409,"app_required","Choose an OVHcloud API application with its key and secret.");let o=n?r.fields:t.fields;return qs(i.fields,o)}credentials(t,r){if(WE(t).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:t.fields.consumerKey};let i=this.values(t,r);return{applicationKey:i.applicationKey,applicationSecret:i.applicationSecret,consumerKey:i.consumerKey}}needsRenewal(){return!1}async outputs(t,r){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let i="ovh"in t?t.ovh:void 0;i&&i.expiresAt!==null&&i.expiresAt<=Date.now()&&M(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=WE(t).authorization==="consumer_key"?{...this.values(t,r),...this.credentials(t,r)}:this.values(t,r);return Object.fromEntries(Object.entries(WE(t).outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};import{readFile as yUe}from"node:fs/promises";var vUe=p.object({accessToken:p.string().min(1).max(16384).regex(/^\S+$/),expiresAt:p.number().int().positive()}).strict();async function SUe(e,t){if(e==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,o=n?await yUe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!o||o.length>16384)&&M(409,"authentication_required","Provide the current OIDC token to this executor."),o.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([t,AbortSignal.timeout(3e3)])});r.ok||M(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let i=(await r.text()).trim();return(!i||i.length>16384)&&M(502,"invalid_response","The instance did not return a valid identity token."),i}function xre(e){if(e.method.kind!=="token"||e.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return e.method.config}var ZE=class{constructor(t,r=SUe){this.transport=t;this.identityToken=r}transport;identityToken;facts=El;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(t,r){let i=qs(xre(t).fields,t.fields),n=i.authentication;["api_key","oidc","instance"].includes(n)||M(400,"invalid_field","Choose a Vultr authentication source.");let o=n==="api_key"?i.token:i.credential||await this.identityToken(n,r);(!o||o.length>16384||/\s/.test(o))&&M(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(i.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&M(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+o},signal:r,body:JSON.stringify({role_id:i.roleId,session_name:i.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:i.userId}:{},...n==="oidc"?{oidc_issuer_id:i.issuerId}:{}})});a.status>=400&&M(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=Cl(a);(c.role_id!==void 0&&c.role_id!==i.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==i.userId)&&M(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=vUe.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&M(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(t,r,i){let n=xre(t);i.throwIfAborted();let o=await te(t),s=this.sessions.get(o);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(o);a||(a=this.obtain(t,i),this.pending.set(o,a));try{s=await a,this.sessions.set(o,s)}finally{this.pending.get(o)===a&&this.pending.delete(o)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,VE(s,c)]))}};function Ere(e,t){let r={oauth:new HE(e),token:new Vh,aws:new NE(t),approval:new Vh,ovh:new JE},i=new ZE(e);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?i:r[n.kind]}function Ci(e){return new TextDecoder("utf-8",{fatal:!0}).decode(e)}async function $4(e,t){let r={},i={},n=[],o=new Set;for(let s of e){if(o.has(s.name)||!_q(s.name))throw new Error("Use distinct, unreserved environment variable names.");o.add(s.name);let a=await t(s.source);if(s.format==="json"&&(a=ft(La(Wn(JSON.parse(Ci(a)),s.pointer??"")))),s.format==="file")i[s.name]=Buffer.from(a).toString("base64");else{let c=Ci(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:i,sensitive:n}}var sp=class{constructor(t,r,i,n,o,s=new OE){this.binding=t;this.keys=r;this.broker=i;this.journal=n;this.providers=Ere(o,s)}binding;keys;broker;journal;active=new Set;providers;provider(t){return this.providers(t)}metadata(t){return KV(t,this.provider(t.method).facts(t))}source(t,r,i){let n=i.find(o=>o.policy.id===t&&o.policy.contentType===r);return n||M(409,"input_required","Include the connection and its application in this execution."),n}async material(t,r,i){let n=typeof i=="function"?a=>i(Pl.parse(JSON.parse(Ci(a)))):i,o=Pl.safeParse(JSON.parse(Ci(await Ec(t,r,this.keys,{destination:n}))));o.success||M(409,"reconnect_required","Reconnect this service with the current connection format.");let s=o.data;return(await this.metadata(s)).authorizationDigest!==t.metadata.authorizationDigest&&M(409,"connection_changed","Approve the current service account and permissions before using this connection."),s.state==="reconnect"&&r.operation!==Q.revoke&&M(409,"reconnect_required","Reconnect this service before using it."),s}async app(t,r,i,n){let o=this.source(t,ge.clientCredential,n),s=aw.parse(JSON.parse(Ci(await Ec(o,i,this.keys))));return s.methodId!==r&&M(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(t,r,i){if(Ls(t.method).application==="none")return null;if(!xl(t.method))return"implicitApp"in t&&t.implicitApp?t.implicitApp:aw.parse({format:1,methodId:t.methodId,generation:t.generation,clientId:"",fields:{}});let n=r.operation===Q.revoke?Q.revoke:Q.refresh,o=await this.app(t.appId,t.methodId,{...r,operation:n},i);return o.generation!==t.appGeneration&&M(409,"app_changed","Reconnect this service with the current application."),Ls(t.method).requiresApp&&t.method.kind!=="aws"&&Object.entries($l(t.method.config.fields,t.fields??{})).some(([s,a])=>o.fields[s]!==a)&&M(409,"app_changed","Reconnect this service with the current application settings."),o}async validate(t,r,i){let n=MO.parse(t);r.operation!==Q[n.action]&&M(400,"wrong_operation","Use the approved connection operation.");let o=await this.material(this.source(n.id,ge.tokenSet,i),r);(n.action==="refresh"||Ls(o.method).revocable)&&await this.connectionApp(o,r,i)}async execute(t,r,i,n){let o=MO.parse(t);this.active.has(o.id)&&M(409,"connection_busy","Another operation is updating this connection."),this.active.add(o.id);try{n.throwIfAborted();let s=this.source(o.id,ge.tokenSet,i),a=await this.material(s,r);if(o.action==="refresh"){let l=await this.refresh(s,a,r,i,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(l)}}let c=this.provider(a.method),u=Ls(a.method).revocable&&!!c.revoke;return u&&await c.revoke(a,await this.connectionApp(a,r,i),n),{kind:"disconnected",id:s.policy.id,revoked:u}}finally{this.active.delete(o.id)}}async outputs(t,r,i,n,o){let s=await this.material(t,r,o);return this.provider(s.method).renew&&await this.broker.state(t.policy.id)&&M(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(t,s,r,i,n,o),this.provider(s.method).outputs(s,await this.connectionApp(s,r,i),n)}async httpDestination(t,r,i){let n=await this.material(t,r,o=>qO(o,i,r.origin));return qO(n,i,r.origin)}async http(t,r,i,n,o){let s=await this.httpDestination(t,r,o),a=await this.material(t,r,s),c=await this.outputs(t,r,i,n,s);return r3(s,o.headers,a.method.http,c)}async refreshed(t,r){let i=await this.metadata(r);return i.authorizationDigest!==t.previous.metadata.authorizationDigest&&M(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),t.material=r,t.content=await Fq(t.previous,ft(C(r)),this.binding,this.keys,i),t.phase="settled",await this.journal.write("refresh_"+t.operation.id,t),await this.broker.commit(t.operation.id,t.operation.fence,t.content),t.delivered=!0,await this.journal.write("refresh_"+t.operation.id,t),r}async refresh(t,r,i,n,o,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||M(409,"reconnect_required","Reconnect this service to renew access.");try{await Os(t,{...i,operation:Q.refresh},{destination:s})}catch{M(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,i,n),u=wUe(),l=await this.broker.prepare(u,t.policy.id,t.materialRevision),d={operation:l,previous:t,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{o.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),o.throwIfAborted();let m=await a.renew({material:r,app:c,signal:o,receive:async f=>{d.checkpoint=f,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,m)}catch(m){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),m instanceof Me&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(m.code))throw m;M(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let t=[];for(let r of await this.journal.pending("refresh_"))try{let i=await this.journal.read(r);if(i.delivered)continue;if(i.content){await this.broker.commit(i.operation.id,i.operation.fence,i.content),i.delivered=!0,await this.journal.write(r,i);continue}let n=await this.broker.state(i.operation.resource_id);if(!n||n.id!==i.operation.id||n.state==="prepared")n?.id===i.operation.id&&n.state==="prepared"&&await this.broker.abort(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i);else if(i.checkpoint&&this.provider(i.material.method).recover){let o=await this.provider(i.material.method).recover(i.material,i.app,i.checkpoint);await this.refreshed(i,o)}else await this.broker.uncertain(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i)}catch{t.push(r.slice(8))}return t}};import{lookup as bUe}from"node:dns/promises";import{request as _Ue}from"node:https";import{brotliDecompressSync as xUe,gunzipSync as EUe,inflateSync as AUe}from"node:zlib";var XE=class{constructor(t){this.origin=t}origin;async send(t){let r=Pn(t.url,this.origin),i=r.hostname.replace(/^\[|\]$/g,""),n=t.maxBytes??1048576;t.body&&Buffer.byteLength(t.body)>n&&M(413,"body_limit","The request body is too large.");let o={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(t.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&M(400,"invalid_header","Choose a valid request header."),o[c]=a}try{let s=await bUe(i,{all:!0,verbatim:!0});(!s.length||s.some(u=>!uw(u.address)))&&M(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]]);return await new Promise((u,l)=>{let d={method:t.method??"GET",headers:o,signal:c,agent:!1,lookup:(f,g,v)=>{g.all?v(null,[a]):v(null,a.address,a.family)}},m=_Ue(r,d,f=>{let g=[],v=0;f.on("data",S=>{v+=S.length,v>n?f.destroy(new Me(413,"body_limit","The response body is too large.")):g.push(S)}),f.on("error",l),f.on("end",()=>{try{let S=Buffer.concat(g),b=f.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?EUe:b==="deflate"?AUe:b==="br"?xUe:null;if(!x)throw new Me(502,"invalid_response","The service returned an unsupported response.");S=x(S,{maxOutputLength:n})}let _={};for(let[x,T]of Object.entries(f.headers))T!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(_[x]=Array.isArray(T)?T.join(", "):T);u({status:f.statusCode??502,headers:_,body:new Uint8Array(S)})}catch(S){l(S)}})});m.on("error",l),m.end(t.body)})}catch(s){if(s instanceof Me)throw s;t.signal?.aborted&&M(409,"cancelled","The operation was cancelled."),M(502,"service_unavailable","The service could not be reached. Try again.")}}};function Are(e){let{keys:t,binding:r,origin:i}=e.identity;if(!t||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=P4(RUe(hO()),"custody",r.id),o=new Tc(P4(n,"client"),i,r,t),s=new lw(e,i,r,t,new pw(o)),a=new fw(e),c=new XE(i),u=new sp(r,t,a.connections(),new Tc(P4(n,"connections"),i,r,t),c);return{custody:s,journal:o,directory:n,keys:t,binding:r,broker:a,transport:c,connections:u}}function IUe(e,t){let r={};if(Object.keys(t).some(i=>!e.parameters.some(n=>n.name===i)))throw new Error("Use the parameters this function declares.");for(let i of e.parameters){let n=Object.hasOwn(t,i.name)?t[i.name]:i.default;if(n===void 0){if(i.required)throw new Error("Complete the required function parameters.");continue}if(i.type!=="json"&&typeof n!==i.type||i.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(i.required&&i.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[i.name]=n}return r}function YE(e,t){let r=IUe(e,t);if(e.program.kind==="command"){let{kind:c,...u}=e.program;return{kind:c,...vc.parse({...u,stdin:JSON.stringify(r)})}}if(e.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");let i=e.program.request,n=c=>typeof c=="string"?c:JSON.stringify(c),o=(c,u=!1)=>{if(u&&typeof c=="string"){let l=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(c)?.[1];if(l){if(!e.parameters.some(d=>d.name===l))throw new Error("Declare every function parameter.");return Object.hasOwn(r,l)?r[l]:null}}return typeof c=="string"?c.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(l,d)=>{if(!e.parameters.some(m=>m.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?n(r[d]):""}):Array.isArray(c)?c.map(l=>o(l,u)):c&&typeof c=="object"?Object.fromEntries(Object.entries(c).map(([l,d])=>[l,o(d,u)])):c},s=i.url===void 0?void 0:new sw(i.url).expand(Object.fromEntries(Object.entries(r).map(([c,u])=>[c,n(u)]))),a=yc.parse({...o(i),...s===void 0?{}:{url:s},connectionId:i.connectionId,bindings:i.bindings,...i.json===void 0?{}:{json:o(i.json,!0)}});if(i.url!==void 0){let c=new URL(i.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.")}return{kind:"http",request:a,responseFormat:e.program.responseFormat}}var kPt=p.object({operation:Ic,save:p.record(p.string(),be)}).strict();function $Ue(e){return e.kind==="http"?{kind:e.kind,request:e.request}:e}async function Rre(e,t){let r=e.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=kq.parse(r.invocation.input);if(t.kind!=="revoke"||C(t.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==e.ownerId||n.environmentId!==e.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let i=Dq.parse(r.invocation.input);if(i.ownerId!==e.ownerId||i.environmentId!==e.environmentId||i.operation.kind!==t.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in i.operation){if(await te($Ue(t))!==i.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(t.kind==="http"&&i.operation.kind==="http"){if(C(t.request)!==C(i.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(t)!==C(Ic.parse(i.operation)))throw new Error("Run the reviewed command.");if(t.kind==="http"&&C(Object.fromEntries(Object.entries(t.save).map(([n,o])=>[n,o.name])))!==C(i.save))throw new Error("Use the reviewed output destinations.")}function PUe(e,t){return e.policy.contentType===ge.value?t.output===void 0:e.policy.contentType===ge.tokenSet&&t.output!==void 0}var Po=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}};function T4(e){return!(e instanceof Me)||["service_unavailable","connection_uncertain","lease_lost"].includes(e.code)}var QE=class{constructor(t,r,i,n,o,s,a,c=s){this.environment=t;this.keys=r;this.broker=i;this.journal=n;this.transport=o;this.commands=s;this.extension=a;this.functionCommands=c}environment;keys;broker;journal;transport;commands;extension;functionCommands;get binding(){return this.environment.manifest.executor}async reconcile(){let t=[];for(let r of await this.journal.pending("run_"))try{let i=await this.journal.read(r);if(!i||i.delivered)continue;if(!i.receipt&&i.phase==="dispatched"){let n=i.operation?.kind==="connect"?await this.extension?.recover?.(i.operation.input,i.request.intent):null;i.receipt=n?await _l(i.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await _l(i.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),i.phase="settled",await this.journal.write(r,i)}i.receipt&&(await this.broker.finish(i.lease,i.receipt),i.delivered=!0,await this.journal.write(r,i))}catch{t.push(r.slice(4))}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:i}=r.request,n="run_"+i.id,o=await te(r.request),s=await this.journal.read(n);if(s&&s.digest!==o)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 m=await _l(i,"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:m,delivered:!1}),await this.broker.finish(r.lease,m),!0}s={digest:o,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([t,a.signal]),u=setInterval(()=>{this.broker.renew(i.id,r.lease).then(m=>{m.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let m=await qq(r.request,this.binding,this.keys);await bl(this.environment,m.intent);let f=Ic.parse(m.operation);if(Q[f.kind]!==i.operation)throw new Error("Use the operation authorized by this intent.");await Rre(i,f),await this.validateOperation(f,i,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(i.id,r.lease),c.throwIfAborted();let g=await this.executeOperation(f,i,r.sources,c);d=await _l(i,"succeeded",{ok:!0,result:g,error:null},this.keys)}catch(m){if(m instanceof Po)throw m;m instanceof Sl&&(m=new Me(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||T4(m));d=await _l(i,f?"uncertain":"failed",{ok:!1,result:null,error:m instanceof Me?{code:m.code,message:m.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(t){let r=t.kind==="function"?YE(t.definition,t.arguments):t;return r.kind==="http"?r.request:null}async validateOperation(t,r,i){if(new Set(i.map(u=>u.policy.id)).size!==i.length||i.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let u of i){await on(u);let l=r.sources.find(f=>f.id===u.policy.id);if(!l||!await sO(u,l))throw new Error("An execution input changed.");let d="checkpoint_"+u.policy.format+"_"+u.policy.id,m=await this.journal.read(d);if(m&&(u.policy.revision<m.policy||u.materialRevision<m.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(d,{policy:u.policy.revision,material:u.materialRevision})}if(t.kind==="function"&&(t.functionId!==r.functionId||await te(t.definition)!==r.functionDigest||!this.environment.manifest.capabilities.includes(Q[t.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(t.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(t),o=n?.url;if(n){if(n.connectionId){let u=i.find(l=>l.policy.id===n.connectionId);if(this.environment.manifest.httpVersion!==zi||!this.extension?.httpDestination||!u||u.policy.contentType!==ge.tokenSet)throw new Error("Choose an HTTP connection and a current execution environment.");o=await this.extension.httpDestination(u,r,n)}if(Pn(o,r.origin),[n.body,n.json,n.form].filter(u=>u!==void 0).length>1)throw new Error("Choose one request body format.");for(let u of n.bindings){let l=qh(u.pointer);if(!l.length||!["headers","body","json","form"].includes(l[0])||l[0]==="body"&&l.length!==1||["headers","form"].includes(l[0])&&l.length!==2)throw new Error("Bind credentials to request headers or the body.");E4(structuredClone(n),u.pointer,"validation")}}let s=t.kind==="function"?t.outputs:t.kind==="http"?t.save:{};for(let[u,l]of Object.entries(s)){if(qh(u),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let d=await Us(l.approval);if(C(d.policy.authorities.find(m=>m.id===d.authorityId))!==C(r.actor)||d.policy.origin!==r.origin||d.policy.contentType!==ge.value||d.policy.ownerId!==r.ownerId||!d.policy.producers.some(m=>m.runId===r.id&&C(m.executor)===C(this.binding)&&Date.parse(m.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let a=t.kind==="function"?YE(t.definition,t.arguments):t,c=a.kind==="command"?a.inputs.map(u=>u.source):n?Uf(n):[];for(let u of c){let l=i.find(m=>m.policy.id===u.id),d=n?.connectionId===u.id&&u.output===void 0;if(!l||!(d?l.policy.contentType===ge.tokenSet:PUe(l,u)))throw new Error("Use the input named in the signed request.");await Os(l,r,{destination:o}),await Ec(l,r,this.keys,{destination:o})}if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(t.input,r,i)}}async executeOperation(t,r,i,n){if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke")return this.extension.execute(t.input,r,i,n);let o=this.request(t),s=t.kind==="function"?YE(t.definition,t.arguments):t,a=o?.connectionId?await this.extension.httpDestination(i.find(v=>v.policy.id===o.connectionId),r,o):o?.url,c=[],u=new Map,l=async v=>{let S=i.find(_=>_.policy.id===v.id);if(S.policy.contentType===ge.value)return Ec(S,r,this.keys,{...o?{destination:a}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");u.has(v.id)||u.set(v.id,this.extension.outputs(S,r,i,n,a));let b=await u.get(v.id);if(!v.output||!Object.hasOwn(b,v.output))throw new Error("Choose an available connection output.");return ft(b[v.output])};if(s.kind==="command"){let v=await $4(s.inputs,l),b=await(t.kind==="function"?this.functionCommands:this.commands).execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:v.environment,files:v.files,...t.kind==="function"?{workspace:"temporary"}:{}},n);if(t.kind==="function"){if(b.timedOut)throw new Me(408,"function_timeout","The function exceeded its time limit.");if(b.truncated)throw new Me(413,"function_output_limit","The function output exceeded its size limit.");if(b.exitCode!==0)throw new Me(422,"function_failed",op(b.stderr,v.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(t,r,b.stdout)}return{...b,stdout:op(b.stdout,v.sensitive),stderr:op(b.stderr,v.sensitive)}}let d=structuredClone(o);for(let v of d.bindings){let S="";for(let b of v.parts)if(typeof b=="string")S+=b;else{let _=Ci(await l(b));c.push(_,Buffer.from(_).toString("base64"),Buffer.from(_).toString("base64url")),S+=_}E4(d,v.pointer,S)}if(d.connectionId){if(!this.extension?.http)throw new Error("This executor cannot use HTTP connections.");let v=await this.extension.http(i.find(S=>S.policy.id===d.connectionId),r,i,n,d);d.url=v.url,d.headers=v.headers,c.push(...v.sensitive)}let m=d.body;d.json!==void 0&&(m=JSON.stringify(d.json),d.headers["content-type"]="application/json"),d.form!==void 0&&(m=new URLSearchParams(d.form).toString(),d.headers["content-type"]="application/x-www-form-urlencoded");let f=await this.transport.send({url:d.url,method:d.method,headers:d.headers,...m===void 0?{}:{body:m},signal:n});if(t.kind==="function"){if(f.status<200||f.status>=300)throw new Me(502,"service_response","The service returned HTTP "+f.status+".");let v=t.definition.program.kind==="http"?t.definition.program.responseFormat:"json",S=Ci(f.body);if(v==="json")try{S=f.body.length===0&&([204,205].includes(f.status)||d.method==="HEAD")?null:Nr.parse(JSON.parse(S))}catch{throw new Me(422,"invalid_function_result","The HTTP response body must contain valid JSON.")}return this.functionResult(t,r,JSON.stringify({status:f.status,headers:f.headers,body:S}))}let g=t.kind==="http"?t.save:{};if(Object.keys(g).length){if(f.status>=400)throw new Me(502,"service_response","The service returned an unsuccessful response.");let v={};for(let[S,b]of Object.entries(g)){let _=f.body;if(S!==""){let T=Wn(JSON.parse(Ci(_)),S);if(T===void 0)throw new Me(400,"invalid_pointer","The response value was not found.");_=ft(typeof T=="string"?T:JSON.stringify(T))}let x=await Af(_,b.approval,r.id,this.binding,this.keys,{bytes:_.length});v[b.name]=(await this.broker.capture(b.name,x)).id}return{status:f.status,saved:v}}return{status:f.status,headers:Object.fromEntries(Object.entries(f.headers).map(([v,S])=>[v,op(S,c)])),body:op(Ci(f.body),c)}}async functionResult(t,r,i){let n;try{n=t.definition.result==="text"?i:Nr.parse(JSON.parse(i))}catch{throw new Me(422,"invalid_function_result","The function must return valid JSON.")}let o={};for(let[s,a]of Object.entries(t.outputs)){let c=s===""?n:Wn(n,s);if(c===void 0)throw new Me(400,"invalid_pointer","The function result value was not found.");let u=ft(typeof c=="string"?c:JSON.stringify(c)),l=await Af(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});o[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(o).length?{saved:o}:n}};import{spawn as Ire}from"node:child_process";import{mkdir as $re,mkdtemp as TUe,rm as CUe,writeFile as Pre}from"node:fs/promises";import{tmpdir as kUe}from"node:os";import{join as Kh}from"node:path";import{StringDecoder as Tre}from"node:string_decoder";function Cre(e={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...e}}var Bh=class{constructor(t){this.options=t;if(t.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(t.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(t,r){r.throwIfAborted();let i=await TUe(Kh(kUe(),"foundation-job-")),n=Kh(i,"files"),o="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=t.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await $re(n,{mode:448});let l={...t.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[m,f]of Object.entries(t.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m))throw new Error("Use valid file variable names.");await Pre(Kh(n,m),Buffer.from(f,"base64"),{mode:384,flag:"wx"}),l[m]=s?"/run/foundation/"+m:Kh(n,m)}let d=t.command;if(s){if(Object.entries(l).some(([g,v])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(g)||v.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let m=Object.entries(l).filter(([,g])=>/[\r\n]/.test(g)),f=Kh(i,"environment");await Pre(f,Object.entries(l).filter(([,g])=>!/[\r\n]/.test(g)).map(([g,v])=>g+"="+v).join(`
123
123
  `),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await $re(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",o,"--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",f,...m.flatMap(([g,v])=>["--env",g+"="+v]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:t.workingDirectory?["--workdir",t.workingDirectory]:[],"--entrypoint="+t.command[0],"-i",this.options.image,...t.command.slice(1)]}return await new Promise(m=>{let f=Ire(d[0],d.slice(1),{env:Cre(s?{}:a?{...l,HOME:i,TMPDIR:i}:l),cwd:s?this.options.cwd:a?i:t.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),g={stdout:new Tre("utf8"),stderr:new Tre("utf8")},v=0,S=!1,b=(U,N)=>{let K=Math.max(0,1e6-v);N.length>K&&(c.truncated=!0);let B=N.subarray(0,K);v+=B.length,c[U]+=g[U].write(B)};f.stdout.on("data",U=>b("stdout",U)),f.stderr.on("data",U=>b("stderr",U)),f.stdin.on("error",()=>{}),f.stdin.end(t.stdin??"");let _=()=>{u=!0;try{f.pid&&process.platform!=="win32"?process.kill(-f.pid,"SIGKILL"):f.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,_()},t.timeoutSeconds*1e3);x.unref();let T=()=>{S||(S=!0,clearTimeout(x),r.removeEventListener("abort",_),c.stdout+=g.stdout.end(),c.stderr+=g.stderr.end(),m())};r.addEventListener("abort",_,{once:!0}),r.aborted&&_(),f.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",T()}),f.once("close",(U,N)=>{c.exitCode=U,c.signal=N,T()})}),c}finally{s&&u&&await new Promise(l=>{let d=Ire("docker",["rm","-f",o],{env:Cre(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await CUe(i,{recursive:!0,force:!0})}}};import{spawn as DUe}from"node:child_process";import{constants as C4}from"node:fs";import{open as kre,rm as OUe}from"node:fs/promises";async function Dre(e){if(process.platform!=="linux"){let r=await kre(e,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+e+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await OUe(e,{force:!0})}}let t=await kre(e,C4.O_CREAT|C4.O_WRONLY|C4.O_NOFOLLOW,384);try{let r=DUe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",t.fd]});await new Promise((i,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",o=>o===0?i():n(new Error(o===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await t.close(),r}return()=>t.close()}var HI=lt(u4(),1),WI=lt(fhe(),1);function mhe(e){return aO.safeParse(e).success?e:null}async function hhe(e=3e3){let t=new HI.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,i=AbortSignal.timeout(e);try{let n=await t.send(new HI.GetCallerIdentityCommand({}),{abortSignal:i});if(!n.Arn)return null;let o=mhe(n.Arn);if(o)return o;let s=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(n.Arn);if(!s||n.Account!==s[2]||!n.UserId)return null;r=new WI.IAMClient({region:t.config.region,credentials:t.config.credentials});let c=(await r.send(new WI.GetRoleCommand({RoleName:s[3]}),{abortSignal:i})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=mhe(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{t.destroy(),r?.destroy()}}var Aj=p.string().refine(e=>!e.includes("\0"),"Use text without null bytes."),Rj=Aj.max(4096).startsWith("/"),ghe=p.object({command:p.array(Aj.max(8192)).min(1).max(100).refine(e=>!!e[0],"Specify a program."),workingDirectory:Rj.optional(),environment:p.record(p.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),Aj.max(65536)).refine(e=>Object.keys(e).length<=128&&JSON.stringify(e).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:p.string().max(1e6).default(""),timeoutSeconds:p.number().int().min(1).max(3600).default(60)}).strict(),cTt=ghe.extend({id:P.optional()}),yhe=p.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),vhe=p.object({exitCode:p.number().int().nullable(),signal:p.string().max(32).nullable(),stdout:p.string().max(1e6),stderr:p.string().max(1e6),timedOut:p.boolean(),truncated:p.boolean()}).strict(),uTt=p.object({state:yhe.exclude(["queued","running"]),result:vhe.nullable(),error:p.string().max(100).nullable()}).strict(),JI=ghe.extend({id:P,environmentId:P,ownerId:P,actorId:P,workingDirectory:Rj,state:yhe,result:vhe.nullable(),error:p.string().nullable(),createdAt:ce,startedAt:ce.nullable(),finishedAt:ce.nullable()}).strict(),lTt=JI.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),dTt=p.object({workingDirectory:Rj}).strict(),She=p.object({lease:P,process:JI}).strict().nullable();var ZI=class{constructor(t){this.api=t}api;claim(t){return this.api.json("/api/environments/"+t+"/processes/claim",{method:"POST",body:{}},She)}dispatch(t,r){return this.api.json("/api/processes/"+t+"/dispatch",{method:"POST",body:{lease:r}})}renew(t,r){return this.api.json("/api/processes/"+t+"/renew",{method:"POST",body:{lease:r}},p.object({active:p.boolean()}))}finish(t,r,i){return this.api.json("/api/processes/"+t+"/finish",{method:"POST",body:{lease:r,...i}},JI)}},XI=class{constructor(t,r,i,n,o=15e3){this.environmentId=t;this.broker=r;this.journal=i;this.commands=n;this.renewalMilliseconds=o}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(t){await this.broker.finish(t.id,t.lease,t.completion),await this.journal.write("process_"+t.id,{...t,delivered:!0})}async reconcile(){let t=[];for(let r of await this.journal.pending("process_")){let i=await this.journal.read(r);if(!(!i||i.delivered||i.phase==="prepared")){i.completion??={state:"uncertain",result:null,error:"execution_interrupted"},i.phase="settled",await this.journal.write(r,i);try{await this.deliver(i)}catch{t.push(i.id)}}}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:i,process:n}=r,o=await this.journal.read("process_"+n.id);if(o&&o.phase!=="prepared"){let l=o.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,i,l),await this.journal.write("process_"+n.id,{...o,lease:i,completion:l,phase:"settled",delivered:!0}),!0}let s={id:n.id,lease:i,delivered:!1,completion:null,phase:"prepared"};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();t.addEventListener("abort",c,{once:!0}),t.aborted&&c();let u;try{s.phase="dispatched",await this.journal.write("process_"+n.id,s),await this.broker.dispatch(n.id,i),u=setInterval(()=>{this.broker.renew(n.id,i).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),t.removeEventListener("abort",c)}s.phase="settled",await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Po}return!0}};var Ij=p.object({format:p.literal(2),functionId:P,ownerId:P,revision:p.number().int().positive(),definition:ks,author:vt,createdAt:ce,signature:_t}).strict();async function whe(e){let t=Ij.parse(e),{signature:r,...i}=t;return await Mi(i.author),await nr(i,r,i.author.signing,"function-publication"),t}var sWe=p.object({functionId:P,publication:Ij}).strict(),$j=p.object({format:p.literal(1),functionId:P,ownerId:P,definitionDigest:yt,revision:p.number().int().positive(),environmentId:P.nullable(),inputAccess:wf,author:vt,executor:vt.nullable(),createdAt:ce,signature:_t}).strict().refine(e=>e.environmentId===null==(e.executor===null),{message:"Approve the executor of the selected environment."});async function bhe(e,t){let r=$j.parse(e),{signature:i,...n}=r;if(await Mi(n.author),await nr(n,i,n.author.signing,"function-settings"),t&&C(n.executor)!==C(t))throw new Error("This function is approved for another executor.");return r}var _Tt=p.object({approval:$j,contents:p.record(P,p.object({version:p.number().int().positive(),content:ir}).strict())}).strict(),aWe=p.object({name:be,definition:ks,authorization:sWe}).strict(),xTt=aWe.extend({version:p.number().int().positive()}),cWe=p.object({id:P.optional(),ownerId:P.optional(),arguments:Mt.default({}),outputs:p.record(p.string().max(500),BS).default({})}).strict(),_he=p.object({code:p.string().max(100),message:p.string().max(1e3)}).strict(),xhe=p.object({id:P,functionId:P,functionVersion:p.number().int().positive(),ownerId:P,actorId:P,state:VS,result:Nr.nullable(),error:_he.nullable(),createdAt:ce,startedAt:ce.nullable(),finishedAt:ce.nullable()}).strict(),uWe=p.object({id:P,functionId:P,functionVersion:p.number().int().positive(),ownerId:P,actorId:P,actor:vt.nullable(),arguments:Mt,outputs:cWe.shape.outputs,definitionDigest:yt,settingsDigest:yt,environmentId:P,createdAt:ce,expiresAt:ce}).strict(),Ehe=p.object({id:P,requestDigest:p.string().regex(/^[A-Za-z0-9_-]{43}$/),state:VS.exclude(["queued","running"]),result:Nr.nullable(),error:_he.nullable(),finishedAt:ce,signature:_t}).strict(),Ahe=p.object({lease:P,request:uWe,publication:Ij,settings:$j,sources:p.array(ir).max(100)}).strict().nullable();var YI=class{api;constructor(t){this.api={async json(r,i={},n){try{return await t.json(r,i,n)}catch(o){throw o instanceof Error&&"status"in o&&typeof o.status=="number"&&"code"in o&&typeof o.code=="string"?new Me(o.status,o.code,o.message):o}}}}claim(t){return this.api.json("/api/environments/"+t+"/invocations/claim",{method:"POST",body:{}},Ahe)}dispatch(t,r){return this.api.json("/api/runtime/functions/"+t+"/dispatch",{method:"POST",body:{lease:r}})}renew(t,r){return this.api.json("/api/runtime/functions/"+t+"/renew",{method:"POST",body:{lease:r}},p.object({active:p.boolean(),reason:p.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(t,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:t,completion:r}},xhe)}},QI=class{constructor(t,r,i,n=15e3){this.executor=t;this.broker=r;this.journal=i;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(t,r,i,n){let o={id:t.id,requestDigest:t.digest,state:r,result:i,error:n,finishedAt:new Date().toISOString()};t.completion=Ehe.parse({...o,signature:await Tt(o,this.executor.keys.signing,"function-result")}),t.phase="settled",await this.journal.write("invocation_"+t.id,t)}async deliver(t){await this.broker.finish(t.lease,t.completion),t.delivered=!0,await this.journal.write("invocation_"+t.id,t)}async reconcile(){let t=[];for(let r of await this.journal.pending("invocation_"))try{let i=await this.journal.read(r);if(!i||i.delivered||i.phase==="prepared")continue;i.completion||await this.complete(i,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(i)}catch{t.push(r.slice(11))}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:i,publication:n,settings:o,sources:s,lease:a}=r,c=await te(i),u="invocation_"+i.id,l=await this.journal.read(u);if(l&&l.digest!==c)throw new Error("An invocation ID was reused for different input.");if(l?.completion)return l.lease=a,await this.deliver(l),!0;if(l?.phase==="dispatched")return l.lease=a,await this.complete(l,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(l),!0;l={id:i.id,digest:c,lease:a,phase:"prepared",delivered:!1,completion:null},await this.journal.write(u,l);let d=new AbortController,m=AbortSignal.any([t,d.signal]),f=!1,g=!1,v=setInterval(()=>{g||(g=!0,this.broker.renew(i.id,a).then(S=>{S.active||(f||=S.reason==="cancelled",d.abort())},()=>d.abort()).finally(()=>{g=!1}))},this.renewalMilliseconds);v.unref();try{if(await whe(n),await bhe(o,this.executor.binding),n.functionId!==i.functionId||o.functionId!==i.functionId||o.ownerId!==n.ownerId||o.definitionDigest!==i.definitionDigest||await te(o)!==i.settingsDigest||o.environmentId!==this.executor.environment.manifest.id||i.environmentId!==o.environmentId||await te(n.definition)!==i.definitionDigest||Date.parse(i.expiresAt)<=Date.now()||!Go(o.inputAccess)||vl(o.inputAccess)<Date.parse(i.expiresAt))throw new Error("Run the current approved function in its configured environment.");let S="function_"+n.functionId,b=await this.journal.read(S),_=await te(n);if(b&&(n.revision<b.revision||n.revision===b.revision&&b.digest!==_))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(S,{revision:n.revision,digest:_});let x="checkpoint_function_settings_"+n.functionId,T=await this.journal.read(x);if(T&&(o.revision<T.revision||o.revision===T.revision&&i.settingsDigest!==T.digest))throw new Error("The execution settings are older than this executor has already observed.");await this.journal.write(x,{revision:o.revision,digest:i.settingsDigest});let U=Zq.parse({kind:"function",functionId:i.functionId,definition:n.definition,arguments:i.arguments,outputs:i.outputs}),N={format:2,id:i.id,origin:this.executor.environment.manifest.origin,ownerId:i.ownerId,actor:i.actor??this.executor.binding,executor:this.executor.binding,environmentId:o.environmentId,environmentDigest:await te(this.executor.environment.manifest),operation:Q.function,operationDigest:await te(U),functionId:i.functionId,functionDigest:i.definitionDigest,sources:await Promise.all(s.map(async B=>({id:B.policy.id,policyDigest:await te(B.policy),materialRevision:B.materialRevision,...B.policy.contentType===ge.tokenSet&&typeof B.metadata.authorizationDigest=="string"?{authorizationDigest:B.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:i.createdAt,expiresAt:i.expiresAt};await bl(this.executor.environment,N),await this.executor.validateOperation(U,N,s),m.throwIfAborted(),await this.broker.dispatch(i.id,a),l.phase="dispatched",await this.journal.write(u,l),m.throwIfAborted();let K=await this.executor.executeOperation(U,N,s,m);if(new TextEncoder().encode(JSON.stringify(K)).byteLength>1e6)throw new Me(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(l,"succeeded",K,null)}catch(S){if(S instanceof Po)throw S;let b=l.phase==="dispatched",_=m.aborted&&f?"cancelled":b&&(m.aborted||T4(S))?"uncertain":"failed";await this.complete(l,_,null,_==="uncertain"?{code:"execution_uncertain",message:"The outcome could not be confirmed. Check the destination before invoking this function again."}:!m.aborted&&S instanceof Me?{code:S.code,message:S.message}:{code:_==="cancelled"?"invocation_cancelled":"invalid_function",message:_==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(v)}try{await this.deliver(l)}catch{throw new Po}return!0}};async function Ihe(e,t){let{directory:r,keys:i,binding:n,broker:o,transport:s}=Are(e),a=P.parse(t.id??crypto.randomUUID()),c=Pj(r,"executors",a);await Rhe(c,{recursive:!0,mode:448});let u=Pj(c,"workspace");await Rhe(u,{recursive:!0,mode:448});let l=await Dre(Pj(c,"process.lock")),d=new AbortController,m=()=>d.abort();process.on("SIGINT",m),process.on("SIGTERM",m);try{let f=new Tc(c,e.identity.origin,n,i),g=await f.read("environment_"+a),v=await hhe(),S=g?{isolation:g.manifest.isolation,image:g.manifest.commandImage,functionImage:g.manifest.functionImage}:t,b={isolation:S.isolation,...S.image?{commandImage:S.image}:{},...S.functionImage?{functionImage:S.functionImage}:{}};if(g){if(await wl(g),g.manifest.ownerId!==t.ownerId||C(g.manifest.executor)!==C(n))throw new Error("Use the owner and identity originally registered for this executor.");if(g.manifest.functionVersion!==Ac||g.manifest.httpVersion!==zi||g.manifest.resultVersion!==1||(g.manifest.awsPrincipal??null)!==v||g.manifest.isolation!==b.isolation||g.manifest.commandImage!==b.commandImage||g.manifest.functionImage!==b.functionImage){let{awsPrincipal:de,commandImage:pe,functionImage:qe,...ee}=g.manifest;g=await uO({...ee,functionVersion:Ac,httpVersion:zi,resultVersion:1,...b,...v?{awsPrincipal:v}:{},revision:ee.revision+1},i),await f.write("environment_"+a,g)}}else g=await uO({format:3,id:a,origin:e.identity.origin,ownerId:t.ownerId,name:t.name,executor:n,operatorId:n.principalId,driver:"attached",capabilities:Object.values(Q),functionVersion:Ac,httpVersion:zi,resultVersion:1,...b,...v?{awsPrincipal:v}:{},revision:1},i),await f.write("environment_"+a,g);await e.json("/api/environments/"+a+"/registration",{method:"PUT",body:g}),process.stdout.write(JSON.stringify({environmentId:a,identityId:n.principalId,fingerprint:await US(n),isolation:g.manifest.isolation,...g.manifest.awsPrincipal?{awsPrincipal:g.manifest.awsPrincipal}:{},...g.manifest.isolation==="process"?{notice:"Only allow trusted code on this host."}:{}})+`
124
124
  `);let _=new sp(n,i,o.connections(),f,s),x=g.manifest.isolation==="container"?"/workspace":process.cwd(),T=new Bh({isolation:g.manifest.isolation,image:g.manifest.commandImage,workspace:u}),U=g.manifest.functionImage?new Bh({isolation:"container",image:g.manifest.functionImage}):T,N=new QE(g,i,o,f,s,T,_,U),K=new QI(N,new YI(e),f);await e.json("/api/environments/"+a+"/processes/registration",{method:"PUT",body:{workingDirectory:x}});let B=new XI(a,new ZI(e),f,T);do{let de=[...await _.reconcile(),...await N.reconcile(),...await K.reconcile(),...await B.reconcile()];de.length&&process.stderr.write(JSON.stringify({event:"reconciliation_pending",ids:de})+`
125
125
  `);let pe=!1;try{pe=await N.tick(d.signal),pe=await K.tick(d.signal)||pe,pe=await B.tick(d.signal)||pe}catch(qe){if(!(qe instanceof Po)||t.once)throw qe}if(t.once)break;pe||await lWe(1e3,void 0,{signal:d.signal})}while(!d.signal.aborted)}catch(f){if(!d.signal.aborted)throw f}finally{process.off("SIGINT",m),process.off("SIGTERM",m),await l()}return 0}async function fWe(){let e=dWe({allowPositionals:!0,options:{version:{type:"boolean"},origin:{type:"string"},owner:{type:"string"},id:{type:"string"},name:{type:"string"},isolation:{type:"string"},image:{type:"string"},once:{type:"boolean"}}});if(e.values.version)return process.stdout.write(`Foundation executor: functions ${Ac}, HTTP ${zi}