@tomato414941/foundation 5.0.1 → 5.1.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/cli.mjs +3 -3
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -11,7 +11,7 @@ More information can be found at: https://a.co/c895JFp`))}}});var NNe,zNe,$8,R8=
|
|
|
11
11
|
`+f}catch{!r.logger||r.logger?.constructor?.name==="NoOpLogger"?console.warn(f):r.logger?.warn?.(f)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(kr.isInstance(n)){let{headers:p={},statusCode:m}=n,y=Object.entries(p);d.$metadata={httpStatusCode:m,requestId:FL(/^x-[\w-]+-request-?id$/,y),extendedRequestId:FL(/^x-[\w-]+-id-2$/,y),cfId:FL(/^x-[\w-]+-cf-id$/,y)}}}catch{}}throw d}},FL=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var tJ,rJ=_(()=>{Re();y$();tJ=t=>(e,r)=>async o=>{let{operationSchema:n}=Vt(r),[,i,s,a,c,u]=n??[],l=r.endpointV2?async()=>xo(r.endpointV2):t.endpoint,d=await t.protocol.serializeRequest(If(i,s,a,c,u),o.input,{...t,...r,endpoint:l});return e({...o,request:d})}});function Os(t){return{applyToStack:e=>{e.add(tJ(t),VL),e.add(Q8(t),qL),t.protocol.setSerdeContext(t)}}}var qL,VL,nJ=_(()=>{eJ();rJ();qL={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},VL={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var ir,Xc=_(()=>{ir=class{name;namespace;traits;static assign(e,r){return Object.assign(e,r)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}getName(){return this.namespace+"#"+this.name}}});var Uy,oJ,iJ=_(()=>{Xc();Uy=class t extends ir{static symbol=Symbol.for("@smithy/lis");valueSchema;symbol=t.symbol},oJ=(t,e,r,o)=>ir.assign(new Uy,{name:e,namespace:t,traits:r,valueSchema:o})});var Ly,sJ,aJ=_(()=>{Xc();Ly=class t extends ir{static symbol=Symbol.for("@smithy/map");keySchema;valueSchema;symbol=t.symbol},sJ=(t,e,r,o,n)=>ir.assign(new Ly,{name:e,namespace:t,traits:r,keySchema:o,valueSchema:n})});var jy,cJ,uJ=_(()=>{Xc();jy=class t extends ir{static symbol=Symbol.for("@smithy/ope");input;output;symbol=t.symbol},cJ=(t,e,r,o,n)=>ir.assign(new jy,{name:e,namespace:t,traits:r,input:o,output:n})});var ed,lJ,GL=_(()=>{Xc();ed=class t extends ir{static symbol=Symbol.for("@smithy/str");memberNames;memberList;symbol=t.symbol},lJ=(t,e,r,o,n)=>ir.assign(new ed,{name:e,namespace:t,traits:r,memberNames:o,memberList:n})});var Fy,dJ,pJ=_(()=>{Xc();GL();Fy=class t extends ed{static symbol=Symbol.for("@smithy/err");ctor;symbol=t.symbol},dJ=(t,e,r,o,n,i)=>ir.assign(new Fy,{name:e,namespace:t,traits:r,memberNames:o,memberList:n,ctor:null})});function Li(t){if(typeof t=="object")return t;if(t=t|0,qy[t])return qy[t];let e={},r=0;for(let o of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(t>>r++&1)===1&&(e[o]=1);return qy[t]=e}var qy,HL=_(()=>{qy=[]});function Gy(t,e){if(t instanceof K)return Object.assign(t,{memberName:e,_isMemberSchema:!0});let r=K;return new r(t,e)}var Vy,Hy,By,K,BL,KL,fJ=_(()=>{jL();HL();Vy={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},Hy=[],By={},K=class t{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=t.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,r){this.ref=e,this.memberName=r;let o=[],n=e,i=e;for(this._isMemberSchema=!1;BL(n);)o.push(n[1]),n=n[0],i=Wo(n),this._isMemberSchema=!0;if(o.length>0){this.memberTraits={};for(let s=o.length-1;s>=0;--s){let a=o[s];Object.assign(this.memberTraits,Li(a))}}else this.memberTraits=0;if(i instanceof t){let s=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},s,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=r??i.memberName;return}if(this.schema=Wo(i),KL(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(i),this.traits=0),this._isMemberSchema&&!r)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}static of(e){let r=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if(Hy[e])return Hy[e]}else if(typeof e=="string"){if(By[e])return By[e]}else if(r&&e[Vy.ns])return e[Vy.ns];let o=Wo(e);if(o instanceof t)return o;if(BL(o)){let[i,s]=o;if(i instanceof t)return Object.assign(i.getMergedTraits(),Li(s)),i;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}let n=new t(o);return r?e[Vy.ns]=n:typeof o=="string"?By[o]=n:typeof o=="number"?Hy[o]=n:n}getSchema(){let e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){let{name:r}=this;return!e&&r&&r.includes("#")?r.split("#")[1]:r||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){let e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){let e=this.getSchema();if(typeof e!="object")return!1;let r=e[0];return r===3||r===-3||r===4}isUnionSchema(){let e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){let e=this.getSchema();return e===21||e===42}isTimestampSchema(){let e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Li(this.memberTraits)}getOwnTraits(){return Li(this.traits)}getKeySchema(){let[e,r]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!r)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let o=this.getSchema(),n=e?15:o[4]??0;return Gy([n,0],"key")}getValueSchema(){let e=this.getSchema(),[r,o,n]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],i=typeof e=="number"?63&e:e&&typeof e=="object"&&(o||n)?e[3+e[0]]:r?15:void 0;if(i!=null)return Gy([i,0],o?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){let r=this.getSchema();if(this.isStructSchema()&&r[4].includes(e)){let o=r[4].indexOf(e),n=r[5][o];return Gy(BL(n)?n:[n,0],e)}if(this.isDocumentSchema())return Gy([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){let e={};try{for(let[r,o]of this.structIterator())e[r]=o}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(let[e,r]of this.structIterator())if(r.isStreaming()&&r.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");let e=this.getSchema(),r=e[4].length,o=e[Vy.it];if(o&&r===o.length){yield*o;return}o=Array(r);for(let n=0;n<r;++n){let i=e[4][n],s=Gy([e[5][n],0],i);yield o[n]=[i,s]}e[Vy.it]=o}};BL=t=>Array.isArray(t)&&t.length===2,KL=t=>Array.isArray(t)&&t.length>=5});var Af,mJ,hJ,gJ=_(()=>{Xc();Af=class t extends ir{static symbol=Symbol.for("@smithy/sim");schemaRef;symbol=t.symbol},mJ=(t,e,r,o)=>ir.assign(new Af,{name:e,namespace:t,traits:o,schemaRef:r}),hJ=(t,e,r,o)=>ir.assign(new Af,{name:e,namespace:t,traits:r,schemaRef:o})});var yJ,vJ=_(()=>{yJ={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128}});var Gt,wJ=_(()=>{Gt=class t{namespace;schemas;exceptions;static registries=new Map;constructor(e,r=new Map,o=new Map){this.namespace=e,this.schemas=r,this.exceptions=o,t.registries.has(e)||t.registries.set(e,this)}static for(e){return t.registries.get(e)??new t(e)}copyFrom(e){let{schemas:r,exceptions:o}=this;for(let[n,i]of e.schemas)r.has(n)||r.set(n,i);for(let[n,i]of e.exceptions)o.has(n)||o.set(n,i)}register(e,r){let o=this.normalizeShapeId(e);for(let n of[this,t.for(o.split("#")[0])])n.schemas.has(o)||n.schemas.set(o,r)}getSchema(e){let r=this.normalizeShapeId(e);if(!this.schemas.has(r)){if(!e.includes("#")){let o="#"+e,n=[];for(let[i,s]of this.schemas.entries())i.endsWith(o)&&n.push(s);if(n.length===1)return n[0]}throw new Error(`@smithy/core/schema - schema not found for ${r}`)}return this.schemas.get(r)}registerError(e,r){let o=e,n=o[1],i=n+"#"+o[2];r.hasOwnProperty?.("shapeId")||(r.shapeId=i);for(let s of[this,t.for(n)])!s.schemas.has(i)&&!s.exceptions.has(o)&&(s.schemas.set(i,o),s.exceptions.set(o,r))}getErrorCtor(e){let r=e;return this.exceptions.has(r)?this.exceptions.get(r):t.for(r[1]).exceptions.get(r)}getBaseException(){for(let e of this.exceptions.keys())if(Array.isArray(e)){let[,r,o]=e,n=r+"#"+o;if(n.startsWith("smithy.ts.sdk.synthetic.")&&n.endsWith("ServiceException"))return e}}find(e){for(let r of this.schemas.values())if(e(r))return r}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}});var ZL={};qt(ZL,{ErrorSchema:()=>Fy,ListSchema:()=>Uy,MapSchema:()=>Ly,NormalizedSchema:()=>K,OperationSchema:()=>jy,SCHEMA:()=>yJ,Schema:()=>ir,SimpleSchema:()=>Af,StructureSchema:()=>ed,TypeRegistry:()=>Gt,deref:()=>Wo,deserializerMiddlewareOption:()=>qL,error:()=>dJ,getSchemaSerdePlugin:()=>Os,isStaticSchema:()=>KL,list:()=>oJ,map:()=>sJ,op:()=>cJ,operation:()=>If,serializerMiddlewareOption:()=>VL,sim:()=>mJ,simAdapter:()=>hJ,simpleSchemaCacheN:()=>Hy,simpleSchemaCacheS:()=>By,struct:()=>lJ,traitsCache:()=>qy,translateTraits:()=>Li});var Xe=_(()=>{jL();nJ();iJ();aJ();uJ();y$();pJ();fJ();Xc();gJ();GL();vJ();HL();wJ()});function Pf(t,e){if(e==null)return e;let r=K.of(t);if(r.getMergedTraits().sensitive)return WL;if(r.isListSchema()){if(!!r.getValueSchema().getMergedTraits().sensitive)return WL}else if(r.isMapSchema()){if(!!r.getKeySchema().getMergedTraits().sensitive||!!r.getValueSchema().getMergedTraits().sensitive)return WL}else if(r.isStructSchema()&&typeof e=="object"){let o=e,n={};for(let[i,s]of r.structIterator())o[i]!=null&&(n[i]=Pf(s,o[i]));return n}return e}var WL,JL=_(()=>{Xe();WL="***SensitiveInformation***"});var XL,Mn,YL,QL=_(()=>{XL=jt(Cs());m$();JL();Mn=class{middlewareStack=Jc();schema;static classBuilder(){return new YL}resolveMiddlewareWithContext(e,r,o,{middlewareFn:n,clientName:i,commandName:s,inputFilterSensitiveLog:a,outputFilterSensitiveLog:c,smithyContext:u,additionalContext:l,CommandCtor:d}){for(let b of n.bind(this)(d,e,r,o))this.middlewareStack.use(b);let f=e.concat(this.middlewareStack),{logger:p}=r,m=l[XL.SMITHY_CONTEXT_KEY],y={logger:p,clientName:i,commandName:s,inputFilterSensitiveLog:a,outputFilterSensitiveLog:c,...l,[XL.SMITHY_CONTEXT_KEY]:{...m,commandInstance:this,...u,...o?.metricsRecorder===void 0?{}:{metricsRecorder:o.metricsRecorder}}},{requestHandler:w}=r,S=o??{};return S.metricsRecorder&&(S={...S},delete S.metricsRecorder),u.eventStream&&(S={isEventStream:!0,...S}),f.resolve(b=>w.handle(b.request,S),y)}},YL=class{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,r,o={}){return this._smithyContext={service:e,operation:r,...o},this}c(e={}){return this._additionalContext=e,this}n(e,r){return this._clientName=e,this._commandName=r,this}f(e=o=>o,r=o=>o){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=r,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){let e=this,r;return r=class extends Mn{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[o]){super(),this.input=o??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(o,n,i){let s=e._operationSchema,a=s?.[4]??s?.input,c=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(o,n,i,{CommandCtor:r,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?Pf.bind(null,a):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?Pf.bind(null,c):u=>u),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}});var _J,SJ=_(()=>{_J="***SensitiveInformation***"});var Ds,bJ=_(()=>{Ds=(t,e,r)=>{for(let[i,s]of Object.entries(t)){let a=async function(u,l,d){let f=new s(u);if(typeof l=="function")this.send(f,l);else if(typeof d=="function"){if(typeof l!="object")throw new Error(`Expected http options but got ${typeof l}`);this.send(f,l||{},d)}else return this.send(f,l)},c=(i[0].toLowerCase()+i.slice(1)).replace(/Command$/,"");e.prototype[c]=a}let{paginators:o={},waiters:n={}}=r??{};for(let[i,s]of Object.entries(o))e.prototype[i]===void 0&&(e.prototype[i]=function(a={},c,...u){return s({...c,client:this},a,...u)});for(let[i,s]of Object.entries(n))e.prototype[i]===void 0&&(e.prototype[i]=async function(a={},c,...u){let l=c;return typeof c=="number"&&(l={maxWaitTime:c}),s({...l,client:this},a,...u)})}});var Jo,td,ej=_(()=>{Jo=class t extends Error{static shapeId="smithy.ts.sdk.synthetic.nonamespace.client#ServiceException";$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;let r=e;return t.prototype.isPrototypeOf(r)||!!r.$fault&&!!r.$metadata&&(r.$fault==="client"||r.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;let r=e;if(this===t)return t.isInstance(e);if(t.isInstance(e)){if(this.prototype.isPrototypeOf(e))return!0;let o=Object.prototype.hasOwnProperty.call(this,"shapeId")?this.shapeId:void 0,n=!1;if(o){let s=Object.getPrototypeOf(r);for(;s&&s!==Object.prototype;){let a=s.constructor,c=a!==t&&Object.prototype.hasOwnProperty.call(a,"shapeId")?a?.shapeId:void 0;if(c&&(n=!0,c===o))return!0;s=Object.getPrototypeOf(s)}}if(o&&n)return!1;let i=this.name;if(i&&i.length>=6){if(r.name===i)return!0;let s=Object.getPrototypeOf(r);for(;s&&s!==Object.prototype;){let a=s.constructor?.name;if(a&&a!=="Error"&&a===i)return!0;s=Object.getPrototypeOf(s)}}}return!1}},td=(t,e={})=>{Object.entries(e).filter(([,o])=>o!==void 0).forEach(([o,n])=>{(t[o]==null||t[o]==="")&&(t[o]=n)});let r=t.message||t.Message||"UnknownError";return t.message=r,delete t.Message,t}});var tj,xJ,WNe,EJ=_(()=>{ej();tj=({output:t,parsedBody:e,exceptionCtor:r,errorCode:o})=>{let n=WNe(t),i=n.httpStatusCode?n.httpStatusCode+"":void 0,s=new r({name:e?.code||e?.Code||o||i||"UnknownError",$fault:"client",$metadata:n});throw td(s,e)},xJ=t=>({output:e,parsedBody:r,errorCode:o})=>{tj({output:e,parsedBody:r,exceptionCtor:t,errorCode:o})},WNe=t=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]})});var Ns,$J=_(()=>{Ns=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}}});var RJ,zs,IJ=_(()=>{RJ=!1,zs=t=>{t&&!RJ&&parseInt(t.substring(1,t.indexOf(".")))<16&&(RJ=!0)}});var rd,AJ,v$,w$,rj=_(()=>{Re();rd=jt(Cs()),AJ=Object.values(rd.AlgorithmId),v$=t=>{let e=[];for(let r in rd.AlgorithmId){if(!_e(rd.AlgorithmId,r))continue;let o=rd.AlgorithmId[r];t[o]!==void 0&&e.push({algorithmId:()=>o,checksumConstructor:()=>t[o]})}for(let[r,o]of Object.entries(t.checksumAlgorithms??{}))e.push({algorithmId:()=>r,checksumConstructor:()=>o});return{addChecksumAlgorithm(r){t.checksumAlgorithms=t.checksumAlgorithms??{};let o=r.algorithmId(),n=r.checksumConstructor();AJ.includes(o)?t.checksumAlgorithms[o.toUpperCase()]=n:t.checksumAlgorithms[o]=n,e.push(r)},checksumAlgorithms(){return e}}},w$=t=>{let e={};return t.checksumAlgorithms().forEach(r=>{let o=r.algorithmId();AJ.includes(o)&&(e[o]=r.checksumConstructor())}),e}});var _$,S$,nj=_(()=>{_$=t=>({setRetryStrategy(e){t.retryStrategy=e},retryStrategy(){return t.retryStrategy}}),S$=t=>{let e={};return e.retryStrategy=t.retryStrategy(),e}});var ji,PJ,Ms,kJ=_(()=>{rj();nj();ji=t=>Object.assign(v$(t),_$(t)),PJ=ji,Ms=t=>Object.assign(w$(t),S$(t))});var TJ,CJ=_(()=>{TJ=t=>Array.isArray(t)?t:[t]});var nd,OJ=_(()=>{Re();nd=t=>{let e="#text";for(let r in t)_e(t,r)&&(t[r][e]!==void 0?t[r]=t[r][e]:typeof t[r]=="object"&&t[r]!==null&&(t[r]=nd(t[r])));return t}});var DJ,NJ=_(()=>{DJ=t=>t!=null});var to,zJ=_(()=>{to=class{trace(){}debug(){}info(){}warn(){}error(){}}});function oj(t,e,r){let o,n,i;if(typeof e>"u"&&typeof r>"u")o={},i=t;else{if(o=t,typeof e=="function")return n=e,i=r,JNe(o,n,i);i=e}for(let s in i)if(_e(i,s)){if(!Array.isArray(i[s])){o[s]=i[s];continue}LJ(o,null,i,s)}return o}var MJ,UJ,JNe,LJ,XNe,YNe,jJ=_(()=>{Re();MJ=t=>{let e={};for(let[r,o]of Object.entries(t||{}))e[r]=[,o];return e},UJ=(t,e)=>{let r={};for(let o in e)_e(e,o)&&LJ(r,t,e,o);return r},JNe=(t,e,r)=>oj(t,Object.entries(r).reduce((o,[n,i])=>(Array.isArray(i)?o[n]=i:typeof i=="function"?o[n]=[e,i()]:o[n]=[e,i],o),{})),LJ=(t,e,r,o)=>{if(e!==null){let s=r[o];typeof s=="function"&&(s=[,s]);let[a=XNe,c=YNe,u=o]=s;(typeof a=="function"&&a(e[u])||typeof a!="function"&&a)&&(t[o]=c(e[u]));return}let[n,i]=r[o];if(typeof i=="function"){let s,a=n===void 0&&(s=i())!=null,c=typeof n=="function"&&!!n(void 0)||typeof n!="function"&&!!n;a?t[o]=s:c&&(t[o]=i())}else{let s=n===void 0&&i!=null,a=typeof n=="function"&&!!n(i)||typeof n!="function"&&!!n;(s||a)&&(t[o]=i)}},XNe=t=>t!=null,YNe=t=>t});var FJ,qJ,VJ=_(()=>{FJ=t=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},qJ=t=>t.toISOString().replace(".000Z","Z")});var b$,GJ=_(()=>{Re();b$=t=>{if(t==null)return{};if(Array.isArray(t))return t.filter(e=>e!=null).map(b$);if(typeof t=="object"){let e={};for(let r in t)_e(t,r)&&t[r]!=null&&(e[r]=b$(t[r]));return e}return t}});function Us(t,e,r,o){return function(i,s,a,c,u={}){let l=Object.assign({},t,i);return Mn.classBuilder().ep(l).m(function(d,f,p,m){let y=s.call(this,d,f,p,m);return y.unshift(o(p,d.getEndpointParameterInstructions())),y}).s(e,a,u).n(r,a.charAt(0).toUpperCase()+a.slice(1)+"Command").sc(c).build()}}var HJ=_(()=>{QL()});var kf={};qt(kf,{AlgorithmId:()=>rd.AlgorithmId,Client:()=>hn,Command:()=>Mn,NoOpLogger:()=>to,SENSITIVE_STRING:()=>_J,ServiceException:()=>Jo,WaiterState:()=>Eo,_json:()=>b$,checkExceptions:()=>G8,constructStack:()=>Jc,convertMap:()=>MJ,createAggregatedClient:()=>Ds,createWaiter:()=>J8,decorateServiceException:()=>td,emitWarningIfUnsupportedVersion:()=>zs,getArrayIfSingleItem:()=>TJ,getChecksumConfiguration:()=>v$,getDefaultClientConfiguration:()=>PJ,getDefaultExtensionConfiguration:()=>ji,getRetryConfiguration:()=>_$,getSmithyContext:()=>Vt,getValueFromTextNode:()=>nd,invalidFunction:()=>U8,invalidProvider:()=>j8,isSerializableHeaderValue:()=>DJ,loadConfigsForDefaultMode:()=>Ns,makeBuilder:()=>Us,map:()=>oj,normalizeProvider:()=>Ut,resolveChecksumRuntimeConfig:()=>w$,resolveDefaultRuntimeConfig:()=>Ms,resolveRetryRuntimeConfig:()=>S$,schemaLogFilter:()=>Pf,serializeDateTime:()=>qJ,serializeFloat:()=>FJ,take:()=>UJ,throwDefaultError:()=>tj,waiterServiceDefaults:()=>h$,withBaseException:()=>xJ});var ge=_(()=>{m$();Re();Re();L8();F8();X8();g$();Y8();QL();SJ();bJ();EJ();$J();IJ();ej();kJ();rj();nj();CJ();OJ();NJ();zJ();jJ();JL();VJ();GJ();HJ()});var x$,ij=_(()=>{x$=t=>typeof ArrayBuffer=="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]"});var Fi,Yc,Qc=_(()=>{ij();Fi=(t,e=0,r=t.byteLength-e)=>{if(!x$(t))throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,e,r)},Yc=(t,e)=>{if(typeof t!="string")throw new TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return e?Buffer.from(t,e):Buffer.from(t)}});var QNe,sr,BJ=_(()=>{Qc();QNe=/^[A-Za-z0-9+/]*={0,2}$/,sr=t=>{if(t.length*3%4!==0)throw new TypeError("Incorrect padding on base64 string.");if(!QNe.exec(t))throw new TypeError("Invalid base64 string.");let e=Yc(t,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}});var xr,E$=_(()=>{Qc();xr=t=>{let e=Yc(t,"utf8");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT)}});var Ht,sj=_(()=>{Qc();E$();Ht=t=>{let e;if(typeof t=="string"?e=xr(t):e=t,typeof e!="object"||typeof e.byteOffset!="number"||typeof e.byteLength!="number")throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Fi(e.buffer,e.byteOffset,e.byteLength).toString("base64")}});function KJ(t,e,r,o){return class $$ extends Uint8Array{static fromString(i,s="utf-8"){if(typeof i=="string")return s==="base64"?$$.mutate(o(i)):$$.mutate(e(i));throw new Error(`Unsupported conversion from ${typeof i} to Uint8ArrayBlobAdapter.`)}static mutate(i){return Object.setPrototypeOf(i,$$.prototype),i}transformToString(i="utf-8"){return i==="base64"?r(this):t(this)}}}var ZJ=_(()=>{});var nr,WJ=_(()=>{Qc();nr=t=>{if(typeof t=="string")return t;if(typeof t!="object"||typeof t.byteOffset!="number"||typeof t.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Fi(t.buffer,t.byteOffset,t.byteLength).toString("utf8")}});function JJ(t){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{let e=new Uint8Array(16);return t(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,gn[e[0]]+gn[e[1]]+gn[e[2]]+gn[e[3]]+"-"+gn[e[4]]+gn[e[5]]+"-"+gn[e[6]]+gn[e[7]]+"-"+gn[e[8]]+gn[e[9]]+"-"+gn[e[10]]+gn[e[11]]+gn[e[12]]+gn[e[13]]+gn[e[14]]+gn[e[15]]}}var gn,XJ=_(()=>{gn=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"))});var YJ,QJ=_(()=>{YJ=(t,e,r=o=>o)=>t});var e7,t7,Tf,e1e,Ky,Cf,r7,R$,I$,A$,aj,t1e,n7,cj,o7,k$,Zy,i7,T$,r1e,Df,C$,s7,a7,c7,u7,uj,l7,d7,eu,O$,P$,Of,lj=_(()=>{Re();e7=t=>{switch(t){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${t}"`)}},t7=t=>{if(t!=null){if(typeof t=="number"){if((t===0||t===1)&&Of.warn(P$(`Expected boolean, got ${typeof t}: ${t}`)),t===0)return!1;if(t===1)return!0}if(typeof t=="string"){let e=t.toLowerCase();if((e==="false"||e==="true")&&Of.warn(P$(`Expected boolean, got ${typeof t}: ${t}`)),e==="false")return!1;if(e==="true")return!0}if(typeof t=="boolean")return t;throw new TypeError(`Expected boolean, got ${typeof t}: ${t}`)}},Tf=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Of.warn(P$(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},e1e=Math.ceil(2**127*(2-2**-23)),Ky=t=>{let e=Tf(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>e1e)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},Cf=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},r7=Cf,R$=t=>aj(t,32),I$=t=>aj(t,16),A$=t=>aj(t,8),aj=(t,e)=>{let r=Cf(t);if(r!==void 0&&t1e(r,e)!==r)throw new TypeError(`Expected ${e}-bit integer, got ${t}`);return r},t1e=(t,e)=>{switch(e){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},n7=(t,e)=>{if(t==null)throw e?new TypeError(`Expected a non-null value for ${e}`):new TypeError("Expected a non-null value");return t},cj=t=>{if(t==null)return;if(typeof t=="object"&&!Array.isArray(t))return t;let e=Array.isArray(t)?"array":typeof t;throw new TypeError(`Expected object, got ${e}: ${t}`)},o7=t=>{if(t!=null){if(typeof t=="string")return t;if(["boolean","number","bigint"].includes(typeof t))return Of.warn(P$(`Expected string, got ${typeof t}: ${t}`)),String(t);throw new TypeError(`Expected string, got ${typeof t}: ${t}`)}},k$=t=>{if(t==null)return;let e=cj(t),r=[];for(let o in e)_e(e,o)&&e[o]!=null&&r.push(o);if(r.length===0)throw new TypeError("Unions must have exactly one non-null member. None were found.");if(r.length>1)throw new TypeError(`Unions must have exactly one non-null member. Keys ${r} were not null.`);return e},Zy=t=>Tf(typeof t=="string"?Df(t):t),i7=Zy,T$=t=>Ky(typeof t=="string"?Df(t):t),r1e=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Df=t=>{let e=t.match(r1e);if(e===null||e[0].length!==t.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(t)},C$=t=>typeof t=="string"?u7(t):Tf(t),s7=C$,a7=C$,c7=t=>typeof t=="string"?u7(t):Ky(t),u7=t=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw new Error(`Unable to parse float value: ${t}`)}},uj=t=>Cf(typeof t=="string"?Df(t):t),l7=uj,d7=t=>R$(typeof t=="string"?Df(t):t),eu=t=>I$(typeof t=="string"?Df(t):t),O$=t=>A$(typeof t=="string"?Df(t):t),P$=t=>String(new TypeError(t).stack||t).split(`
|
|
12
12
|
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
|
|
13
13
|
`),Of={warn:console.warn}});function $o(t){let e=t.getUTCFullYear(),r=t.getUTCMonth(),o=t.getUTCDay(),n=t.getUTCDate(),i=t.getUTCHours(),s=t.getUTCMinutes(),a=t.getUTCSeconds(),c=n<10?`0${n}`:`${n}`,u=i<10?`0${i}`:`${i}`,l=s<10?`0${s}`:`${s}`,d=a<10?`0${a}`:`${a}`;return`${n1e[o]}, ${c} ${pj[r]} ${e} ${u}:${l}:${d} GMT`}var n1e,pj,o1e,p7,i1e,zf,s1e,a1e,c1e,tu,Mf,Wy,u1e,l1e,d1e,dj,p1e,f1e,m1e,Ls,h1e,g1e,Nf,f7=_(()=>{lj();n1e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],pj=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];o1e=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),p7=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=o1e.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,o,n,i,s,a,c,u]=e,l=eu(Nf(o)),d=Ls(n,"month",1,12),f=Ls(i,"day",1,31);return Wy(l,d,f,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u})},i1e=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),zf=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=i1e.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,o,n,i,s,a,c,u,l]=e,d=eu(Nf(o)),f=Ls(n,"month",1,12),p=Ls(i,"day",1,31),m=Wy(d,f,p,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u});return l.toUpperCase()!="Z"&&m.setTime(m.getTime()-g1e(l)),m},s1e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),a1e=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),c1e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),tu=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=s1e.exec(t);if(e){let[r,o,n,i,s,a,c,u]=e;return Wy(eu(Nf(i)),dj(n),Ls(o,"day",1,31),{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u})}if(e=a1e.exec(t),e){let[r,o,n,i,s,a,c,u]=e;return d1e(Wy(u1e(i),dj(n),Ls(o,"day",1,31),{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u}))}if(e=c1e.exec(t),e){let[r,o,n,i,s,a,c,u]=e;return Wy(eu(Nf(u)),dj(o),Ls(n.trimLeft(),"day",1,31),{hours:i,minutes:s,seconds:a,fractionalMilliseconds:c})}throw new TypeError("Invalid RFC-7231 date-time value")},Mf=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=Zy(t);else if(typeof t=="object"&&t.tag===1)e=t.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Wy=(t,e,r,o)=>{let n=e-1;return f1e(t,n,r),new Date(Date.UTC(t,n,r,Ls(o.hours,"hour",0,23),Ls(o.minutes,"minute",0,59),Ls(o.seconds,"seconds",0,60),h1e(o.fractionalMilliseconds)))},u1e=t=>{let e=new Date().getUTCFullYear(),r=Math.floor(e/100)*100+eu(Nf(t));return r<e?r+100:r},l1e=50*365*24*60*60*1e3,d1e=t=>t.getTime()-new Date().getTime()>l1e?new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())):t,dj=t=>{let e=pj.indexOf(t);if(e<0)throw new TypeError(`Invalid month: ${t}`);return e+1},p1e=[31,28,31,30,31,30,31,31,30,31,30,31],f1e=(t,e,r)=>{let o=p1e[e];if(e===1&&m1e(t)&&(o=29),r>o)throw new TypeError(`Invalid day for ${pj[e]} in ${t}: ${r}`)},m1e=t=>t%4===0&&(t%100!==0||t%400===0),Ls=(t,e,r,o)=>{let n=O$(Nf(t));if(n<r||n>o)throw new TypeError(`${e} must be between ${r} and ${o}, inclusive`);return n},h1e=t=>t==null?0:T$("0."+t)*1e3,g1e=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);let o=Number(t.substring(1,3)),n=Number(t.substring(4,6));return r*(o*60+n)*60*1e3},Nf=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var mr,m7=_(()=>{mr=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};mr.from=t=>t&&typeof t=="object"&&(t instanceof mr||"deserializeJSON"in t)?t:typeof t=="string"||Object.getPrototypeOf(t)===String.prototype?mr(String(t)):mr(JSON.stringify(t));mr.fromObject=mr.from});function D$(t){return(t.includes(",")||t.includes('"'))&&(t=`"${t.replace(/"/g,'\\"')}"`),t}var h7=_(()=>{});function Ha(t,e,r){let o=Number(t);if(o<e||o>r)throw new Error(`Value ${o} out of range [${e}, ${r}]`)}var fj,mj,hj,g7,y7,y1e,v1e,w1e,_1e,S1e,ru,N$,z$,v7=_(()=>{fj="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",mj="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",hj="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",g7="(\\d?\\d)",y7="(\\d{4})",y1e=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),v1e=new RegExp(`^${fj}, ${g7} ${mj} ${y7} ${hj} GMT$`),w1e=new RegExp(`^${fj}, ${g7}-${mj}-(\\d\\d) ${hj} GMT$`),_1e=new RegExp(`^${fj} ${mj} ( [1-9]|\\d\\d) ${hj} ${y7}$`),S1e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ru=t=>{if(t==null)return;let e=NaN;if(typeof t=="number")e=t;else if(typeof t=="string"){if(!/^-?\d*\.?\d+$/.test(t))throw new TypeError("parseEpochTimestamp - numeric string invalid.");e=Number.parseFloat(t)}else typeof t=="object"&&t.tag===1&&(e=t.value);if(isNaN(e)||Math.abs(e)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(e*1e3))},N$=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC3339 timestamps must be strings");let e=y1e.exec(t);if(!e)throw new TypeError(`Invalid RFC3339 timestamp format ${t}`);let[,r,o,n,i,s,a,,c,u]=e;Ha(o,1,12),Ha(n,1,31),Ha(i,0,23),Ha(s,0,59),Ha(a,0,60);let l=new Date(Date.UTC(Number(r),Number(o)-1,Number(n),Number(i),Number(s),Number(a),Number(c)?Math.round(parseFloat(`0.${c}`)*1e3):0));if(l.setUTCFullYear(Number(r)),u.toUpperCase()!="Z"){let[,d,f,p]=/([+-])(\d\d):(\d\d)/.exec(u)||[void 0,"+",0,0],m=d==="-"?1:-1;l.setTime(l.getTime()+m*(Number(f)*60*60*1e3+Number(p)*60*1e3))}return l},z$=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC7231 timestamps must be strings.");let e,r,o,n,i,s,a,c;if((c=v1e.exec(t))?[,e,r,o,n,i,s,a]=c:(c=w1e.exec(t))?([,e,r,o,n,i,s,a]=c,o=(Number(o)+1900).toString()):(c=_1e.exec(t))&&([,r,e,n,i,s,a,o]=c),o&&s){let u=Date.UTC(Number(o),S1e.indexOf(r),Number(e),Number(n),Number(i),Number(s),a?Math.round(parseFloat(`0.${a}`)*1e3):0);Ha(e,1,31),Ha(n,0,23),Ha(i,0,59),Ha(s,0,60);let l=new Date(u);return l.setUTCFullYear(Number(o)),l}throw new TypeError(`Invalid RFC7231 date-time value ${t}.`)}});function M$(t,e,r){if(r<=0||!Number.isInteger(r))throw new Error("Invalid number of delimiters ("+r+") for splitEvery.");let o=t.split(e);if(r===1)return o;let n=[],i="";for(let s=0;s<o.length;s++)i===""?i=o[s]:i+=e+o[s],(s+1)%r===0&&(n.push(i),i="");return i!==""&&n.push(i),n}var w7=_(()=>{});var Uf,_7=_(()=>{Uf=t=>{let e=t.length,r=[],o=!1,n,i=0;for(let s=0;s<e;++s){let a=t[s];switch(a){case'"':n!=="\\"&&(o=!o);break;case",":o||(r.push(t.slice(i,s)),i=s+1);break;default:}n=a}return r.push(t.slice(i)),r.map(s=>{s=s.trim();let a=s.length;return a<2?s:(s[0]==='"'&&s[a-1]==='"'&&(s=s.slice(1,a-1)),s.replace(/\\"/g,'"'))})}});function U$(t){return new Ye(String(t),"bigDecimal")}var S7,Ye,b7=_(()=>{S7=/^-?((0|[1-9]\d*)(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/,Ye=class t{string;type;constructor(e,r){if(this.string=e,this.type=r,!S7.test(e))throw new Error(`@smithy/core/serde - NumericValue string must conform to the Smithy bigDecimal format. Received: "${e}"`)}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;let r=e;return t.prototype.isPrototypeOf(e)||r.type==="bigDecimal"&&S7.test(r.string)}}});function L$(t){if(t.length%2!==0)throw new Error("Hex encoded strings must have an even number length");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2){let o=t.slice(r,r+2).toLowerCase();if(o in gj)e[r/2]=gj[o];else throw new Error(`Cannot decode unrecognized sequence ${o} as hexadecimal`)}return e}function Xo(t){let e="";for(let r=0;r<t.byteLength;r++)e+=x7[t[r]];return e}var x7,gj,yj=_(()=>{x7={},gj={};for(let t=0;t<256;t++){let e=t.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),x7[t]=e,gj[e]=t}});import{ReadStream as b1e,fstatSync as x1e,lstatSync as E1e}from"node:fs";var js,E7=_(()=>{js=t=>{if(!t)return 0;if(typeof t=="string")return Buffer.byteLength(t);if(typeof t.byteLength=="number")return t.byteLength;if(typeof t.size=="number")return t.size;if(typeof t.start=="number"&&typeof t.end=="number")return t.end+1-t.start;if(t instanceof b1e){if(t.path!=null)return E1e(t.path).size;if(typeof t.fd=="number")return x1e(t.fd).size}throw new Error(`Body Length computation failed for ${t}`)}});var Un,vj=_(()=>{E$();Un=t=>t instanceof Uint8Array?t:typeof t=="string"?xr(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)});function Fs(t,e){if(e===void 0){e=0;for(let n of t)e+=n.byteLength}let r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.byteLength;return r}var Jy=_(()=>{});var j$,wj,_j=_(()=>{Re();j$=(t,e)=>(r,o)=>async n=>{let{response:i}=await r(n);try{let s=await e(i,t);return{response:i,output:s}}catch(s){if(Object.defineProperty(s,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in s)){let a="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{s.message+=`
|
|
14
|
-
`+a}catch{!o.logger||o.logger?.constructor?.name==="NoOpLogger"?console.warn(a):o.logger?.warn?.(a)}typeof s.$responseBodyText<"u"&&s.$response&&(s.$response.body=s.$responseBodyText);try{if(kr.isInstance(i)){let{headers:c={}}=i,u=Object.entries(c);s.$metadata={httpStatusCode:i.statusCode,requestId:wj(/^x-[\w-]+-request-?id$/,u),extendedRequestId:wj(/^x-[\w-]+-id-2$/,u),cfId:wj(/^x-[\w-]+-cf-id$/,u)}}}catch{}}throw s}},wj=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var Ro,Xy=_(()=>{Ro=class t extends Error{name="ProviderError";tryNextLink;constructor(e,r=!0){let o,n=!0;typeof r=="boolean"?(o=void 0,n=r):r!=null&&typeof r=="object"&&(o=r.logger,n=r.tryNextLink??!0),super(e),this.tryNextLink=n,Object.setPrototypeOf(this,t.prototype),o?.debug?.(`@smithy/property-provider ${n?"->":"(!)"} ${e}`)}static from(e,r=!0){return Object.assign(new this(e.message,r),e)}}});var nu,F$=_(()=>{Xy();nu=class t extends Ro{name="CredentialsProviderError";constructor(e,r=!0){super(e,r),Object.setPrototypeOf(this,t.prototype)}}});var q$,$7=_(()=>{Xy();q$=class t extends Ro{name="TokenProviderError";constructor(e,r=!0){super(e,r),Object.setPrototypeOf(this,t.prototype)}}});var V$,Sj=_(()=>{Xy();V$=(...t)=>async()=>{if(t.length===0)throw new Ro("No providers in chain");let e;for(let r of t)try{return await r()}catch(o){if(e=o,o?.tryNextLink)continue;throw o}throw e}});var G$,bj=_(()=>{G$=t=>()=>Promise.resolve(t)});var Lf,H$=_(()=>{Lf=(t,e,r)=>{let o,n,i,s=!1,a=async()=>{n||(n=t());try{o=await n,i=!0,s=!1}finally{n=void 0}return o};return e===void 0?async c=>((!i||c?.forceRefresh)&&(o=await a()),o):async c=>((!i||c?.forceRefresh)&&(o=await a()),s?o:r&&!r(o)?(s=!0,o):(e(o)&&await a(),o))}});var Tr,B$=_(()=>{Tr=(t,e,r)=>{if(e in t){if(t[e]==="true")return!0;if(t[e]==="false")return!1;throw new Error(`Cannot load ${r} "${e}". Expected "true" or "false", got ${t[e]}.`)}}});var R7,I7=_(()=>{R7=(t,e,r)=>{if(!(e in t))return;let o=parseInt(t[e],10);if(Number.isNaN(o))throw new TypeError(`Cannot load ${r} '${e}'. Expected number, got '${t[e]}'.`);return o}});var hr,K$=_(()=>{(function(t){t.ENV="env",t.CONFIG="shared config entry"})(hr||(hr={}))});import{homedir as $1e}from"node:os";import{sep as R1e}from"node:path";var xj,I1e,qs,jf=_(()=>{xj={},I1e=()=>process&&process.geteuid?`${process.geteuid()}`:"DEFAULT",qs=()=>{let{HOME:t,USERPROFILE:e,HOMEPATH:r,HOMEDRIVE:o=`C:${R1e}`}=process.env;if(t)return t;if(e)return e;if(r)return`${o}${r}`;let n=I1e();return xj[n]||(xj[n]=$1e()),xj[n]}});var Ej,$j,Z$,Rj=_(()=>{Ej="AWS_PROFILE",$j="default",Z$=t=>t.profile||process.env[Ej]||$j});import{createHash as A1e}from"node:crypto";import{join as P1e}from"node:path";var W$,Ij=_(()=>{jf();W$=t=>{let r=A1e("sha1").update(t).digest("hex");return P1e(qs(),".aws","sso","cache",`${r}.json`)}});import{readFile as k1e}from"node:fs/promises";var Yy,A7,Aj=_(()=>{Ij();Yy={},A7=async t=>{if(Yy[t])return Yy[t];let e=W$(t),r=await k1e(e,"utf8");return JSON.parse(r)}});var Vs,P7=_(()=>{Vs="."});var Pj,k7,T7=_(()=>{Pj=jt(Cs()),k7=t=>Object.entries(t).filter(([e])=>{let r=e.indexOf(".");return r===-1?!1:Object.values(Pj.IniSectionType).includes(e.substring(0,r))}).reduce((e,[r,o])=>{let n=r.indexOf("."),i=r.substring(0,n)===Pj.IniSectionType.PROFILE?r.substring(n+1):r;return e[i]=o,e},{...t.default&&{default:t.default}})});import{join as T1e}from"node:path";var C1e,J$,kj=_(()=>{jf();C1e="AWS_CONFIG_FILE",J$=()=>process.env[C1e]||T1e(qs(),".aws","config")});import{join as O1e}from"node:path";var D1e,C7,O7=_(()=>{jf();D1e="AWS_SHARED_CREDENTIALS_FILE",C7=()=>process.env[D1e]||O1e(qs(),".aws","credentials")});var D7,N1e,z1e,Qy,Tj=_(()=>{D7=jt(Cs()),N1e=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,z1e=["__proto__","profile __proto__"],Qy=t=>{let e={},r,o;for(let n of t.split(/\r?\n/)){let i=n.split(/(^|\s)[;#]/)[0].trim();if(i[0]==="["&&i[i.length-1]==="]"){r=void 0,o=void 0;let a=i.substring(1,i.length-1),c=N1e.exec(a);if(c){let[,u,,l]=c;Object.values(D7.IniSectionType).includes(u)&&(r=[u,l].join("."))}else r=a;if(z1e.includes(a))throw new Error(`Found invalid profile name "${a}"`)}else if(r){let a=i.indexOf("=");if(![0,-1].includes(a)){let[c,u]=[i.substring(0,a).trim(),i.substring(a+1).trim()];if(u==="")o=c;else{o&&n.trimStart()===n&&(o=void 0),e[r]=e[r]||{};let l=o?[o,c].join("."):c;e[r][l]=u}}}}return e}});import{readFile as M1e}from"node:fs/promises";var Cj,ev,od,tv=_(()=>{Cj={},ev={},od=(t,e)=>ev[t]!==void 0?ev[t]:((!Cj[t]||e?.ignoreCache)&&(Cj[t]=M1e(t,"utf8")),Cj[t])});import{join as N7}from"node:path";var z7,Ff,X$=_(()=>{T7();kj();O7();jf();Tj();tv();z7=()=>({}),Ff=async(t={})=>{let{filepath:e=C7(),configFilepath:r=J$()}=t,o=qs(),n="~/",i=e;e.startsWith(n)&&(i=N7(o,e.slice(2)));let s=r;r.startsWith(n)&&(s=N7(o,r.slice(2)));let a=await Promise.all([od(s,{ignoreCache:t.ignoreCache}).then(Qy).then(k7).catch(z7),od(i,{ignoreCache:t.ignoreCache}).then(Qy).catch(z7)]);return{configFile:a[0],credentialsFile:a[1]}}});var M7,U7,L7=_(()=>{M7=jt(Cs()),U7=t=>Object.entries(t).filter(([e])=>e.startsWith(M7.IniSectionType.SSO_SESSION+".")).reduce((e,[r,o])=>({...e,[r.substring(r.indexOf(".")+1)]:o}),{})});var U1e,j7,F7=_(()=>{kj();L7();Tj();tv();U1e=()=>({}),j7=async(t={})=>od(t.configFilepath??J$()).then(Qy).then(U7).catch(U1e)});var q7,V7=_(()=>{q7=(...t)=>{let e={};for(let r of t)for(let[o,n]of Object.entries(r))e[o]!==void 0?Object.assign(e[o],n):e[o]=n;return e}});var G7,H7=_(()=>{X$();V7();G7=async t=>{let e=await Ff(t);return q7(e.configFile,e.credentialsFile)}});var B7,K7=_(()=>{Aj();tv();B7={getFileRecord(){return ev},interceptFile(t,e){ev[t]=Promise.resolve(e)},getTokenRecord(){return Yy},interceptToken(t,e){Yy[t]=e}}});function Y$(t){try{let e=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return e.delete("CONFIG"),e.delete("CONFIG_PREFIX_SEPARATOR"),e.delete("ENV"),[...e].join(", ")}catch{return t}}var Oj=_(()=>{});var Z7,W7=_(()=>{F$();Oj();Z7=(t,e)=>async()=>{try{let r=t(process.env,e);if(r===void 0)throw new Error;return r}catch(r){throw new nu(r.message||`Not found in ENV: ${Y$(t.toString())}`,{logger:e?.logger})}}});var J7,X7=_(()=>{F$();Rj();X$();Oj();J7=(t,{preferredFile:e="config",...r}={})=>async()=>{let o=Z$(r),{configFile:n,credentialsFile:i}=await Ff(r),s=i[o]||{},a=n[o]||{},c=e==="config"?{...s,...a}:{...a,...s};try{let l=t(c,e==="config"?n:i);if(l===void 0)throw new Error;return l}catch(u){throw new nu(u.message||`Not found in config files w/ profile [${o}]: ${Y$(t.toString())}`,{logger:r.logger})}}});var L1e,Q$,Dj=_(()=>{bj();L1e=t=>typeof t=="function",Q$=t=>L1e(t)?async()=>await t():G$(t)});var Ee,Nj=_(()=>{Sj();H$();W7();X7();Dj();Ee=({environmentVariableSelector:t,configFileSelector:e,default:r},o={})=>{let{signingName:n,logger:i}=o;return Lf(V$(Z7(t,{signingName:n,logger:i}),J7(e,o),Q$(r)))}});var eR,tR,Y7,Gs,Q7,eX=_(()=>{B$();K$();eR="AWS_USE_DUALSTACK_ENDPOINT",tR="use_dualstack_endpoint",Y7=!1,Gs={environmentVariableSelector:t=>Tr(t,eR,hr.ENV),configFileSelector:t=>Tr(t,tR,hr.CONFIG),default:!1},Q7={environmentVariableSelector:t=>Tr(t,eR,hr.ENV),configFileSelector:t=>Tr(t,tR,hr.CONFIG),default:void 0}});var rR,nR,tX,Hs,rX,nX=_(()=>{B$();K$();rR="AWS_USE_FIPS_ENDPOINT",nR="use_fips_endpoint",tX=!1,Hs={environmentVariableSelector:t=>Tr(t,rR,hr.ENV),configFileSelector:t=>Tr(t,nR,hr.CONFIG),default:!1},rX={environmentVariableSelector:t=>Tr(t,rR,hr.ENV),configFileSelector:t=>Tr(t,nR,hr.CONFIG),default:void 0}});var oX,iX=_(()=>{ge();oX=t=>{let{tls:e,endpoint:r,urlParser:o,useDualstackEndpoint:n}=t;return Object.assign(t,{tls:e??!0,endpoint:Ut(typeof r=="string"?o(r):r),isCustomEndpoint:!0,useDualstackEndpoint:Ut(n??!1)})}});var sX,aX=_(()=>{sX=async t=>{let{tls:e=!0}=t,r=await t.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(r))throw new Error("Invalid region in client config");let n=await t.useDualstackEndpoint(),i=await t.useFipsEndpoint(),{hostname:s}=await t.regionInfoProvider(r,{useDualstackEndpoint:n,useFipsEndpoint:i})??{};if(!s)throw new Error("Cannot resolve hostname from client config");return t.urlParser(`${e?"https:":"http:"}//${s}`)}});var cX,uX=_(()=>{ge();aX();cX=t=>{let e=Ut(t.useDualstackEndpoint??!1),{endpoint:r,useFipsEndpoint:o,urlParser:n,tls:i}=t;return Object.assign(t,{tls:i??!0,endpoint:r?Ut(typeof r=="string"?n(r):r):()=>sX({...t,useDualstackEndpoint:e,useFipsEndpoint:o}),isCustomEndpoint:!!r,useDualstackEndpoint:e})}});var lX,zj,Mj,dX,pX,fX,mX,hX,gX,Uj=_(()=>{lX="AWS_EXECUTION_ENV",zj="AWS_REGION",Mj="AWS_DEFAULT_REGION",dX="AWS_EC2_METADATA_DISABLED",pX=["in-region","cross-region","mobile","standard","legacy"],fX="/latest/meta-data/placement/region",mX="/latest/api/token",hX="x-aws-ec2-metadata-token",gX="x-aws-ec2-metadata-token-ttl-seconds"});var yX,j1e,_X,oR,vX,F1e,wX,Lj=_(()=>{Uj();yX=1e3,j1e=6e4,_X=0,oR=async()=>{if(!process.env[dX]&&!(Date.now()<_X))try{let t=F1e(),e=(await wX({...t,path:mX,method:"PUT",headers:{[gX]:"21600"}})).toString();return(await wX({...t,path:fX,method:"GET",headers:{[hX]:e}})).toString().trim()||vX()}catch{return vX()}},vX=()=>{_X=Date.now()+j1e},F1e=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let e=new URL(t);return{hostname:e.hostname.replace(/^\[(.+)]$/,"$1"),port:e.port?Number(e.port):void 0}}return process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6"?{hostname:"fd00:ec2::254"}:{hostname:"169.254.169.254"}},wX=async t=>{let{request:e}=await import("node:http");return new Promise((r,o)=>{let n=e({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:yX,signal:AbortSignal.timeout(yX)});n.on("error",i=>{o(i),n.destroy()}),n.on("timeout",()=>{o(new Error("TimeoutError from instance metadata service")),n.destroy()}),n.on("response",i=>{let{statusCode:s=400}=i;if(s<200||s>=300){o(Object.assign(new Error("Error response received from instance metadata service"),{statusCode:s})),n.destroy();return}let a=[];i.on("data",c=>a.push(c)),i.on("end",()=>{r(Buffer.concat(a)),n.destroy()})}),n.end()})}});var qf,Vf,Br,Ln,jj=_(()=>{Lj();qf="AWS_REGION",Vf="region",Br={environmentVariableSelector:t=>t[qf],configFileSelector:t=>t[Vf],default:async()=>{let t=await oR();if(t)return t;throw new Error("Region is missing")}},Ln={preferredFile:"credentials"}});var SX,bX,xX=_(()=>{Re();SX=new Set,bX=(t,e=Ui)=>{if(!SX.has(t)&&!e(t))if(t==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${t}" is not a valid hostname component.`);else SX.add(t)}});var iR,Fj=_(()=>{iR=t=>typeof t=="string"&&(t.startsWith("fips-")||t.endsWith("-fips"))});var EX,$X=_(()=>{Fj();EX=t=>iR(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t});var Io,RX=_(()=>{xX();$X();Fj();Io=t=>{let{region:e,useFipsEndpoint:r}=t;if(!e)throw new Error("Region is missing");return Object.assign(t,{region:async()=>{let o=typeof e=="function"?await e():e,n=EX(o);return bX(n),n},useFipsEndpoint:async()=>{let o=typeof e=="string"?e:await e();return iR(o)?!0:typeof r!="function"?Promise.resolve(!!r):r()}})}});var qj,IX=_(()=>{qj=(t=[],{useFipsEndpoint:e,useDualstackEndpoint:r})=>t.find(({tags:o})=>e===o.includes("fips")&&r===o.includes("dualstack"))?.hostname});var AX,PX=_(()=>{AX=(t,{regionHostname:e,partitionHostname:r})=>e||(r?r.replace("{region}",t):void 0)});var kX,TX=_(()=>{kX=(t,{partitionHash:e})=>Object.keys(e||{}).find(r=>e[r].regions.includes(t))??"aws"});var CX,OX=_(()=>{CX=(t,{signingRegion:e,regionRegex:r,useFipsEndpoint:o})=>{if(e)return e;if(o){let n=r.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),i=t.match(n);if(i)return i[0].slice(1,-1)}}});var DX,NX=_(()=>{IX();PX();TX();OX();DX=(t,{useFipsEndpoint:e=!1,useDualstackEndpoint:r=!1,signingService:o,regionHash:n,partitionHash:i})=>{let s=kX(t,{partitionHash:i}),a=t in n?t:i[s]?.endpoint??t,c={useFipsEndpoint:e,useDualstackEndpoint:r},u=qj(n[a]?.variants,c),l=qj(i[s]?.variants,c),d=AX(a,{regionHostname:u,partitionHostname:l});if(d===void 0)throw new Error(`Endpoint resolution failed for: ${{resolvedRegion:a,useFipsEndpoint:e,useDualstackEndpoint:r}}`);let f=CX(d,{signingRegion:n[a]?.signingRegion,regionRegex:i[s].regionRegex,useFipsEndpoint:e});return{partition:s,signingService:o,hostname:d,...f&&{signingRegion:f},...n[a]?.signingService&&{signingService:n[a].signingService}}}});var q1e,V1e,zX,MX=_(()=>{q1e="AWS_DEFAULTS_MODE",V1e="defaults_mode",zX={environmentVariableSelector:t=>t[q1e],configFileSelector:t=>t[V1e],default:"legacy"}});var Bs,G1e,H1e,UX=_(()=>{jj();Lj();Nj();H$();Uj();MX();Bs=({region:t=Ee(Br),defaultsMode:e=Ee(zX)}={})=>Lf(async()=>{let r=typeof e=="function"?await e():e;switch(r?.toLowerCase()){case"auto":return G1e(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(r?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${pX.join(", ")}, got ${r}`)}}),G1e=async t=>{if(t){let e=typeof t=="function"?await t():t,r=await H1e();return r?e===r?"in-region":"cross-region":"standard"}return"standard"},H1e=async()=>process.env[lX]&&(process.env[zj]||process.env[Mj])?process.env[zj]??process.env[Mj]:oR()});var Ao={};qt(Ao,{CONFIG_PREFIX_SEPARATOR:()=>Vs,CONFIG_USE_DUALSTACK_ENDPOINT:()=>tR,CONFIG_USE_FIPS_ENDPOINT:()=>nR,CredentialsProviderError:()=>nu,DEFAULT_PROFILE:()=>$j,DEFAULT_USE_DUALSTACK_ENDPOINT:()=>Y7,DEFAULT_USE_FIPS_ENDPOINT:()=>tX,ENV_PROFILE:()=>Ej,ENV_USE_DUALSTACK_ENDPOINT:()=>eR,ENV_USE_FIPS_ENDPOINT:()=>rR,NODE_REGION_CONFIG_FILE_OPTIONS:()=>Ln,NODE_REGION_CONFIG_OPTIONS:()=>Br,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:()=>Gs,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:()=>Hs,ProviderError:()=>Ro,REGION_ENV_NAME:()=>qf,REGION_INI_NAME:()=>Vf,SelectorType:()=>hr,TokenProviderError:()=>q$,booleanSelector:()=>Tr,chain:()=>V$,externalDataInterceptor:()=>B7,fromStatic:()=>Q$,fromValue:()=>G$,getHomeDir:()=>qs,getProfileName:()=>Z$,getRegionInfo:()=>DX,getSSOTokenFilepath:()=>W$,getSSOTokenFromFile:()=>A7,loadConfig:()=>Ee,loadSharedConfigFiles:()=>Ff,loadSsoSessionData:()=>j7,memoize:()=>Lf,nodeDualstackConfigSelectors:()=>Q7,nodeFipsConfigSelectors:()=>rX,numberSelector:()=>R7,parseKnownFiles:()=>G7,readFile:()=>od,resolveCustomEndpointsConfig:()=>oX,resolveDefaultsModeConfig:()=>Bs,resolveEndpointsConfig:()=>cX,resolveRegionConfig:()=>Io});var Dt=_(()=>{Xy();F$();$7();Sj();bj();H$();B$();I7();K$();jf();Rj();Ij();Aj();P7();X$();F7();H7();K7();tv();Nj();Dj();eX();nX();iX();uX();jj();RX();NX();UX()});var LX,jX,FX,qX=_(()=>{LX="AWS_ENDPOINT_URL",jX="endpoint_url",FX=t=>({environmentVariableSelector:e=>{let r=t.split(" ").map(i=>i.toUpperCase()),o=e[[LX,...r].join("_")];if(o)return o;let n=e[LX];if(n)return n},configFileSelector:(e,r)=>{if(e.services){let n=["services",e.services].join(".");if(!r||!r[n])throw new Error(`The services section "${e.services}" specified in the profile is not present in the shared configuration file.`);let i=r[n],s=t.split(" ").map(c=>c.toLowerCase()),a=i[[s.join("_"),jX].join(".")];if(a)return a}let o=e[jX];if(o)return o},default:void 0})});var B1e,K1e,VX,GX=_(()=>{Dt();B1e="AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",K1e="ignore_configured_endpoint_urls",VX={environmentVariableSelector:t=>Tr(t,B1e,hr.ENV),configFileSelector:t=>Tr(t,K1e,hr.CONFIG),default:!1}});var rv,HX=_(()=>{Dt();qX();GX();rv=async t=>{if(!await Ee(VX)())return Ee(FX(t??""))()}});var Vj,Z1e,W1e,J1e,BX,KX,ZX=_(()=>{Vj=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),KX(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!BX(e)||e.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(t.ForcePathStyle=!0);return t.DisableMultiRegionAccessPoints&&(t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0),t},Z1e=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,W1e=/(\d+\.){3}\d+/,J1e=/\.\./,BX=t=>Z1e.test(t)&&!W1e.test(t)&&!J1e.test(t),KX=t=>{let[e,r,o,,,n]=t.split(":"),i=e==="arn"&&t.split(":").length>=6,s=!!(i&&r&&o&&n);if(i&&!s)throw new Error(`Invalid ARN: ${t} was an invalid ARN.`);return s}});var WX=_(()=>{ZX()});var JX,XX=_(()=>{JX=(t,e,r,o=!1)=>{let n=async()=>{let i;return o?i=r.clientContextParams?.[t]??r[t]??r[e]:i=r[t]??r[e],typeof i=="function"?i():i};return t==="credentialScope"||e==="CredentialScope"?async()=>{let i=typeof r.credentials=="function"?await r.credentials():r.credentials;return i?.credentialScope??i?.CredentialScope}:t==="accountId"||e==="AccountId"?async()=>{let i=typeof r.credentials=="function"?await r.credentials():r.credentials;return i?.accountId??i?.AccountId}:t==="endpoint"||e==="endpoint"?async()=>{if(r.isCustomEndpoint===!1)return;let i=await n();if(i&&typeof i=="object"){if("url"in i)return i.url.href;if("hostname"in i){let{protocol:s,hostname:a,port:c,path:u}=i;return`${s}//${a}${c?":"+c:""}${u}`}}return i}:n}});var sR=_(()=>{Re()});function aR(t){return async(e,r,o,n)=>{if(!o.isCustomEndpoint&&!o.ignoreConfiguredEndpointUrls){let a;o.serviceConfiguredEndpoint?a=await o.serviceConfiguredEndpoint():a=await t(o.serviceId),a&&(o.endpoint=()=>Promise.resolve(xo(a)),o.isCustomEndpoint=!0,n?.logger?.debug?.(`@smithy/core/endpoints - resolved endpoint from config: ${a}`))}let i=await nv(e,r,o);if(typeof o.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");let s=o.endpointProvider(i,n);if(o.isCustomEndpoint&&o.endpoint){let a=await o.endpoint();if(a?.headers){s.headers??={};for(let[c,u]of Object.entries(a.headers))s.headers[c]=Array.isArray(u)?u:[u]}}return s}}var nv,cR=_(()=>{WX();XX();sR();nv=async(t,e,r)=>{let o={},n=e?.getEndpointParameterInstructions?.()||{};for(let[i,s]of Object.entries(n))switch(s.type){case"staticContextParams":o[i]=s.value;break;case"contextParams":o[i]=t[s.name];break;case"clientContextParams":case"builtInParams":o[i]=await JX(s.name,i,r,s.type!=="builtInParams")();break;case"operationContextParams":o[i]=s.get(t);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(n).length===0&&Object.assign(o,r),String(r.serviceId).toLowerCase()==="s3"&&await Vj(o),o}});function X1e(t,e,r){t.__smithy_context?t.__smithy_context.features||(t.__smithy_context.features={}):t.__smithy_context={features:{}},t.__smithy_context.features[e]=r}function uR(t){let e=aR(t);return({config:r,instructions:o})=>(n,i)=>async s=>{r.isCustomEndpoint&&X1e(i,"ENDPOINT_OVERRIDE","N");let a=await e(s.input,{getEndpointParameterInstructions(){return o}},{...r},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;let c=i.authSchemes?.[0];if(c){i.signing_region=c.signingRegion,i.signing_service=c.signingName;let l=Vt(i)?.selectedHttpAuthScheme?.httpAuthOption;l&&(l.signingProperties=Object.assign(l.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties))}return n({...s})}}var Gj=_(()=>{Re();cR()});function YX(t){let e=uR(t);return(r,o)=>({applyToStack:n=>{n.addRelativeTo(e({config:r,instructions:o}),Hj)}})}var Y1e,Hj,Bj=_(()=>{Gj();Y1e={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0},Hj={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Y1e.name}});function QX(t){return e=>{let r=e.tls??!0,{endpoint:o,useDualstackEndpoint:n,useFipsEndpoint:i}=e,s=o!=null?async()=>xo(await Ut(o)()):void 0,c=Object.assign(e,{endpoint:s,tls:r,isCustomEndpoint:!!o,useDualstackEndpoint:Ut(n??!1),useFipsEndpoint:Ut(i??!1),ignoreConfiguredEndpointUrls:!!e.ignoreConfiguredEndpointUrls}),u;return c.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=t(e.serviceId)),u),c}}var eY=_(()=>{Re();sR()});var Yo,tY=_(()=>{Yo=class t{nodes;root;conditions;results;constructor(e,r,o,n){this.nodes=e,this.root=r,this.conditions=o,this.results=n}static from(e,r,o,n){return new t(e,r,o,n)}}});var Qo,rY=_(()=>{Qo=class{capacity;data=new Map;parameters=[];constructor({size:e,params:r}){this.capacity=e??50,r&&(this.parameters=r)}get(e,r){let o=this.hash(e);if(o===!1)return r();if(!this.data.has(o)){if(this.data.size>this.capacity+10){let n=this.data.keys(),i=0;for(;;){let{value:s,done:a}=n.next();if(this.data.delete(s),a||++i>10)break}}this.data.set(o,r())}return this.data.get(o)}size(){return this.data.size}hash(e){let r="",{parameters:o}=this;if(o.length===0)return!1;for(let n of o){let i=String(e[n]??"");if(i.includes("|;"))return!1;r+=i+"|;"}return r}}});var ct,nY=_(()=>{ct=class extends Error{constructor(e){super(e),this.name="EndpointError"}}});var Po=_(()=>{nY()});var Ks,oY=_(()=>{Ks="endpoints"});function ko(t){return typeof t!="object"||t==null?t:"ref"in t?`$${ko(t.ref)}`:"fn"in t?`${t.fn}(${(t.argv||[]).map(ko).join(", ")})`:JSON.stringify(t,null,2)}var iY=_(()=>{});var ov=_(()=>{oY();iY()});var ro,Kj=_(()=>{ro={}});var Zj,sY=_(()=>{Zj=(t,e)=>t===e});function Wj(...t){for(let e of t)if(e!=null)return e}var aY=_(()=>{});var cY,uY=_(()=>{Po();cY=t=>{let e=t.split("."),r=[];for(let o of e){let n=o.indexOf("[");if(n!==-1){if(o.indexOf("]")!==o.length-1)throw new ct(`Path: '${t}' does not end with ']'`);let i=o.slice(n+1,-1);if(Number.isNaN(parseInt(i)))throw new ct(`Invalid array index: '${i}' in path: '${t}'`);n!==0&&r.push(o.slice(0,n)),r.push(i)}else r.push(o)}return r}});var iv,lY=_(()=>{Po();uY();iv=(t,e)=>cY(e).reduce((r,o)=>{if(typeof r!="object")throw new ct(`Index '${o}' in '${e}' not found in '${JSON.stringify(t)}'`);if(Array.isArray(r)){let n=parseInt(o);return r[n<0?r.length+n:n]}return r[o]},t)});var Jj,dY=_(()=>{Jj=t=>t!=null});function Xj(t,e,r){return t?e:r}var pY=_(()=>{});var Yj,fY=_(()=>{Yj=t=>!t});var Q1e,Ba,Qj=_(()=>{Q1e=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),Ba=t=>Q1e.test(t)||t.startsWith("[")&&t.endsWith("]")});var lR,e4,t4,mY=_(()=>{lR=jt(Cs());Qj();e4={[lR.EndpointURLScheme.HTTP]:80,[lR.EndpointURLScheme.HTTPS]:443},t4=t=>{let e=(()=>{try{if(t instanceof URL)return t;if(typeof t=="object"&&"hostname"in t){let{hostname:f,port:p,protocol:m="",path:y="",query:w={}}=t,S=new URL(`${m}//${f}${p?`:${p}`:""}${y}`);return S.search=Object.entries(w).map(([b,x])=>`${b}=${x}`).join("&"),S}return new URL(t)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let r=e.href,{host:o,hostname:n,pathname:i,protocol:s,search:a}=e;if(a)return null;let c=s.slice(0,-1);if(!Object.values(lR.EndpointURLScheme).includes(c))return null;let u=Ba(n),l=r.includes(`${o}:${e4[c]}`)||typeof t=="string"&&t.includes(`${o}:${e4[c]}`),d=`${o}${l?`:${e4[c]}`:""}`;return{scheme:c,authority:d,path:i,normalizedPath:i.endsWith("/")?i:`${i}/`,isIp:u}}});function r4(t,e,r){if(r===1)return[t];if(t==="")return[""];let o=t.split(e);return r===0?o:o.slice(0,r-1).concat(o.slice(1).join(e))}var hY=_(()=>{});var n4,gY=_(()=>{n4=(t,e)=>t===e});var o4,yY=_(()=>{o4=(t,e,r,o)=>t==null||e>=r||t.length<r||/[^\u0000-\u007f]/.test(t)?null:o?t.substring(t.length-r,t.length-e):t.substring(e,r)});var i4,vY=_(()=>{i4=t=>encodeURIComponent(t).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var s4=_(()=>{sY();aY();lY();dY();Re();pY();fY();mY();hY();gY();yY();vY()});var wY,_Y=_(()=>{s4();wY={booleanEquals:Zj,coalesce:Wj,getAttr:iv,isSet:Jj,isValidHostLabel:Ui,ite:Xj,not:Yj,parseURL:t4,split:r4,stringEquals:n4,substring:o4,uriEncode:i4}});var dR,a4=_(()=>{s4();dR=(t,e)=>{let r=[],{referenceRecord:o,endpointParams:n}=e,i=0;for(;i<t.length;){let s=t.indexOf("{",i);if(s===-1){r.push(t.slice(i));break}r.push(t.slice(i,s));let a=t.indexOf("}",s);if(a===-1){r.push(t.slice(s));break}t[s+1]==="{"&&t[a+1]==="}"&&(r.push(t.slice(s+1,a)),i=a+2);let c=t.substring(s+1,a);if(c.includes("#")){let[u,l]=c.split("#");r.push(iv(o[u]??n[u],l))}else r.push(o[c]??n[c]);i=a+1}return r.join("")}});var SY,bY=_(()=>{SY=({ref:t},e)=>e.referenceRecord[t]??e.endpointParams[t]});var Ka,pR,xY,Gf=_(()=>{Po();Kj();_Y();a4();bY();Ka=(t,e,r)=>{if(typeof t=="string")return dR(t,r);if(t.fn)return xY.callFunction(t,r);if(t.ref)return SY(t,r);throw new ct(`'${e}': ${String(t)} is not a string, function or reference.`)},pR=({fn:t,argv:e},r)=>{let o=Array(e.length);for(let s=0;s<o.length;++s){let a=e[s];typeof a=="boolean"||typeof a=="number"?o[s]=a:o[s]=xY.evaluateExpression(a,"arg",r)}let n=t.indexOf(".");if(n!==-1){let a=ro[t.slice(0,n)]?.[t.slice(n+1)];if(typeof a=="function")return a(...o)}let i=wY[t];if(typeof i=="function")return i(...o);throw new Error(`function ${t} not loaded in endpointFunctions.`)},xY={evaluateExpression:Ka,callFunction:pR}});var EY=_(()=>{Gf()});var fR,c4=_(()=>{ov();Po();EY();fR=(t,e)=>{let{assign:r}=t;if(r&&r in e.referenceRecord)throw new ct(`'${r}' is already defined in Reference Record.`);let o=pR(t,e);e.logger?.debug?.(`${Ks} evaluateCondition: ${ko(t)} = ${ko(o)}`);let n=o===""?!0:!!o;return r!=null?{result:n,toAssign:{name:r,value:o}}:{result:n}}});var mR,u4=_(()=>{Po();Gf();mR=(t,e)=>Object.entries(t??{}).reduce((r,[o,n])=>(r[o]=n.map(i=>{let s=Ka(i,"Header value entry",e);if(typeof s!="string")throw new ct(`Header '${o}' value '${s}' is not a string`);return s}),r),{})});var sv,$Y,RY,l4=_(()=>{Po();a4();sv=(t,e)=>Object.entries(t).reduce((r,[o,n])=>(r[o]=RY.getEndpointProperty(n,e),r),{}),$Y=(t,e)=>{if(Array.isArray(t))return t.map(r=>$Y(r,e));switch(typeof t){case"string":return dR(t,e);case"object":if(t===null)throw new ct(`Unexpected endpoint property: ${t}`);return RY.getEndpointProperties(t,e);case"boolean":return t;default:throw new ct(`Unexpected endpoint property type: ${typeof t}`)}},RY={getEndpointProperty:$Y,getEndpointProperties:sv}});var hR,d4=_(()=>{Po();Gf();hR=(t,e)=>{let r=Ka(t,"Endpoint URL",e);if(typeof r=="string")try{return new URL(r)}catch(o){throw console.error(`Failed to construct URL with ${r}`,o),o}throw new ct(`Endpoint URL must be a string, got ${typeof r}`)}});var p4,Zs,IY=_(()=>{Po();c4();Gf();u4();l4();d4();p4=1e8,Zs=(t,e)=>{let{nodes:r,root:o,results:n,conditions:i}=t,s=o,a={},c={referenceRecord:a,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<p4;){let u=3*(Math.abs(s)-1),[l,d,f]=[r[u],r[u+1],r[u+2]],[p,m,y]=i[l],w=fR({fn:p,assign:y,argv:m},c);if(w.toAssign){let{name:S,value:b}=w.toAssign;a[S]=b}s=s>=0===w.result?d:f}if(s>=p4){let u=n[s-p4];if(u[0]===-1){let[,p]=u;throw new ct(Ka(p,"Error",c))}let[l,d,f]=u;return{url:hR(l,c),properties:sv(d,c),headers:mR(f??{},c)}}throw new ct("No matching endpoint.")}});var Hf,gR=_(()=>{ov();c4();Hf=(t=[],e)=>{let r={},o={...e,referenceRecord:{...e.referenceRecord}},n=!1;for(let i of t){let{result:s,toAssign:a}=fR(i,o);if(!s)return{result:s};a&&(n=!0,r[a.name]=a.value,o.referenceRecord[a.name]=a.value,e.logger?.debug?.(`${Ks} assign: ${a.name} := ${ko(a.value)}`))}return n?{result:!0,referenceRecord:r}:{result:!0}}});var AY,PY=_(()=>{ov();gR();u4();l4();d4();AY=(t,e)=>{let{conditions:r,endpoint:o}=t,{result:n,referenceRecord:i}=Hf(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e,{url:a,properties:c,headers:u}=o;e.logger?.debug?.(`${Ks} Resolving endpoint from template: ${ko(o)}`);let l={url:hR(a,s)};return u!=null&&(l.headers=mR(u,s)),c!=null&&(l.properties=sv(c,s)),l}});var kY,TY=_(()=>{Po();gR();Gf();kY=(t,e)=>{let{conditions:r,error:o}=t,{result:n,referenceRecord:i}=Hf(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e;throw new ct(Ka(o,"Error",s))}});var yR,CY,f4,OY=_(()=>{Po();gR();PY();TY();yR=(t,e)=>{for(let r of t)if(r.type==="endpoint"){let o=AY(r,e);if(o)return o}else if(r.type==="error")kY(r,e);else if(r.type==="tree"){let o=f4.evaluateTreeRule(r,e);if(o)return o}else throw new ct(`Unknown endpoint rule: ${r}`);throw new ct("Rules evaluation failed")},CY=(t,e)=>{let{conditions:r,rules:o}=t,{result:n,referenceRecord:i}=Hf(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e;return f4.evaluateRules(o,s)},f4={evaluateRules:yR,evaluateTreeRule:CY}});var DY=_(()=>{OY()});var av,NY=_(()=>{Re();ov();Po();DY();av=(t,e)=>{let{endpointParams:r,logger:o}=e,{parameters:n,rules:i}=t;e.logger?.debug?.(`${Ks} Initial EndpointParams: ${ko(r)}`);for(let a in n){if(!_e(n,a))continue;let c=n[a],u=r[a];if(u==null&&c.default!=null){r[a]=c.default;continue}if(c.required&&u==null)throw new ct(`Missing required parameter: '${a}'`)}let s=yR(i,{endpointParams:r,logger:o,referenceRecord:{}});return e.logger?.debug?.(`${Ks} Resolved endpoint: ${ko(s)}`),s}});var zY,MY=_(()=>{zY=t=>{let{endpoint:e}=t;return e===void 0&&(t.endpoint=async()=>{throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")}),t}});var m4={};qt(m4,{BinaryDecisionDiagram:()=>Yo,EndpointCache:()=>Qo,EndpointError:()=>ct,customEndpointFunctions:()=>ro,decideEndpoint:()=>Zs,endpointMiddleware:()=>tze,endpointMiddlewareOptions:()=>Hj,getEndpointFromInstructions:()=>eze,getEndpointPlugin:()=>Wa,isIpAddress:()=>Ba,isValidHostLabel:()=>Ui,middlewareEndpointToEndpointV1:()=>xo,resolveEndpoint:()=>av,resolveEndpointConfig:()=>Za,resolveEndpointRequiredConfig:()=>zY,resolveParams:()=>nv,toEndpointV1:()=>xo});var eze,Za,tze,Wa,Bt=_(()=>{HX();cR();Gj();Bj();eY();Re();tY();rY();IY();Qj();Re();Kj();NY();Po();cR();sR();Bj();MY();eze=aR(rv),Za=QX(rv),tze=uR(rv),Wa=YX(rv)});var vR,h4=_(()=>{Bt();vR=(t,e)=>(r,o)=>async n=>{let i=t,s=o.endpointV2?async()=>xo(o.endpointV2):i.endpoint;if(!s)throw new Error("No valid endpoint provider available.");let a=await e(n.input,{...t,endpoint:s});return r({...n,request:a})}});function UY(t,e,r){return{applyToStack:o=>{o.add(j$(t,r),g4),o.add(vR(t,e),y4)}}}var g4,y4,LY=_(()=>{_j();h4();g4={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},y4={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});import{createHash as rze,createHmac as nze}from"node:crypto";function jY(t,e){return Buffer.isBuffer(t)?t:typeof t=="string"?Yc(t,e):ArrayBuffer.isView(t)?Fi(t.buffer,t.byteOffset,t.byteLength):Fi(t)}var wR,FY=_(()=>{Qc();vj();wR=class{algorithmIdentifier;secret;hash;constructor(e,r){this.algorithmIdentifier=e,this.secret=r,this.reset()}update(e,r){this.hash.update(Un(jY(e,r)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?nze(this.algorithmIdentifier,jY(this.secret)):rze(this.algorithmIdentifier)}}});import{Readable as oze}from"node:stream";var Bf,v4=_(()=>{sj();Bf=class extends oze{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:e,checksum:r,source:o,checksumSourceLocation:n,base64Encoder:i}){if(super(),typeof o.pipe!="function")throw new Error(`@smithy/util-stream: unsupported source type ${o?.constructor?.name??o} in ChecksumStream.`);this.source=o,this.base64Encoder=i??Ht,this.expectedChecksum=e,this.checksum=r,this.checksumSourceLocation=n,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=e=>{if(!this.destroyed){try{this.checksum.update(e)}catch(r){this.destroy(r);return}this.push(e)||this.source.pause()}};onSourceEnd=async()=>{if(!this.destroyed){try{let e=await this.checksum.digest(),r=this.base64Encoder(e);if(this.expectedChecksum!==r){this.destroy(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${r}" in response header "${this.checksumSourceLocation}".`));return}}catch(e){this.destroy(e);return}this.push(null)}};onSourceError=e=>{this.destroy(e)};onSourceClose=()=>{!this.destroyed&&!this.source.readableEnded&&this.destroy(new Error("Connection lost or stream closed before all data was received."))};_read(e){this.source.resume()}_destroy(e,r){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),r(e)}}});var Er,ou,qi=_(()=>{Er=t=>typeof ReadableStream=="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),ou=t=>typeof Blob=="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)});var qY,VY=_(()=>{qY=t=>new TextEncoder().encode(t)});var GY,XPt,HY,_R,w4,BY,KY=_(()=>{GY="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",XPt=Object.entries(GY).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),HY=GY.split(""),_R=6,w4=8,BY=63});function SR(t){let e;typeof t=="string"?e=qY(t):e=t;let r=typeof e=="object"&&typeof e.length=="number",o=typeof e=="object"&&typeof e.byteOffset=="number"&&typeof e.byteLength=="number";if(!r&&!o)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let n="";for(let i=0;i<e.length;i+=3){let s=0,a=0;for(let u=i,l=Math.min(i+3,e.length);u<l;u++)s|=e[u]<<(l-u-1)*w4,a+=w4;let c=Math.ceil(a/_R);s<<=c*_R-a;for(let u=1;u<=c;u++){let l=(c-u)*_R;n+=HY[(s&BY<<l)>>l]}n+="==".slice(0,4-c)}return n}var _4=_(()=>{VY();KY()});var ize,bR,ZY=_(()=>{ize=typeof ReadableStream=="function"?ReadableStream:function(){},bR=class extends ize{}});var WY,JY=_(()=>{_4();qi();ZY();WY=({expectedChecksum:t,checksum:e,source:r,checksumSourceLocation:o,base64Encoder:n})=>{if(!Er(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);let i=n??SR;if(typeof TransformStream!="function")throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let s=new TransformStream({start(){},async transform(c,u){e.update(c),u.enqueue(c)},async flush(c){let u=await e.digest(),l=i(u);if(t!==l){let d=new Error(`Checksum mismatch: expected "${t}" but received "${l}" in response header "${o}".`);c.error(d)}else c.terminate()}});r.pipeThrough(s);let a=s.readable;return Object.setPrototypeOf(a,bR.prototype),a}});function XY(t){return typeof ReadableStream=="function"&&Er(t.source)?WY(t):new Bf(t)}var YY=_(()=>{qi();v4();JY()});var id,S4=_(()=>{id=class{allocByteArray;byteLength=0;byteArrays=[];constructor(e){this.allocByteArray=e}push(e){this.byteArrays.push(e),this.byteLength+=e.byteLength}flush(){if(this.byteArrays.length===1){let o=this.byteArrays[0];return this.reset(),o}let e=this.allocByteArray(this.byteLength),r=0;for(let o=0;o<this.byteArrays.length;++o){let n=this.byteArrays[o];e.set(n,r),r+=n.byteLength}return this.reset(),e}reset(){this.byteArrays=[],this.byteLength=0}}});function QY(t,e,r){let o=t.getReader(),n=!1,i=0,s=["",new id(u=>new Uint8Array(u))],a=-1,c=async u=>{let{value:l,done:d}=await o.read(),f=l;if(d){if(a!==-1){let p=sd(s,a);Ja(p)>0&&u.enqueue(p)}u.close()}else{let p=x4(f,!1);if(a!==p&&(a>=0&&u.enqueue(sd(s,a)),a=p),a===-1){u.enqueue(f);return}let m=Ja(f);i+=m;let y=Ja(s[a]);if(m>=e&&y===0)u.enqueue(f);else{let w=b4(s,a,f);!n&&i>e*2&&(n=!0,r?.warn(`@smithy/util-stream - stream chunk size ${m} is below threshold of ${e}, automatically buffering.`)),w>=e?u.enqueue(sd(s,a)):await c(u)}}};return new ReadableStream({pull:c})}function b4(t,e,r){switch(e){case 0:return t[0]+=r,Ja(t[0]);case 1:case 2:return t[e].push(r),Ja(t[e])}}function sd(t,e){switch(e){case 0:let r=t[0];return t[0]="",r;case 1:case 2:return t[e].flush()}throw new Error(`@smithy/util-stream - invalid index ${e} given to flush()`)}function Ja(t){return t?.byteLength??t?.length??0}function x4(t,e=!0){return e&&typeof Buffer<"u"&&t instanceof Buffer?2:t instanceof Uint8Array?1:typeof t=="string"?0:-1}var eQ=_(()=>{S4()});import{Readable as sze}from"node:stream";function tQ(t,e,r){if(Er(t))return QY(t,e,r);let o=new sze({read(){}}),n=!1,i=0,s=["",new id(c=>new Uint8Array(c)),new id(c=>Buffer.from(new Uint8Array(c)))],a=-1;return t.on("data",c=>{let u=x4(c,!0);if(a!==u&&(a>=0&&o.push(sd(s,a)),a=u),a===-1){o.push(c);return}let l=Ja(c);i+=l;let d=Ja(s[a]);if(l>=e&&d===0)o.push(c);else{let f=b4(s,a,c);!n&&i>e*2&&(n=!0,r?.warn(`@smithy/util-stream - stream chunk size ${l} is below threshold of ${e}, automatically buffering.`)),f>=e&&o.push(sd(s,a))}}),t.on("end",()=>{if(a!==-1){let c=sd(s,a);Ja(c)>0&&o.push(c)}o.push(null)}),o}var rQ=_(()=>{S4();eQ();qi()});var nQ,oQ=_(()=>{nQ=(t,e)=>{let{base64Encoder:r,bodyLengthChecker:o,checksumAlgorithmFn:n,checksumLocationName:i,streamHasher:s}=e,a=r!==void 0&&o!==void 0&&n!==void 0&&i!==void 0&&s!==void 0,c=a?s(n,t):void 0;Promise.resolve(c).catch(()=>{});let u=t.getReader();return new ReadableStream({async pull(l){let{value:d,done:f}=await u.read();if(f){if(l.enqueue(`0\r
|
|
14
|
+
`+a}catch{!o.logger||o.logger?.constructor?.name==="NoOpLogger"?console.warn(a):o.logger?.warn?.(a)}typeof s.$responseBodyText<"u"&&s.$response&&(s.$response.body=s.$responseBodyText);try{if(kr.isInstance(i)){let{headers:c={}}=i,u=Object.entries(c);s.$metadata={httpStatusCode:i.statusCode,requestId:wj(/^x-[\w-]+-request-?id$/,u),extendedRequestId:wj(/^x-[\w-]+-id-2$/,u),cfId:wj(/^x-[\w-]+-cf-id$/,u)}}}catch{}}throw s}},wj=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var Ro,Xy=_(()=>{Ro=class t extends Error{name="ProviderError";tryNextLink;constructor(e,r=!0){let o,n=!0;typeof r=="boolean"?(o=void 0,n=r):r!=null&&typeof r=="object"&&(o=r.logger,n=r.tryNextLink??!0),super(e),this.tryNextLink=n,Object.setPrototypeOf(this,t.prototype),o?.debug?.(`@smithy/property-provider ${n?"->":"(!)"} ${e}`)}static from(e,r=!0){return Object.assign(new this(e.message,r),e)}}});var nu,F$=_(()=>{Xy();nu=class t extends Ro{name="CredentialsProviderError";constructor(e,r=!0){super(e,r),Object.setPrototypeOf(this,t.prototype)}}});var q$,$7=_(()=>{Xy();q$=class t extends Ro{name="TokenProviderError";constructor(e,r=!0){super(e,r),Object.setPrototypeOf(this,t.prototype)}}});var V$,Sj=_(()=>{Xy();V$=(...t)=>async()=>{if(t.length===0)throw new Ro("No providers in chain");let e;for(let r of t)try{return await r()}catch(o){if(e=o,o?.tryNextLink)continue;throw o}throw e}});var G$,bj=_(()=>{G$=t=>()=>Promise.resolve(t)});var Lf,H$=_(()=>{Lf=(t,e,r)=>{let o,n,i,s=!1,a=async()=>{n||(n=t());try{o=await n,i=!0,s=!1}finally{n=void 0}return o};return e===void 0?async c=>((!i||c?.forceRefresh)&&(o=await a()),o):async c=>((!i||c?.forceRefresh)&&(o=await a()),s?o:r&&!r(o)?(s=!0,o):(e(o)&&await a(),o))}});var Tr,B$=_(()=>{Tr=(t,e,r)=>{if(e in t){if(t[e]==="true")return!0;if(t[e]==="false")return!1;throw new Error(`Cannot load ${r} "${e}". Expected "true" or "false", got ${t[e]}.`)}}});var R7,I7=_(()=>{R7=(t,e,r)=>{if(!(e in t))return;let o=parseInt(t[e],10);if(Number.isNaN(o))throw new TypeError(`Cannot load ${r} '${e}'. Expected number, got '${t[e]}'.`);return o}});var hr,K$=_(()=>{(function(t){t.ENV="env",t.CONFIG="shared config entry"})(hr||(hr={}))});import{homedir as $1e}from"node:os";import{sep as R1e}from"node:path";var xj,I1e,qs,jf=_(()=>{xj={},I1e=()=>process&&process.geteuid?`${process.geteuid()}`:"DEFAULT",qs=()=>{let{HOME:t,USERPROFILE:e,HOMEPATH:r,HOMEDRIVE:o=`C:${R1e}`}=process.env;if(t)return t;if(e)return e;if(r)return`${o}${r}`;let n=I1e();return xj[n]||(xj[n]=$1e()),xj[n]}});var Ej,$j,Z$,Rj=_(()=>{Ej="AWS_PROFILE",$j="default",Z$=t=>t.profile||process.env[Ej]||$j});import{createHash as A1e}from"node:crypto";import{join as P1e}from"node:path";var W$,Ij=_(()=>{jf();W$=t=>{let r=A1e("sha1").update(t).digest("hex");return P1e(qs(),".aws","sso","cache",`${r}.json`)}});import{readFile as k1e}from"node:fs/promises";var Yy,A7,Aj=_(()=>{Ij();Yy={},A7=async t=>{if(Yy[t])return Yy[t];let e=W$(t),r=await k1e(e,"utf8");return JSON.parse(r)}});var Vs,P7=_(()=>{Vs="."});var Pj,k7,T7=_(()=>{Pj=jt(Cs()),k7=t=>Object.entries(t).filter(([e])=>{let r=e.indexOf(".");return r===-1?!1:Object.values(Pj.IniSectionType).includes(e.substring(0,r))}).reduce((e,[r,o])=>{let n=r.indexOf("."),i=r.substring(0,n)===Pj.IniSectionType.PROFILE?r.substring(n+1):r;return e[i]=o,e},{...t.default&&{default:t.default}})});import{join as T1e}from"node:path";var C1e,J$,kj=_(()=>{jf();C1e="AWS_CONFIG_FILE",J$=()=>process.env[C1e]||T1e(qs(),".aws","config")});import{join as O1e}from"node:path";var D1e,C7,O7=_(()=>{jf();D1e="AWS_SHARED_CREDENTIALS_FILE",C7=()=>process.env[D1e]||O1e(qs(),".aws","credentials")});var D7,N1e,z1e,Qy,Tj=_(()=>{D7=jt(Cs()),N1e=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,z1e=["__proto__","profile __proto__"],Qy=t=>{let e={},r,o;for(let n of t.split(/\r?\n/)){let i=n.split(/(^|\s)[;#]/)[0].trim();if(i[0]==="["&&i[i.length-1]==="]"){r=void 0,o=void 0;let a=i.substring(1,i.length-1),c=N1e.exec(a);if(c){let[,u,,l]=c;Object.values(D7.IniSectionType).includes(u)&&(r=[u,l].join("."))}else r=a;if(z1e.includes(a))throw new Error(`Found invalid profile name "${a}"`)}else if(r){let a=i.indexOf("=");if(![0,-1].includes(a)){let[c,u]=[i.substring(0,a).trim(),i.substring(a+1).trim()];if(u==="")o=c;else{o&&n.trimStart()===n&&(o=void 0),e[r]=e[r]||{};let l=o?[o,c].join("."):c;e[r][l]=u}}}}return e}});import{readFile as M1e}from"node:fs/promises";var Cj,ev,od,tv=_(()=>{Cj={},ev={},od=(t,e)=>ev[t]!==void 0?ev[t]:((!Cj[t]||e?.ignoreCache)&&(Cj[t]=M1e(t,"utf8")),Cj[t])});import{join as N7}from"node:path";var z7,Ff,X$=_(()=>{T7();kj();O7();jf();Tj();tv();z7=()=>({}),Ff=async(t={})=>{let{filepath:e=C7(),configFilepath:r=J$()}=t,o=qs(),n="~/",i=e;e.startsWith(n)&&(i=N7(o,e.slice(2)));let s=r;r.startsWith(n)&&(s=N7(o,r.slice(2)));let a=await Promise.all([od(s,{ignoreCache:t.ignoreCache}).then(Qy).then(k7).catch(z7),od(i,{ignoreCache:t.ignoreCache}).then(Qy).catch(z7)]);return{configFile:a[0],credentialsFile:a[1]}}});var M7,U7,L7=_(()=>{M7=jt(Cs()),U7=t=>Object.entries(t).filter(([e])=>e.startsWith(M7.IniSectionType.SSO_SESSION+".")).reduce((e,[r,o])=>({...e,[r.substring(r.indexOf(".")+1)]:o}),{})});var U1e,j7,F7=_(()=>{kj();L7();Tj();tv();U1e=()=>({}),j7=async(t={})=>od(t.configFilepath??J$()).then(Qy).then(U7).catch(U1e)});var q7,V7=_(()=>{q7=(...t)=>{let e={};for(let r of t)for(let[o,n]of Object.entries(r))e[o]!==void 0?Object.assign(e[o],n):e[o]=n;return e}});var G7,H7=_(()=>{X$();V7();G7=async t=>{let e=await Ff(t);return q7(e.configFile,e.credentialsFile)}});var B7,K7=_(()=>{Aj();tv();B7={getFileRecord(){return ev},interceptFile(t,e){ev[t]=Promise.resolve(e)},getTokenRecord(){return Yy},interceptToken(t,e){Yy[t]=e}}});function Y$(t){try{let e=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return e.delete("CONFIG"),e.delete("CONFIG_PREFIX_SEPARATOR"),e.delete("ENV"),[...e].join(", ")}catch{return t}}var Oj=_(()=>{});var Z7,W7=_(()=>{F$();Oj();Z7=(t,e)=>async()=>{try{let r=t(process.env,e);if(r===void 0)throw new Error;return r}catch(r){throw new nu(r.message||`Not found in ENV: ${Y$(t.toString())}`,{logger:e?.logger})}}});var J7,X7=_(()=>{F$();Rj();X$();Oj();J7=(t,{preferredFile:e="config",...r}={})=>async()=>{let o=Z$(r),{configFile:n,credentialsFile:i}=await Ff(r),s=i[o]||{},a=n[o]||{},c=e==="config"?{...s,...a}:{...a,...s};try{let l=t(c,e==="config"?n:i);if(l===void 0)throw new Error;return l}catch(u){throw new nu(u.message||`Not found in config files w/ profile [${o}]: ${Y$(t.toString())}`,{logger:r.logger})}}});var L1e,Q$,Dj=_(()=>{bj();L1e=t=>typeof t=="function",Q$=t=>L1e(t)?async()=>await t():G$(t)});var Ee,Nj=_(()=>{Sj();H$();W7();X7();Dj();Ee=({environmentVariableSelector:t,configFileSelector:e,default:r},o={})=>{let{signingName:n,logger:i}=o;return Lf(V$(Z7(t,{signingName:n,logger:i}),J7(e,o),Q$(r)))}});var eR,tR,Y7,Gs,Q7,eX=_(()=>{B$();K$();eR="AWS_USE_DUALSTACK_ENDPOINT",tR="use_dualstack_endpoint",Y7=!1,Gs={environmentVariableSelector:t=>Tr(t,eR,hr.ENV),configFileSelector:t=>Tr(t,tR,hr.CONFIG),default:!1},Q7={environmentVariableSelector:t=>Tr(t,eR,hr.ENV),configFileSelector:t=>Tr(t,tR,hr.CONFIG),default:void 0}});var rR,nR,tX,Hs,rX,nX=_(()=>{B$();K$();rR="AWS_USE_FIPS_ENDPOINT",nR="use_fips_endpoint",tX=!1,Hs={environmentVariableSelector:t=>Tr(t,rR,hr.ENV),configFileSelector:t=>Tr(t,nR,hr.CONFIG),default:!1},rX={environmentVariableSelector:t=>Tr(t,rR,hr.ENV),configFileSelector:t=>Tr(t,nR,hr.CONFIG),default:void 0}});var oX,iX=_(()=>{ge();oX=t=>{let{tls:e,endpoint:r,urlParser:o,useDualstackEndpoint:n}=t;return Object.assign(t,{tls:e??!0,endpoint:Ut(typeof r=="string"?o(r):r),isCustomEndpoint:!0,useDualstackEndpoint:Ut(n??!1)})}});var sX,aX=_(()=>{sX=async t=>{let{tls:e=!0}=t,r=await t.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(r))throw new Error("Invalid region in client config");let n=await t.useDualstackEndpoint(),i=await t.useFipsEndpoint(),{hostname:s}=await t.regionInfoProvider(r,{useDualstackEndpoint:n,useFipsEndpoint:i})??{};if(!s)throw new Error("Cannot resolve hostname from client config");return t.urlParser(`${e?"https:":"http:"}//${s}`)}});var cX,uX=_(()=>{ge();aX();cX=t=>{let e=Ut(t.useDualstackEndpoint??!1),{endpoint:r,useFipsEndpoint:o,urlParser:n,tls:i}=t;return Object.assign(t,{tls:i??!0,endpoint:r?Ut(typeof r=="string"?n(r):r):()=>sX({...t,useDualstackEndpoint:e,useFipsEndpoint:o}),isCustomEndpoint:!!r,useDualstackEndpoint:e})}});var lX,zj,Mj,dX,pX,fX,mX,hX,gX,Uj=_(()=>{lX="AWS_EXECUTION_ENV",zj="AWS_REGION",Mj="AWS_DEFAULT_REGION",dX="AWS_EC2_METADATA_DISABLED",pX=["in-region","cross-region","mobile","standard","legacy"],fX="/latest/meta-data/placement/region",mX="/latest/api/token",hX="x-aws-ec2-metadata-token",gX="x-aws-ec2-metadata-token-ttl-seconds"});var yX,j1e,_X,oR,vX,F1e,wX,Lj=_(()=>{Uj();yX=1e3,j1e=6e4,_X=0,oR=async()=>{if(!process.env[dX]&&!(Date.now()<_X))try{let t=F1e(),e=(await wX({...t,path:mX,method:"PUT",headers:{[gX]:"21600"}})).toString();return(await wX({...t,path:fX,method:"GET",headers:{[hX]:e}})).toString().trim()||vX()}catch{return vX()}},vX=()=>{_X=Date.now()+j1e},F1e=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let e=new URL(t);return{hostname:e.hostname.replace(/^\[(.+)]$/,"$1"),port:e.port?Number(e.port):void 0}}return process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6"?{hostname:"fd00:ec2::254"}:{hostname:"169.254.169.254"}},wX=async t=>{let{request:e}=await import("node:http");return new Promise((r,o)=>{let n=e({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:yX,signal:AbortSignal.timeout(yX)});n.on("error",i=>{o(i),n.destroy()}),n.on("timeout",()=>{o(new Error("TimeoutError from instance metadata service")),n.destroy()}),n.on("response",i=>{let{statusCode:s=400}=i;if(s<200||s>=300){o(Object.assign(new Error("Error response received from instance metadata service"),{statusCode:s})),n.destroy();return}let a=[];i.on("data",c=>a.push(c)),i.on("end",()=>{r(Buffer.concat(a)),n.destroy()})}),n.end()})}});var qf,Vf,Br,Ln,jj=_(()=>{Lj();qf="AWS_REGION",Vf="region",Br={environmentVariableSelector:t=>t[qf],configFileSelector:t=>t[Vf],default:async()=>{let t=await oR();if(t)return t;throw new Error("Region is missing")}},Ln={preferredFile:"credentials"}});var SX,bX,xX=_(()=>{Re();SX=new Set,bX=(t,e=Ui)=>{if(!SX.has(t)&&!e(t))if(t==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${t}" is not a valid hostname component.`);else SX.add(t)}});var iR,Fj=_(()=>{iR=t=>typeof t=="string"&&(t.startsWith("fips-")||t.endsWith("-fips"))});var EX,$X=_(()=>{Fj();EX=t=>iR(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t});var Io,RX=_(()=>{xX();$X();Fj();Io=t=>{let{region:e,useFipsEndpoint:r}=t;if(!e)throw new Error("Region is missing");return Object.assign(t,{region:async()=>{let o=typeof e=="function"?await e():e,n=EX(o);return bX(n),n},useFipsEndpoint:async()=>{let o=typeof e=="string"?e:await e();return iR(o)?!0:typeof r!="function"?Promise.resolve(!!r):r()}})}});var qj,IX=_(()=>{qj=(t=[],{useFipsEndpoint:e,useDualstackEndpoint:r})=>t.find(({tags:o})=>e===o.includes("fips")&&r===o.includes("dualstack"))?.hostname});var AX,PX=_(()=>{AX=(t,{regionHostname:e,partitionHostname:r})=>e||(r?r.replace("{region}",t):void 0)});var kX,TX=_(()=>{kX=(t,{partitionHash:e})=>Object.keys(e||{}).find(r=>e[r].regions.includes(t))??"aws"});var CX,OX=_(()=>{CX=(t,{signingRegion:e,regionRegex:r,useFipsEndpoint:o})=>{if(e)return e;if(o){let n=r.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),i=t.match(n);if(i)return i[0].slice(1,-1)}}});var DX,NX=_(()=>{IX();PX();TX();OX();DX=(t,{useFipsEndpoint:e=!1,useDualstackEndpoint:r=!1,signingService:o,regionHash:n,partitionHash:i})=>{let s=kX(t,{partitionHash:i}),a=t in n?t:i[s]?.endpoint??t,c={useFipsEndpoint:e,useDualstackEndpoint:r},u=qj(n[a]?.variants,c),l=qj(i[s]?.variants,c),d=AX(a,{regionHostname:u,partitionHostname:l});if(d===void 0)throw new Error(`Endpoint resolution failed for: ${{resolvedRegion:a,useFipsEndpoint:e,useDualstackEndpoint:r}}`);let f=CX(d,{signingRegion:n[a]?.signingRegion,regionRegex:i[s].regionRegex,useFipsEndpoint:e});return{partition:s,signingService:o,hostname:d,...f&&{signingRegion:f},...n[a]?.signingService&&{signingService:n[a].signingService}}}});var q1e,V1e,zX,MX=_(()=>{q1e="AWS_DEFAULTS_MODE",V1e="defaults_mode",zX={environmentVariableSelector:t=>t[q1e],configFileSelector:t=>t[V1e],default:"legacy"}});var Bs,G1e,H1e,UX=_(()=>{jj();Lj();Nj();H$();Uj();MX();Bs=({region:t=Ee(Br),defaultsMode:e=Ee(zX)}={})=>Lf(async()=>{let r=typeof e=="function"?await e():e;switch(r?.toLowerCase()){case"auto":return G1e(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(r?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${pX.join(", ")}, got ${r}`)}}),G1e=async t=>{if(t){let e=typeof t=="function"?await t():t,r=await H1e();return r?e===r?"in-region":"cross-region":"standard"}return"standard"},H1e=async()=>process.env[lX]&&(process.env[zj]||process.env[Mj])?process.env[zj]??process.env[Mj]:oR()});var Ao={};qt(Ao,{CONFIG_PREFIX_SEPARATOR:()=>Vs,CONFIG_USE_DUALSTACK_ENDPOINT:()=>tR,CONFIG_USE_FIPS_ENDPOINT:()=>nR,CredentialsProviderError:()=>nu,DEFAULT_PROFILE:()=>$j,DEFAULT_USE_DUALSTACK_ENDPOINT:()=>Y7,DEFAULT_USE_FIPS_ENDPOINT:()=>tX,ENV_PROFILE:()=>Ej,ENV_USE_DUALSTACK_ENDPOINT:()=>eR,ENV_USE_FIPS_ENDPOINT:()=>rR,NODE_REGION_CONFIG_FILE_OPTIONS:()=>Ln,NODE_REGION_CONFIG_OPTIONS:()=>Br,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:()=>Gs,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:()=>Hs,ProviderError:()=>Ro,REGION_ENV_NAME:()=>qf,REGION_INI_NAME:()=>Vf,SelectorType:()=>hr,TokenProviderError:()=>q$,booleanSelector:()=>Tr,chain:()=>V$,externalDataInterceptor:()=>B7,fromStatic:()=>Q$,fromValue:()=>G$,getHomeDir:()=>qs,getProfileName:()=>Z$,getRegionInfo:()=>DX,getSSOTokenFilepath:()=>W$,getSSOTokenFromFile:()=>A7,loadConfig:()=>Ee,loadSharedConfigFiles:()=>Ff,loadSsoSessionData:()=>j7,memoize:()=>Lf,nodeDualstackConfigSelectors:()=>Q7,nodeFipsConfigSelectors:()=>rX,numberSelector:()=>R7,parseKnownFiles:()=>G7,readFile:()=>od,resolveCustomEndpointsConfig:()=>oX,resolveDefaultsModeConfig:()=>Bs,resolveEndpointsConfig:()=>cX,resolveRegionConfig:()=>Io});var Dt=_(()=>{Xy();F$();$7();Sj();bj();H$();B$();I7();K$();jf();Rj();Ij();Aj();P7();X$();F7();H7();K7();tv();Nj();Dj();eX();nX();iX();uX();jj();RX();NX();UX()});var LX,jX,FX,qX=_(()=>{LX="AWS_ENDPOINT_URL",jX="endpoint_url",FX=t=>({environmentVariableSelector:e=>{let r=t.split(" ").map(i=>i.toUpperCase()),o=e[[LX,...r].join("_")];if(o)return o;let n=e[LX];if(n)return n},configFileSelector:(e,r)=>{if(e.services){let n=["services",e.services].join(".");if(!r||!r[n])throw new Error(`The services section "${e.services}" specified in the profile is not present in the shared configuration file.`);let i=r[n],s=t.split(" ").map(c=>c.toLowerCase()),a=i[[s.join("_"),jX].join(".")];if(a)return a}let o=e[jX];if(o)return o},default:void 0})});var B1e,K1e,VX,GX=_(()=>{Dt();B1e="AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",K1e="ignore_configured_endpoint_urls",VX={environmentVariableSelector:t=>Tr(t,B1e,hr.ENV),configFileSelector:t=>Tr(t,K1e,hr.CONFIG),default:!1}});var rv,HX=_(()=>{Dt();qX();GX();rv=async t=>{if(!await Ee(VX)())return Ee(FX(t??""))()}});var Vj,Z1e,W1e,J1e,BX,KX,ZX=_(()=>{Vj=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),KX(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!BX(e)||e.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(t.ForcePathStyle=!0);return t.DisableMultiRegionAccessPoints&&(t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0),t},Z1e=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,W1e=/(\d+\.){3}\d+/,J1e=/\.\./,BX=t=>Z1e.test(t)&&!W1e.test(t)&&!J1e.test(t),KX=t=>{let[e,r,o,,,n]=t.split(":"),i=e==="arn"&&t.split(":").length>=6,s=!!(i&&r&&o&&n);if(i&&!s)throw new Error(`Invalid ARN: ${t} was an invalid ARN.`);return s}});var WX=_(()=>{ZX()});var JX,XX=_(()=>{JX=(t,e,r,o=!1)=>{let n=async()=>{let i;return o?i=r.clientContextParams?.[t]??r[t]??r[e]:i=r[t]??r[e],typeof i=="function"?i():i};return t==="credentialScope"||e==="CredentialScope"?async()=>{let i=typeof r.credentials=="function"?await r.credentials():r.credentials;return i?.credentialScope??i?.CredentialScope}:t==="accountId"||e==="AccountId"?async()=>{let i=typeof r.credentials=="function"?await r.credentials():r.credentials;return i?.accountId??i?.AccountId}:t==="endpoint"||e==="endpoint"?async()=>{if(r.isCustomEndpoint===!1)return;let i=await n();if(i&&typeof i=="object"){if("url"in i)return i.url.href;if("hostname"in i){let{protocol:s,hostname:a,port:c,path:u}=i;return`${s}//${a}${c?":"+c:""}${u}`}}return i}:n}});var sR=_(()=>{Re()});function aR(t){return async(e,r,o,n)=>{if(!o.isCustomEndpoint&&!o.ignoreConfiguredEndpointUrls){let a;o.serviceConfiguredEndpoint?a=await o.serviceConfiguredEndpoint():a=await t(o.serviceId),a&&(o.endpoint=()=>Promise.resolve(xo(a)),o.isCustomEndpoint=!0,n?.logger?.debug?.(`@smithy/core/endpoints - resolved endpoint from config: ${a}`))}let i=await nv(e,r,o);if(typeof o.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");let s=o.endpointProvider(i,n);if(o.isCustomEndpoint&&o.endpoint){let a=await o.endpoint();if(a?.headers){s.headers??={};for(let[c,u]of Object.entries(a.headers))s.headers[c]=Array.isArray(u)?u:[u]}}return s}}var nv,cR=_(()=>{WX();XX();sR();nv=async(t,e,r)=>{let o={},n=e?.getEndpointParameterInstructions?.()||{};for(let[i,s]of Object.entries(n))switch(s.type){case"staticContextParams":o[i]=s.value;break;case"contextParams":o[i]=t[s.name];break;case"clientContextParams":case"builtInParams":o[i]=await JX(s.name,i,r,s.type!=="builtInParams")();break;case"operationContextParams":o[i]=s.get(t);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(n).length===0&&Object.assign(o,r),String(r.serviceId).toLowerCase()==="s3"&&await Vj(o),o}});function X1e(t,e,r){t.__smithy_context?t.__smithy_context.features||(t.__smithy_context.features={}):t.__smithy_context={features:{}},t.__smithy_context.features[e]=r}function uR(t){let e=aR(t);return({config:r,instructions:o})=>(n,i)=>async s=>{r.isCustomEndpoint&&X1e(i,"ENDPOINT_OVERRIDE","N");let a=await e(s.input,{getEndpointParameterInstructions(){return o}},{...r},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;let c=i.authSchemes?.[0];if(c){i.signing_region=c.signingRegion,i.signing_service=c.signingName;let l=Vt(i)?.selectedHttpAuthScheme?.httpAuthOption;l&&(l.signingProperties=Object.assign(l.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties))}return n({...s})}}var Gj=_(()=>{Re();cR()});function YX(t){let e=uR(t);return(r,o)=>({applyToStack:n=>{n.addRelativeTo(e({config:r,instructions:o}),Hj)}})}var Y1e,Hj,Bj=_(()=>{Gj();Y1e={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0},Hj={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Y1e.name}});function QX(t){return e=>{let r=e.tls??!0,{endpoint:o,useDualstackEndpoint:n,useFipsEndpoint:i}=e,s=o!=null?async()=>xo(await Ut(o)()):void 0,c=Object.assign(e,{endpoint:s,tls:r,isCustomEndpoint:!!o,useDualstackEndpoint:Ut(n??!1),useFipsEndpoint:Ut(i??!1),ignoreConfiguredEndpointUrls:!!e.ignoreConfiguredEndpointUrls}),u;return c.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=t(e.serviceId)),u),c}}var eY=_(()=>{Re();sR()});var Yo,tY=_(()=>{Yo=class t{nodes;root;conditions;results;constructor(e,r,o,n){this.nodes=e,this.root=r,this.conditions=o,this.results=n}static from(e,r,o,n){return new t(e,r,o,n)}}});var Qo,rY=_(()=>{Qo=class{capacity;data=new Map;parameters=[];constructor({size:e,params:r}){this.capacity=e??50,r&&(this.parameters=r)}get(e,r){let o=this.hash(e);if(o===!1)return r();if(!this.data.has(o)){if(this.data.size>this.capacity+10){let n=this.data.keys(),i=0;for(;;){let{value:s,done:a}=n.next();if(this.data.delete(s),a||++i>10)break}}this.data.set(o,r())}return this.data.get(o)}size(){return this.data.size}hash(e){let r="",{parameters:o}=this;if(o.length===0)return!1;for(let n of o){let i=e[n],s=i==null?"\0":String(i);if(s.includes("|;"))return!1;r+=s+"|;"}return r}}});var ct,nY=_(()=>{ct=class extends Error{constructor(e){super(e),this.name="EndpointError"}}});var Po=_(()=>{nY()});var Ks,oY=_(()=>{Ks="endpoints"});function ko(t){return typeof t!="object"||t==null?t:"ref"in t?`$${ko(t.ref)}`:"fn"in t?`${t.fn}(${(t.argv||[]).map(ko).join(", ")})`:JSON.stringify(t,null,2)}var iY=_(()=>{});var ov=_(()=>{oY();iY()});var ro,Kj=_(()=>{ro={}});var Zj,sY=_(()=>{Zj=(t,e)=>t===e});function Wj(...t){for(let e of t)if(e!=null)return e}var aY=_(()=>{});var cY,uY=_(()=>{Po();cY=t=>{let e=t.split("."),r=[];for(let o of e){let n=o.indexOf("[");if(n!==-1){if(o.indexOf("]")!==o.length-1)throw new ct(`Path: '${t}' does not end with ']'`);let i=o.slice(n+1,-1);if(Number.isNaN(parseInt(i)))throw new ct(`Invalid array index: '${i}' in path: '${t}'`);n!==0&&r.push(o.slice(0,n)),r.push(i)}else r.push(o)}return r}});var iv,lY=_(()=>{Po();uY();iv=(t,e)=>cY(e).reduce((r,o)=>{if(typeof r!="object")throw new ct(`Index '${o}' in '${e}' not found in '${JSON.stringify(t)}'`);if(Array.isArray(r)){let n=parseInt(o);return r[n<0?r.length+n:n]}return r[o]},t)});var Jj,dY=_(()=>{Jj=t=>t!=null});function Xj(t,e,r){return t?e:r}var pY=_(()=>{});var Yj,fY=_(()=>{Yj=t=>!t});var Q1e,Ba,Qj=_(()=>{Q1e=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),Ba=t=>Q1e.test(t)||t.startsWith("[")&&t.endsWith("]")});var lR,e4,t4,mY=_(()=>{lR=jt(Cs());Qj();e4={[lR.EndpointURLScheme.HTTP]:80,[lR.EndpointURLScheme.HTTPS]:443},t4=t=>{let e=(()=>{try{if(t instanceof URL)return t;if(typeof t=="object"&&"hostname"in t){let{hostname:f,port:p,protocol:m="",path:y="",query:w={}}=t,S=new URL(`${m}//${f}${p?`:${p}`:""}${y}`);return S.search=Object.entries(w).map(([b,x])=>`${b}=${x}`).join("&"),S}return new URL(t)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let r=e.href,{host:o,hostname:n,pathname:i,protocol:s,search:a}=e;if(a)return null;let c=s.slice(0,-1);if(!Object.values(lR.EndpointURLScheme).includes(c))return null;let u=Ba(n),l=r.includes(`${o}:${e4[c]}`)||typeof t=="string"&&t.includes(`${o}:${e4[c]}`),d=`${o}${l?`:${e4[c]}`:""}`;return{scheme:c,authority:d,path:i,normalizedPath:i.endsWith("/")?i:`${i}/`,isIp:u}}});function r4(t,e,r){if(r===1)return[t];if(t==="")return[""];let o=t.split(e);return r===0?o:o.slice(0,r-1).concat(o.slice(1).join(e))}var hY=_(()=>{});var n4,gY=_(()=>{n4=(t,e)=>t===e});var o4,yY=_(()=>{o4=(t,e,r,o)=>t==null||e>=r||t.length<r||/[^\u0000-\u007f]/.test(t)?null:o?t.substring(t.length-r,t.length-e):t.substring(e,r)});var i4,vY=_(()=>{i4=t=>encodeURIComponent(t).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var s4=_(()=>{sY();aY();lY();dY();Re();pY();fY();mY();hY();gY();yY();vY()});var wY,_Y=_(()=>{s4();wY={booleanEquals:Zj,coalesce:Wj,getAttr:iv,isSet:Jj,isValidHostLabel:Ui,ite:Xj,not:Yj,parseURL:t4,split:r4,stringEquals:n4,substring:o4,uriEncode:i4}});var dR,a4=_(()=>{s4();dR=(t,e)=>{let r=[],{referenceRecord:o,endpointParams:n}=e,i=0;for(;i<t.length;){let s=t.indexOf("{",i);if(s===-1){r.push(t.slice(i));break}r.push(t.slice(i,s));let a=t.indexOf("}",s);if(a===-1){r.push(t.slice(s));break}t[s+1]==="{"&&t[a+1]==="}"&&(r.push(t.slice(s+1,a)),i=a+2);let c=t.substring(s+1,a);if(c.includes("#")){let[u,l]=c.split("#");r.push(iv(o[u]??n[u],l))}else r.push(o[c]??n[c]);i=a+1}return r.join("")}});var SY,bY=_(()=>{SY=({ref:t},e)=>e.referenceRecord[t]??e.endpointParams[t]});var Ka,pR,xY,Gf=_(()=>{Po();Kj();_Y();a4();bY();Ka=(t,e,r)=>{if(typeof t=="string")return dR(t,r);if(t.fn)return xY.callFunction(t,r);if(t.ref)return SY(t,r);throw new ct(`'${e}': ${String(t)} is not a string, function or reference.`)},pR=({fn:t,argv:e},r)=>{let o=Array(e.length);for(let s=0;s<o.length;++s){let a=e[s];typeof a=="boolean"||typeof a=="number"?o[s]=a:o[s]=xY.evaluateExpression(a,"arg",r)}let n=t.indexOf(".");if(n!==-1){let a=ro[t.slice(0,n)]?.[t.slice(n+1)];if(typeof a=="function")return a(...o)}let i=wY[t];if(typeof i=="function")return i(...o);throw new Error(`function ${t} not loaded in endpointFunctions.`)},xY={evaluateExpression:Ka,callFunction:pR}});var EY=_(()=>{Gf()});var fR,c4=_(()=>{ov();Po();EY();fR=(t,e)=>{let{assign:r}=t;if(r&&r in e.referenceRecord)throw new ct(`'${r}' is already defined in Reference Record.`);let o=pR(t,e);e.logger?.debug?.(`${Ks} evaluateCondition: ${ko(t)} = ${ko(o)}`);let n=o===""?!0:!!o;return r!=null?{result:n,toAssign:{name:r,value:o}}:{result:n}}});var mR,u4=_(()=>{Po();Gf();mR=(t,e)=>Object.entries(t??{}).reduce((r,[o,n])=>(r[o]=n.map(i=>{let s=Ka(i,"Header value entry",e);if(typeof s!="string")throw new ct(`Header '${o}' value '${s}' is not a string`);return s}),r),{})});var sv,$Y,RY,l4=_(()=>{Po();a4();sv=(t,e)=>Object.entries(t).reduce((r,[o,n])=>(r[o]=RY.getEndpointProperty(n,e),r),{}),$Y=(t,e)=>{if(Array.isArray(t))return t.map(r=>$Y(r,e));switch(typeof t){case"string":return dR(t,e);case"object":if(t===null)throw new ct(`Unexpected endpoint property: ${t}`);return RY.getEndpointProperties(t,e);case"boolean":return t;default:throw new ct(`Unexpected endpoint property type: ${typeof t}`)}},RY={getEndpointProperty:$Y,getEndpointProperties:sv}});var hR,d4=_(()=>{Po();Gf();hR=(t,e)=>{let r=Ka(t,"Endpoint URL",e);if(typeof r=="string")try{return new URL(r)}catch(o){throw console.error(`Failed to construct URL with ${r}`,o),o}throw new ct(`Endpoint URL must be a string, got ${typeof r}`)}});var p4,Zs,IY=_(()=>{Po();c4();Gf();u4();l4();d4();p4=1e8,Zs=(t,e)=>{let{nodes:r,root:o,results:n,conditions:i}=t,s=o,a={},c={referenceRecord:a,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<p4;){let u=3*(Math.abs(s)-1),[l,d,f]=[r[u],r[u+1],r[u+2]],[p,m,y]=i[l],w=fR({fn:p,assign:y,argv:m},c);if(w.toAssign){let{name:S,value:b}=w.toAssign;a[S]=b}s=s>=0===w.result?d:f}if(s>=p4){let u=n[s-p4];if(u[0]===-1){let[,p]=u;throw new ct(Ka(p,"Error",c))}let[l,d,f]=u;return{url:hR(l,c),properties:sv(d,c),headers:mR(f??{},c)}}throw new ct("No matching endpoint.")}});var Hf,gR=_(()=>{ov();c4();Hf=(t=[],e)=>{let r={},o={...e,referenceRecord:{...e.referenceRecord}},n=!1;for(let i of t){let{result:s,toAssign:a}=fR(i,o);if(!s)return{result:s};a&&(n=!0,r[a.name]=a.value,o.referenceRecord[a.name]=a.value,e.logger?.debug?.(`${Ks} assign: ${a.name} := ${ko(a.value)}`))}return n?{result:!0,referenceRecord:r}:{result:!0}}});var AY,PY=_(()=>{ov();gR();u4();l4();d4();AY=(t,e)=>{let{conditions:r,endpoint:o}=t,{result:n,referenceRecord:i}=Hf(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e,{url:a,properties:c,headers:u}=o;e.logger?.debug?.(`${Ks} Resolving endpoint from template: ${ko(o)}`);let l={url:hR(a,s)};return u!=null&&(l.headers=mR(u,s)),c!=null&&(l.properties=sv(c,s)),l}});var kY,TY=_(()=>{Po();gR();Gf();kY=(t,e)=>{let{conditions:r,error:o}=t,{result:n,referenceRecord:i}=Hf(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e;throw new ct(Ka(o,"Error",s))}});var yR,CY,f4,OY=_(()=>{Po();gR();PY();TY();yR=(t,e)=>{for(let r of t)if(r.type==="endpoint"){let o=AY(r,e);if(o)return o}else if(r.type==="error")kY(r,e);else if(r.type==="tree"){let o=f4.evaluateTreeRule(r,e);if(o)return o}else throw new ct(`Unknown endpoint rule: ${r}`);throw new ct("Rules evaluation failed")},CY=(t,e)=>{let{conditions:r,rules:o}=t,{result:n,referenceRecord:i}=Hf(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e;return f4.evaluateRules(o,s)},f4={evaluateRules:yR,evaluateTreeRule:CY}});var DY=_(()=>{OY()});var av,NY=_(()=>{Re();ov();Po();DY();av=(t,e)=>{let{endpointParams:r,logger:o}=e,{parameters:n,rules:i}=t;e.logger?.debug?.(`${Ks} Initial EndpointParams: ${ko(r)}`);for(let a in n){if(!_e(n,a))continue;let c=n[a],u=r[a];if(u==null&&c.default!=null){r[a]=c.default;continue}if(c.required&&u==null)throw new ct(`Missing required parameter: '${a}'`)}let s=yR(i,{endpointParams:r,logger:o,referenceRecord:{}});return e.logger?.debug?.(`${Ks} Resolved endpoint: ${ko(s)}`),s}});var zY,MY=_(()=>{zY=t=>{let{endpoint:e}=t;return e===void 0&&(t.endpoint=async()=>{throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")}),t}});var m4={};qt(m4,{BinaryDecisionDiagram:()=>Yo,EndpointCache:()=>Qo,EndpointError:()=>ct,customEndpointFunctions:()=>ro,decideEndpoint:()=>Zs,endpointMiddleware:()=>tze,endpointMiddlewareOptions:()=>Hj,getEndpointFromInstructions:()=>eze,getEndpointPlugin:()=>Wa,isIpAddress:()=>Ba,isValidHostLabel:()=>Ui,middlewareEndpointToEndpointV1:()=>xo,resolveEndpoint:()=>av,resolveEndpointConfig:()=>Za,resolveEndpointRequiredConfig:()=>zY,resolveParams:()=>nv,toEndpointV1:()=>xo});var eze,Za,tze,Wa,Bt=_(()=>{HX();cR();Gj();Bj();eY();Re();tY();rY();IY();Qj();Re();Kj();NY();Po();cR();sR();Bj();MY();eze=aR(rv),Za=QX(rv),tze=uR(rv),Wa=YX(rv)});var vR,h4=_(()=>{Bt();vR=(t,e)=>(r,o)=>async n=>{let i=t,s=o.endpointV2?async()=>xo(o.endpointV2):i.endpoint;if(!s)throw new Error("No valid endpoint provider available.");let a=await e(n.input,{...t,endpoint:s});return r({...n,request:a})}});function UY(t,e,r){return{applyToStack:o=>{o.add(j$(t,r),g4),o.add(vR(t,e),y4)}}}var g4,y4,LY=_(()=>{_j();h4();g4={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},y4={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});import{createHash as rze,createHmac as nze}from"node:crypto";function jY(t,e){return Buffer.isBuffer(t)?t:typeof t=="string"?Yc(t,e):ArrayBuffer.isView(t)?Fi(t.buffer,t.byteOffset,t.byteLength):Fi(t)}var wR,FY=_(()=>{Qc();vj();wR=class{algorithmIdentifier;secret;hash;constructor(e,r){this.algorithmIdentifier=e,this.secret=r,this.reset()}update(e,r){this.hash.update(Un(jY(e,r)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?nze(this.algorithmIdentifier,jY(this.secret)):rze(this.algorithmIdentifier)}}});import{Readable as oze}from"node:stream";var Bf,v4=_(()=>{sj();Bf=class extends oze{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:e,checksum:r,source:o,checksumSourceLocation:n,base64Encoder:i}){if(super(),typeof o.pipe!="function")throw new Error(`@smithy/util-stream: unsupported source type ${o?.constructor?.name??o} in ChecksumStream.`);this.source=o,this.base64Encoder=i??Ht,this.expectedChecksum=e,this.checksum=r,this.checksumSourceLocation=n,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=e=>{if(!this.destroyed){try{this.checksum.update(e)}catch(r){this.destroy(r);return}this.push(e)||this.source.pause()}};onSourceEnd=async()=>{if(!this.destroyed){try{let e=await this.checksum.digest(),r=this.base64Encoder(e);if(this.expectedChecksum!==r){this.destroy(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${r}" in response header "${this.checksumSourceLocation}".`));return}}catch(e){this.destroy(e);return}this.push(null)}};onSourceError=e=>{this.destroy(e)};onSourceClose=()=>{!this.destroyed&&!this.source.readableEnded&&this.destroy(new Error("Connection lost or stream closed before all data was received."))};_read(e){this.source.resume()}_destroy(e,r){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),r(e)}}});var Er,ou,qi=_(()=>{Er=t=>typeof ReadableStream=="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),ou=t=>typeof Blob=="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)});var qY,VY=_(()=>{qY=t=>new TextEncoder().encode(t)});var GY,XPt,HY,_R,w4,BY,KY=_(()=>{GY="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",XPt=Object.entries(GY).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),HY=GY.split(""),_R=6,w4=8,BY=63});function SR(t){let e;typeof t=="string"?e=qY(t):e=t;let r=typeof e=="object"&&typeof e.length=="number",o=typeof e=="object"&&typeof e.byteOffset=="number"&&typeof e.byteLength=="number";if(!r&&!o)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let n="";for(let i=0;i<e.length;i+=3){let s=0,a=0;for(let u=i,l=Math.min(i+3,e.length);u<l;u++)s|=e[u]<<(l-u-1)*w4,a+=w4;let c=Math.ceil(a/_R);s<<=c*_R-a;for(let u=1;u<=c;u++){let l=(c-u)*_R;n+=HY[(s&BY<<l)>>l]}n+="==".slice(0,4-c)}return n}var _4=_(()=>{VY();KY()});var ize,bR,ZY=_(()=>{ize=typeof ReadableStream=="function"?ReadableStream:function(){},bR=class extends ize{}});var WY,JY=_(()=>{_4();qi();ZY();WY=({expectedChecksum:t,checksum:e,source:r,checksumSourceLocation:o,base64Encoder:n})=>{if(!Er(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);let i=n??SR;if(typeof TransformStream!="function")throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let s=new TransformStream({start(){},async transform(c,u){e.update(c),u.enqueue(c)},async flush(c){let u=await e.digest(),l=i(u);if(t!==l){let d=new Error(`Checksum mismatch: expected "${t}" but received "${l}" in response header "${o}".`);c.error(d)}else c.terminate()}});r.pipeThrough(s);let a=s.readable;return Object.setPrototypeOf(a,bR.prototype),a}});function XY(t){return typeof ReadableStream=="function"&&Er(t.source)?WY(t):new Bf(t)}var YY=_(()=>{qi();v4();JY()});var id,S4=_(()=>{id=class{allocByteArray;byteLength=0;byteArrays=[];constructor(e){this.allocByteArray=e}push(e){this.byteArrays.push(e),this.byteLength+=e.byteLength}flush(){if(this.byteArrays.length===1){let o=this.byteArrays[0];return this.reset(),o}let e=this.allocByteArray(this.byteLength),r=0;for(let o=0;o<this.byteArrays.length;++o){let n=this.byteArrays[o];e.set(n,r),r+=n.byteLength}return this.reset(),e}reset(){this.byteArrays=[],this.byteLength=0}}});function QY(t,e,r){let o=t.getReader(),n=!1,i=0,s=["",new id(u=>new Uint8Array(u))],a=-1,c=async u=>{let{value:l,done:d}=await o.read(),f=l;if(d){if(a!==-1){let p=sd(s,a);Ja(p)>0&&u.enqueue(p)}u.close()}else{let p=x4(f,!1);if(a!==p&&(a>=0&&u.enqueue(sd(s,a)),a=p),a===-1){u.enqueue(f);return}let m=Ja(f);i+=m;let y=Ja(s[a]);if(m>=e&&y===0)u.enqueue(f);else{let w=b4(s,a,f);!n&&i>e*2&&(n=!0,r?.warn(`@smithy/util-stream - stream chunk size ${m} is below threshold of ${e}, automatically buffering.`)),w>=e?u.enqueue(sd(s,a)):await c(u)}}};return new ReadableStream({pull:c})}function b4(t,e,r){switch(e){case 0:return t[0]+=r,Ja(t[0]);case 1:case 2:return t[e].push(r),Ja(t[e])}}function sd(t,e){switch(e){case 0:let r=t[0];return t[0]="",r;case 1:case 2:return t[e].flush()}throw new Error(`@smithy/util-stream - invalid index ${e} given to flush()`)}function Ja(t){return t?.byteLength??t?.length??0}function x4(t,e=!0){return e&&typeof Buffer<"u"&&t instanceof Buffer?2:t instanceof Uint8Array?1:typeof t=="string"?0:-1}var eQ=_(()=>{S4()});import{Readable as sze}from"node:stream";function tQ(t,e,r){if(Er(t))return QY(t,e,r);let o=new sze({read(){}}),n=!1,i=0,s=["",new id(c=>new Uint8Array(c)),new id(c=>Buffer.from(new Uint8Array(c)))],a=-1;return t.on("data",c=>{let u=x4(c,!0);if(a!==u&&(a>=0&&o.push(sd(s,a)),a=u),a===-1){o.push(c);return}let l=Ja(c);i+=l;let d=Ja(s[a]);if(l>=e&&d===0)o.push(c);else{let f=b4(s,a,c);!n&&i>e*2&&(n=!0,r?.warn(`@smithy/util-stream - stream chunk size ${l} is below threshold of ${e}, automatically buffering.`)),f>=e&&o.push(sd(s,a))}}),t.on("end",()=>{if(a!==-1){let c=sd(s,a);Ja(c)>0&&o.push(c)}o.push(null)}),o}var rQ=_(()=>{S4();eQ();qi()});var nQ,oQ=_(()=>{nQ=(t,e)=>{let{base64Encoder:r,bodyLengthChecker:o,checksumAlgorithmFn:n,checksumLocationName:i,streamHasher:s}=e,a=r!==void 0&&o!==void 0&&n!==void 0&&i!==void 0&&s!==void 0,c=a?s(n,t):void 0;Promise.resolve(c).catch(()=>{});let u=t.getReader();return new ReadableStream({async pull(l){let{value:d,done:f}=await u.read();if(f){if(l.enqueue(`0\r
|
|
15
15
|
`),a){let p=r(await c);l.enqueue(`${i}:${p}\r
|
|
16
16
|
`),l.enqueue(`\r
|
|
17
17
|
`)}l.close()}else l.enqueue(`${(o(d)||0).toString(16)}\r
|
|
@@ -125,9 +125,9 @@ ${c}`:c:"",l=Function,d=`return (input) => {
|
|
|
125
125
|
${c}
|
|
126
126
|
}`,f;try{f=new l(...s,d)(...a)}catch(p){throw new Ge(`this schema (generated code failed to evaluate: ${p.message})`)}return e?.debug&&(f.code=u),f.definite=o.definite,f}function he(t,e){for(let[o,n]of t.constants)if(n===e)return o;let r=`c${t.constantCounter++}`;return t.constants.set(r,e),r}function $l(t,e){return t.definite=!1,he(t,e)}function de(t){return`v${t.varCounter++}`}function Ske(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return Tn;let o=r;return o.issues.length===0?o.value:Tn}function un(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return Yt(t,e,r,o,n)}catch(u){if(!(u instanceof Ge)||!u.islandable)throw u;if(t.content.length=i,e.constants.size>s){let l=Array.from(e.constants.keys()).slice(s);for(let d of l)e.constants.delete(d)}return e.constantCounter=a,e.varCounter=c,bke(t,e,r,o)}}function bke(t,e,r,o){e.definite=!1;let n=he(e,r),i=he(e,Ske),s=de(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var xke=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Eke(t,e,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let s of n){let a=s._zod.def;if(a.when&&!xke.has(a.check))throw new Ge('check with a custom "when" condition');switch(a.check){case"greater_than":$ke(t,e,a,i);break;case"less_than":Rke(t,e,a,i);break;case"multiple_of":Ike(t,e,a,i);break;case"number_format":$9(t,a,i);break;case"min_length":{let c=xl(a.minimum,"min_length"),u=pz(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=xl(a.maximum,"max_length"),u=pz(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=xl(a.length,"length_equals"),u=pz(t,e,i,`${i}.length >= ${c} && ${i}.length <= ${a.length*2}`);t.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":t.write(`if (${i}.size < ${xl(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${xl(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${xl(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=R9(t,e,a,i);break;case"custom":i=Oke(t,e,s,i);break;case"bigint_format":Ake(t,a,i);break;case"mime_type":Pke(t,e,a,i);break;case"property":Tke(t,e,a,i);break;case"properties":kke(t,e,a,i);break;case"overwrite":{let c=de(e);Cke(t,e,s,i,c),i=c;break}default:throw new Ge(`check type ${a.check}`)}}return i}function pz(t,e,r,o){let n=he(e,vl),i=de(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function xl(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Ge(`${e} bound of type ${typeof t}`);return`${t}`}function E9(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Ge("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Ge("comparison check with Invalid Date bound");return he(t,e)}throw new Ge(`comparison check bound of type ${typeof e}`)}function $ke(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${E9(e,r.value)}) return INVALID;`)}function Rke(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${E9(e,r.value)}) return INVALID;`)}function Ike(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Ge("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=he(e,Vh);t.write(`if (${n}(${o}, ${xl(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function $9(t,e,r){let o=e.format;switch(o){case"safeint":t.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":t.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":t.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":t.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":t.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Ge(`number format ${o}`)}}function Ake(t,e,r){let o=e.format;if(o)switch(o){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Ge(`bigint format ${o}`)}}function Pke(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=he(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function kke(t,e,r,o){if(r.when)throw new Ge('check with a custom "when" condition');t.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let s=typeof i=="symbol"?he(e,i):Pn(i),a=de(e);t.write(`const ${a} = ${o}[${s}];`),un(t,e,n[i],a,!1)}}function Tke(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Yt(t,e,r.schema,n)}function Cke(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Ge("overwrite check without a transform function");if(Rl(i))throw new $i("z.compile: async overwrite transforms are not supported");let s=he(e,i);t.write(`const ${n} = ${s}(${o});`)}function fz(){throw new Jn}function gz(t){this.issues.push(t)}function Oke(t,e,r,o){let n=r._zod.def;if(n.fn){if(Rl(n.fn))throw new $i("z.compile: async .refine() predicates are not supported");let i=$l(e,n.fn),s=he(e,fz),a=de(e);return t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`),o}if(r._zod.check){if(Rl(r._zod.check))throw new $i("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=$l(e,u=>{let l={value:u,issues:[],addIssue:gz};return i(l)instanceof Promise&&fz(),l.issues.length===0?l.value:Tn}),c=de(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Ge("custom check without a predicate or check function")}var Dke=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 R9(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=he(e,ig);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=he(e,zb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=he(e,Vb),l=he(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=he(e,og);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=he(e,Cb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=he(e,Lb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=he(e,Fb);return t.write(`if (!${u}(${o})) return INVALID;`),o}let s=r;if(i==="url"||i==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=he(e,yb),l=he(e,r),d=de(e),f=de(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${f} = ${u}(${d}, ${l});`),t.write(`if (typeof ${f} === "number") return INVALID;`),s.hostname!==void 0){let y=he(e,vb);t.write(`if (!${y}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let y=he(e,wb);t.write(`if (!${y}(${f}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=de(e),m=s.normalize?`${f}.href`:`${he(e,ng)}(${d})`;return t.write(`const ${p} = ${m};`),p}let a=r.fn;if(a){if(Rl(a))throw new Ge(`async string format ${i}`);let u=he(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(Dke.has(i)&&r.pattern){let u=he(e,r.pattern);return t.write(`${u}.lastIndex = 0;`),t.write(`if (!${u}.test(${o})) return INVALID;`),o}let c=r.format;switch(c){case"regex":throw new Ge("regex format without a pattern");case"lowercase":t.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":t.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":t.write(`if (!${o}.includes(${Pn(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${Pn(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${Pn(u)}) return INVALID;`);break}default:throw new Ge(`string format ${c}`)}return o}function Yt(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Ge(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=Nke(t,e,r,o,a);break;case"number":c=zke(t,r,o);break;case"boolean":c=Mke(t,o);break;case"bigint":c=Uke(t,r,o);break;case"symbol":c=Lke(t,o);break;case"undefined":c=jke(t,o);break;case"null":c=Fke(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=qke(t,o);break;case"nan":c=Vke(t,o);break;case"date":c=Gke(t,o);break;case"object":c=Hke(t,e,r,o,a);break;case"optional":c=Bke(t,e,r,o,a);break;case"nullable":c=Wke(t,e,r,o,a);break;case"array":c=Jke(t,e,r,o,a);break;case"literal":c=Xke(t,e,r,o);break;case"enum":c=Yke(t,e,r,o);break;case"readonly":{let u=S9(t,e,r,o),l=de(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":S9(t,e,r,o),c="true";break;case"default":case"prefault":c=Qke(t,e,r,o);break;case"nonoptional":c=eTe(t,e,r,o);break;case"tuple":c=tTe(t,e,r,o);break;case"union":c=rTe(t,e,r,o);break;case"intersection":c=iTe(t,e,r,o);break;case"record":c=sTe(t,e,r,o);break;case"map":c=cTe(t,e,r,o);break;case"set":c=uTe(t,e,r,o);break;case"file":c=lTe(t,o);break;case"template_literal":c=dTe(t,e,r,o);break;case"lazy":c=pTe(t,e,r,o);break;case"pipe":c=fTe(t,e,r,o);break;case"custom":c=mTe(t,e,r,o);break;case"transform":c=yTe(t,e,r,o);break;case"catch":c=gTe(t,e,r,o);break;default:throw new Ge(`schema type ${s}`)}return c===null?null:Eke(t,e,r,c)}function Nke(t,e,r,o,n=!0){t.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:R9(t,e,i,o,n)}function zke(t,e,r){t.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=e._zod.def;return o.check==="number_format"&&o.format&&$9(t,{format:o.format},r),r}function Mke(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function Uke(t,e,r){t.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=e._zod.def;if(o.format)switch(o.format){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function Lke(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function jke(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Fke(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function qke(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Vke(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function Gke(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function Hke(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let s=i.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=b=>typeof b=="symbol"?he(e,b):Pn(b),d=b=>typeof b=="symbol"?`[${l(b)}]`:Pn(b),f=s;if(a.includes("__proto__"))throw new Ge('object shape key "__proto__"');let p=new Map;for(let b of u){let x=f[b],k=l(b),T=de(e);if(t.write(`const ${T} = ${o}[${k}];`),x._zod.optin!==void 0){let U=de(e);t.write(`let ${U} = (() => {`),t.indented(X=>{let ue=un(X,e,x,T);X.write(`return ${ue};`)}),t.write("})();"),x._zod.optout==="optional"?(t.write(`if (${U} === INVALID) {`),t.indented(X=>{X.write(`if (${k} in ${o}) return INVALID;`),X.write(`${U} = undefined;`)}),t.write("}")):t.write(`if (${U} === INVALID) return INVALID;`),p.set(b,U)}else{Zke(x)&&t.write(`if (!(${k} in ${o})) return INVALID;`);let U=un(t,e,x,T,n);U!==null&&p.set(b,U)}}let m=i.catchall,y="none";if(m){let b=m._zod.def.type;if(b==="never"){let x=a.map(k=>`k !== ${Pn(k)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(k=>{k.write(`if (${x}) return INVALID;`)}),t.write("}")}else(b==="unknown"||b==="any")&&!m._zod.def.checks?.length?y="passthrough":y="schema"}let w=de(e),S=u.some(b=>_9(f[b])||mz(f[b]));if(!n){if(y==="schema"){let b=a.length>0?he(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{x.write('if (k === "__proto__") continue;'),b&&x.write(`if (${b}.has(k)) continue;`);let k=de(e);x.write(`const ${k} = ${o}[k];`),un(x,e,m,k,!1)}),t.write("}")}return null}if(S){t.write(`const ${w} = {};`);for(let b of u){let x=l(b),k=p.get(b);mz(f[b])?t.write(`if (${x} in ${o}) ${w}[${x}] = ${k};`):_9(f[b])?t.write(`if (${k} !== undefined || ${x} in ${o}) ${w}[${x}] = ${k};`):t.write(`${w}[${x}] = ${k};`)}}else{let b=u.map(x=>`${d(x)}: ${p.get(x)}`).join(", ");t.write(`const ${w} = { ${b} };`)}if(y!=="none"){let b=a.length>0?he(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{if(x.write('if (k === "__proto__") continue;'),b&&x.write(`if (${b}.has(k)) continue;`),y==="passthrough")x.write(`${w}[k] = ${o}[k];`);else{let k=de(e);x.write(`const ${k} = ${o}[k];`);let T=un(x,e,m,k);x.write(`${w}[k] = ${T};`)}}),t.write("}")}return w}function Bke(t,e,r,o,n=!0){let i=r._zod.def;if(Kke(r))return Yt(t,e,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=de(e),c=de(e);return t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=Yt(l,e,i.innerType,o);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),t.write("} else {"),t.indented(u=>{let l=Yt(u,e,i.innerType,o);u.write(`${a} = ${l};`)}),t.write("}"),a}let s=n?de(e):null;return s&&t.write(`let ${s};`),t.write(`if (${o} !== undefined) {`),t.indented(a=>{let c=Yt(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function Kke(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function Zke(t){return t._zod.optin===void 0&&El(t)}function El(t){if(t._zod.def.coerce)return!0;let e=t._zod.def;switch(e.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return e.innerType?El(e.innerType):!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return e.innerType?El(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(El):!0;case"intersection":return!e.left||!e.right?!0:El(e.left)&&El(e.right);case"pipe":return e.in?El(e.in):!0;default:return!0}}function mz(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function _9(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&Ap(t)}function Ap(t){let e=t._zod.def;switch(e.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return e.innerType?Ap(e.innerType):!0;case"union":return e.options?e.options.some(Ap):!0;case"intersection":return!e.left||!e.right||Ap(e.left)||Ap(e.right);case"pipe":return e.out?Ap(e.out):!0;default:return!0}}function Wke(t,e,r,o,n=!0){let i=r._zod.def,s=n?de(e):null;return s&&t.write(`let ${s} = null;`),t.write(`if (${o} !== null) {`),t.indented(a=>{let c=Yt(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function Jke(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (!Array.isArray(${o})) return INVALID;`);let s=n?de(e):null,a=de(e),c=de(e);return s&&t.write(`const ${s} = new Array(${o}.length);`),t.write(`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`),t.indented(u=>{u.write(`const ${c} = ${o}[${a}];`);let l=un(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function Xke(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=he(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}let s=i[0];if(typeof s=="number"&&Number.isNaN(s)){let a=he(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${Pn(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")t.write(`if (${o} !== ${s}) return INVALID;`);else if(s===null)t.write(`if (${o} !== null) return INVALID;`);else if(s===void 0)t.write(`if (${o} !== undefined) return INVALID;`);else if(typeof s=="bigint")t.write(`if (${o} !== ${s}n) return INVALID;`);else throw new Ge(`literal type ${typeof s}`);return o}function Yke(t,e,r,o){let n=r._zod.values;if(!n)throw new Ge("enum schema without enumerated values");let i=he(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function S9(t,e,r,o){let n=r._zod.def;return Yt(t,e,n.innerType,o)}function Qke(t,e,r,o){let n=r._zod.def,s=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!s)return Yt(t,e,n.innerType,o);let c=he(e,s),u=de(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),Yt(t,e,n.innerType,u)}let a=de(e);if(s){let c=he(e,s),u=he(e,up);t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),t.write("} else {"),t.indented(l=>{let d=Yt(l,e,n.innerType,o);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),t.write("}")}else t.write(`let ${a};`),t.write(`if (${o} !== undefined) {`),t.indented(c=>{let u=Yt(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function eTe(t,e,r,o){let n=r._zod.def,i=Yt(t,e,n.innerType,o),s=de(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function tTe(t,e,r,o){let n=r._zod.def,i=n.items,s=n.rest;t.write(`if (!Array.isArray(${o})) return INVALID;`);let a=b9(i,"optin"),c=b9(i,"optout");s?t.write(`if (${o}.length < ${a}) return INVALID;`):t.write(`if (${o}.length < ${a} || ${o}.length > ${i.length}) return INVALID;`);let u=de(e);t.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)t.write(`if (${u}.length === ${l}) {`),t.indented(f=>{f.write(`if (${l} < ${o}.length) {`),f.indented(p=>{let m=de(e);p.write(`const ${m} = ${o}[${l}];`);let y=un(p,e,d,m);p.write(`${u}[${l}] = ${y};`)}),f.write("} else {"),f.indented(p=>{if(mz(d)){p.write(`${u}.length = ${l};`);return}let m=de(e),y=de(e);p.write(`const ${m} = undefined;`),p.write(`const ${y} = (() => {`),p.indented(w=>{let S=un(w,e,d,m);w.write(`return ${S};`)}),p.write("})();"),p.write(`if (${y} === INVALID || ${y} === undefined) ${u}.length = ${l};`),p.write(`else ${u}[${l}] = ${y};`)}),f.write("}")}),t.write("}");else{let f=de(e);t.write(`const ${f} = ${o}[${l}];`);let p=un(t,e,d,f);t.write(`${u}[${l}] = ${p};`)}}if(s){let l=de(e),d=de(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(f=>{f.write(`const ${d} = ${o}[${l}];`);let p=un(f,e,s,d);f.write(`${u}[${l}] = ${p};`)}),t.write("}")}return u}function b9(t,e){for(let r=t.length-1;r>=0;r--)if(!(e==="optin"?t[r]._zod.optin!==void 0:t[r]._zod.optout==="optional"))return r+1;return 0}function rTe(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return nTe(t,e,n,o);if(n.inclusive===!1)throw new Ge("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return Yt(t,e,i[0],o);if(i.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(i.flatMap(l=>l._zod.def.values)),u=he(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=de(e);t.write(`let ${a};`);for(let c=0;c<i.length;c++){let u=i[c];c===0?t.write(`${a} = (() => {`):t.write(`if (${a} === INVALID) ${a} = (() => {`),t.indented(l=>{let d=Yt(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function nTe(t,e,r,o){if(r.unionFallback)throw new Ge("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=de(e),i=de(e);t.write(`const ${n} = ${o}?.[${Pn(r.discriminator)}];`),t.write(`let ${i};`);let s=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Ge("discriminated union option without static discriminator values");for(let f of u){if(a.has(f))throw new Ge(`duplicate discriminator value ${String(f)}`);a.add(f)}let l=Array.from(u,f=>oTe(e,n,f)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(f=>{let p=Yt(f,e,c,o);f.write(`${i} = ${p};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function oTe(t,e,r){if(typeof r=="string")return`${e} === ${Pn(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${e})`:`${e} === ${r}`;if(typeof r=="boolean")return`${e} === ${r}`;if(r===null)return`${e} === null`;if(r===void 0)return`${e} === undefined`;if(typeof r=="bigint")return`${e} === ${r}n`;if(typeof r=="symbol"){let o=he(t,r);return`${e} === ${o}`}throw new Ge(`literal discriminator value ${String(r)}`)}function iTe(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=un(t,e,n.left,o),s=un(t,e,n.right,o),a=he(e,_p),c=de(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function sTe(t,e,r,o){let n=r._zod.def,i=he(e,Vo);t.write(`if (!${i}(${o})) return INVALID;`);let s=de(e),a=de(e),c=de(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let p=[];for(let y of l){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new Ge(`record key value ${String(y)}`);let w=typeof y=="number"?y.toString():y;if(w==="__proto__")throw new Ge('record key "__proto__"');p.push(w);let S=he(e,y),b=Yt(t,e,n.keyType,S),x=de(e);t.write(`const ${x} = ${o}[${aTe(e,w)}];`);let k=un(t,e,n.valueType,x);t.write(`${s}[${b}] = ${k};`)}let m=he(e,new Set(p));return t.write(`for (const ${a} in ${o}) {`),t.indented(y=>{y.write(`if (${m}.has(${a})) continue;`),u.mode==="loose"?y.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):y.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let p=n.mode==="loose",m=Lx(n.keyType);m.definite===!1&&(e.definite=!1);let y=he(e,m),w=he(e,ka),S=de(e);return x9(t,e,o,a,b=>{b.write(`let ${S} = ${y}(${a});`),b.write(`if (${S} === INVALID && typeof ${a} === "string" && ${w}.test(${a})) ${S} = ${y}(Number(${a}));`),p?b.write(`if (${S} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):b.write(`if (${S} === INVALID) return INVALID;`),b.write(`if (${S} === "__proto__") continue;`);let x=de(e);b.write(`const ${x} = ${o}[${a}];`);let k=un(b,e,n.valueType,x);b.write(`${s}[${S}] = ${k};`)}),s}return x9(t,e,o,a,p=>{p.write(`const ${c} = ${o}[${a}];`);let m=un(p,e,n.valueType,c);p.write(`${s}[${a}] = ${m};`)},"return INVALID;"),s}function x9(t,e,r,o,n,i){let s=he(e,Object.prototype.propertyIsEnumerable),a=de(e),c=de(e),u=de(e);t.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),t.write(`const ${c} = Object.getOwnPropertyNames(${r});`),t.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${c}[${u}];`),l.write(`if (${o} === "__proto__" || !${s}.call(${r}, ${o})) continue;`),n(l)}),t.write("}"),t.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),t.write("}")}function aTe(t,e){return typeof e=="string"?Pn(e):he(t,e)}function cTe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Map)) return INVALID;`);let i=de(e),s=de(e),a=de(e);return t.write(`const ${i} = new Map();`),t.write(`for (const [${s}, ${a}] of ${o}) {`),t.indented(c=>{let u=Yt(c,e,n.keyType,s),l=Yt(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function uTe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Set)) return INVALID;`);let i=de(e),s=de(e);return t.write(`const ${i} = new Set();`),t.write(`for (const ${s} of ${o}) {`),t.indented(a=>{let c=Yt(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function lTe(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function dTe(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=he(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function pTe(t,e,r,o){let n=r._zod.def,i=$l(e,n.getter),s=he(e,{parser:null});t.write(`if (!${s}.parser) {`),t.indented(c=>{c.write(`const inner = ${i}();`),c.write(`${s}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),t.write("}");let a=de(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function fTe(t,e,r,o){let n=r._zod.def,i=Yt(t,e,n.in,o);if(n.transform){if(Rl(n.transform))throw new $i("z.compile: async transforms in pipes are not supported");let s=n.transform,c=$l(e,l=>{let d={value:l,issues:[],addIssue:gz},f=s(l,d);return f instanceof Promise?Tn:d.issues.length===0?f:Tn}),u=de(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),Yt(t,e,n.out,u)}else return Yt(t,e,n.out,i)}function Rl(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function mTe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Rl(n.fn))throw new $i("z.compile: async custom predicates are not supported");let i=$l(e,n.fn),s=he(e,fz),a=de(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new Ge("custom schema without a predicate function");return o}function hTe(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return Tn;let n=o;return n.issues.length===0?n.value:e()}function gTe(t,e,r,o){let n=r._zod.def;if(!n.catchValue[KS])throw new Ge("catch with a callback (only a constant catch value compiles)",!1);let i=de(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=un(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=he(e,n.innerType),a=$l(e,n.catchValue),c=he(e,hTe);return t.write(`if (${i} === INVALID) {`),t.indented(u=>{u.write(`${i} = ${c}(${s}, ${a}, ${o});`),u.write(`if (${i} === INVALID) return INVALID;`)}),t.write("}"),i}function yTe(t,e,r,o){let n=r._zod.def;if(n.transform){if(Rl(n.transform))throw new $i("z.compile: async transforms are not supported");let i=n.transform,a=$l(e,u=>{let l={value:u,issues:[],addIssue:gz},d=i(u,l);return d instanceof Promise?Tn:l.issues.length===0?d:Tn}),c=de(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function jx(t){return t.checks&&(t.checks=[...t.checks]),t}function Fx(t,e){return new t(jx({type:"string",...F(e)}))}function yz(t,e){return new t(jx({type:"string",coerce:!0,...F(e)}))}function gg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...F(e)})}function yg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...F(e)})}function vg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...F(e)})}function wg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...F(e)})}function _g(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...F(e)})}function Sg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...F(e)})}function Pp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...F(e)})}function bg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...F(e)})}function xg(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...F(e)})}function Eg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...F(e)})}function $g(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...F(e)})}function Rg(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...F(e)})}function Ig(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...F(e)})}function Ag(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...F(e)})}function Pg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...F(e)})}function kg(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...F(e)})}function qx(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...F(e)})}function Tg(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...F(e)})}function Cg(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...F(e)})}function Og(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...F(e)})}function Dg(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...F(e)})}function Ng(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...F(e)})}function Vx(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...F(e)})}function Gx(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...F(e)})}function zg(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...F(e)})}var vz={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Mg(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...F(e)})}function Ug(t,e){return new t({type:"string",format:"date",check:"string_format",...F(e)})}function Lg(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...F(e)})}function jg(t,e){return new t({type:"string",format:"duration",check:"string_format",...F(e)})}function Hx(t,e){return new t(jx({type:"number",checks:[],...F(e)}))}function wz(t,e){return new t(jx({type:"number",coerce:!0,checks:[],...F(e)}))}function Bx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...F(e)})}function Kx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...F(e)})}function Zx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...F(e)})}function Wx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...F(e)})}function Jx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...F(e)})}function Xx(t,e){return new t({type:"boolean",...F(e)})}function _z(t,e){return new t({type:"boolean",coerce:!0,...F(e)})}function Yx(t,e){return new t({type:"bigint",...F(e)})}function Sz(t,e){return new t({type:"bigint",coerce:!0,...F(e)})}function Qx(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...F(e)})}function e0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...F(e)})}function t0(t,e){return new t({type:"symbol",...F(e)})}function r0(t,e){return new t({type:"undefined",...F(e)})}function n0(t,e){return new t({type:"null",...F(e)})}function o0(t){return new t({type:"any"})}function i0(t){return new t({type:"unknown"})}function s0(t,e){return new t({type:"never",...F(e)})}function a0(t,e){return new t({type:"void",...F(e)})}function c0(t,e){return new t({type:"date",...F(e)})}function bz(t,e){return new t({type:"date",coerce:!0,...F(e)})}function u0(t,e){return new t({type:"nan",...F(e)})}function bs(t,e){return new ab({check:"less_than",...F(e),value:t,inclusive:!1})}function ho(t,e){return new ab({check:"less_than",...F(e),value:t,inclusive:!0})}function xs(t,e){return new cb({check:"greater_than",...F(e),value:t,inclusive:!1})}function go(t,e){return new cb({check:"greater_than",...F(e),value:t,inclusive:!0})}function l0(t){return xs(0,t)}function d0(t){return bs(0,t)}function p0(t){return ho(0,t)}function f0(t){return go(0,t)}function xc(t,e){return new C1({check:"multiple_of",...F(e),value:t})}function Ec(t,e){return new N1({check:"max_size",...F(e),maximum:t})}function Es(t,e){return new z1({check:"min_size",...F(e),minimum:t})}function Il(t,e){return new M1({check:"size_equals",...F(e),size:t})}function Al(t,e){return new U1({check:"max_length",...F(e),maximum:t})}function Ta(t,e){return new L1({check:"min_length",...F(e),minimum:t})}function Pl(t,e){return new j1({check:"length_equals",...F(e),length:t})}function kp(t,e){return new F1({check:"string_format",format:"regex",...F(e),pattern:t})}function Tp(t){return new q1({check:"string_format",format:"lowercase",...F(t)})}function Cp(t){return new V1({check:"string_format",format:"uppercase",...F(t)})}function Op(t,e){return new G1({check:"string_format",format:"includes",...F(e),includes:t})}function Dp(t,e){return new H1({check:"string_format",format:"starts_with",...F(e),prefix:t})}function Np(t,e){return new B1({check:"string_format",format:"ends_with",...F(e),suffix:t})}function m0(t,e,r){return new K1({check:"property",property:t,schema:e,...F(r)})}function zp(t,e){return new Z1({check:"properties",shape:t,...F(e)})}function Mp(t,e){return new W1({check:"mime_type",mime:t,...F(e)})}function Ri(t){return new J1({check:"overwrite",tx:t})}function Up(t){return Ri(e=>e.normalize(t))}function Lp(){return Ri(t=>t.trim())}function jp(){return Ri(t=>t.toLowerCase())}function Fp(){return Ri(t=>t.toUpperCase())}function qp(){return Ri(t=>ON(t))}function xz(t,e,r){return new t({type:"array",element:e,...F(r)})}function vTe(t,e,r){return new t({type:"union",options:e,...F(r)})}function wTe(t,e,r){return new t({type:"union",options:e,inclusive:!1,...F(r)})}function _Te(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...F(o)})}function STe(t,e,r){return new t({type:"intersection",left:e,right:r})}function bTe(t,e,r,o){let n=r instanceof we,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...F(i)})}function xTe(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...F(o)})}function ETe(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...F(o)})}function $Te(t,e,r){return new t({type:"set",valueType:e,...F(r)})}function RTe(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...F(r)})}function ITe(t,e,r){return new t({type:"enum",entries:e,...F(r)})}function ATe(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...F(r)})}function h0(t,e){return new t({type:"file",...F(e)})}function PTe(t,e){return new t({type:"transform",transform:e})}function kTe(t,e){return new t({type:"optional",innerType:e})}function TTe(t,e){return new t({type:"nullable",innerType:e})}function CTe(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():up(r)}})}function OTe(t,e,r){return new t({type:"nonoptional",innerType:e,...F(r)})}function DTe(t,e){return new t({type:"success",innerType:e})}function NTe(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:jN(r)})}function zTe(t,e,r){return new t({type:"pipe",in:e,out:r})}function MTe(t,e){return new t({type:"readonly",innerType:e})}function UTe(t,e,r){return new t({type:"template_literal",parts:e,...F(r)})}function LTe(t,e){return new t({type:"lazy",getter:e})}function jTe(t,e){return new t({type:"promise",innerType:e})}function g0(t,e,r){let o=F(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function y0(t,e,r){return new t({type:"custom",check:"custom",fn:e,...F(r)})}function v0(t,e){let r=I9(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(lp(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(lp(i))}},t(o.value,o)),e);return r}function I9(t,e){let r=new At({check:"custom",...F(e)});return r._zod.check=t,r}function w0(t){let e=new At({check:"describe"});return e._zod.onattach=[r=>{let o=Fr.get(r)??{};Fr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function _0(t){let e=new At({check:"meta"});return e._zod.onattach=[r=>{let o=Fr.get(r)??{};Fr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function S0(t,e){let r=F(e),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(p=>typeof p=="string"?p.toLowerCase():p),n=n.map(p=>typeof p=="string"?p.toLowerCase():p));let i=new Set(o),s=new Set(n),a=t.Codec??xp,c=t.Boolean??Sp,u=t.String??bc,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),f=new a({type:"pipe",in:l,out:d,transform:((p,m)=>{let y=p;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:s.has(y)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:f,continue:!1}),{})}),reverseTransform:((p,m)=>p===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function $c(t,e,r,o={}){let n=F(o),i={check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(i.pattern=r),new t(i)}function Fg(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&jr(t,o,r[o]);return t}function Rc(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Fr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function Sr(t,e,r,o,n){let i=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:o.path,message:n}):e.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function Rt(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,l);else{let f=s.schema,p=e.processors[n.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);p(t,e,f,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),Rt(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Fg(s.schema,c),e.io==="input"&&Cn(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function A9(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Ic(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,f=t.external.uri??(m=>m);if(d)return{ref:f(d)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${A9(p)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+A9(l)}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=n(s);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
127
127
|
|
|
128
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function T9(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;T9(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var C9=new Set(["type","properties","required","additionalProperties"]),P9=["oneOf","anyOf"];function k9(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function Ez(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!C9.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??k9(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:Ez(a)??{allOf:a};jr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=k9(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function FTe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of C9)if(n in t)return;let r=e.filter(n=>P9.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Ez(e);else{let n=r[0],i=P9.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>Ez([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,Fg(t,o))}function Ac(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Fg(u,m),Fg(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&p.def)for(let w in u)w==="$ref"||w==="allOf"||w in p.def&&JSON.stringify(u[w])===JSON.stringify(p.def[w])&&delete u[w]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())T9(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])FTe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Fg(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,jr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Vp(e,"input",t.processors),output:Vp(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Cn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Cn(o.element,r);if(o.type==="set")return Cn(o.valueType,r);if(o.type==="lazy")return Cn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Cn(o.innerType,r);if(o.type==="intersection")return Cn(o.left,r)||Cn(o.right,r);if(o.type==="record"||o.type==="map")return Cn(o.keyType,r)||Cn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Cn(o.in,r)||Cn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Cn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Cn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Cn(n,r))return!0;return!!(o.rest&&Cn(o.rest,r))}return!1}var $z=(t,e={})=>r=>{let o=Rc({...r,processors:e});return Rt(t,o),Ic(o,t),Ac(o,t)},Vp=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Rc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Ic(s,t),Ac(s,t)};var Gp=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},Hp=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},O9=(t,e)=>{Gp(t,"minimum",e),Hp(t,"maximum",e)},M9=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},U9=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},L9=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},j9=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},D9=(t,e)=>Gp(t,"minimum",e.minimum),N9=(t,e)=>Hp(t,"maximum",e.maximum),z9=t=>(e,r)=>{j9(e,r.format);let[o,n]=t[r.format];Gp(e,"minimum",o),Hp(e,"maximum",n)},qTe={greater_than:(t,e)=>Gp(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>Hp(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>M9(t,e.value),number_format:z9(Hh),bigint_format:z9(Bh),min_length:D9,max_length:N9,length_equals:(t,e)=>O9(t,e.length),min_size:D9,max_size:N9,size_equals:(t,e)=>O9(t,e.size),string_format:(t,e)=>{j9(t,e.format),e.pattern&&U9(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>L9(t,e.mime)};function br(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)qTe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Gp(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Gp(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Hp(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Hp(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&M9(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&L9(e,n.mime);for(let i of n.patterns??[])U9(e,i);return e}var VTe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},GTe=new Map([[Db,p1],[sg,f1]]),F9=t=>GTe.get(t)??t,Az=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=br(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=VTe[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(F9);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Pz=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=br(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let S of a)Number.isFinite(S)&&S!==0?m.add(Math.abs(S)):Sr(t,e,n,o,`A multipleOf divisor of ${S} cannot be represented in JSON Schema`);let[y,...w]=m;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(S=>({multipleOf:S}))])}},kz=(t,e,r,o)=>{r.type="boolean"},Tz=(t,e,r,o)=>{Sr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},Cz=(t,e,r,o)=>{Sr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},Oz=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Dz=(t,e,r,o)=>{Sr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},Nz=(t,e,r,o)=>{Sr(t,e,r,o,"Void cannot be represented in JSON Schema")},zz=(t,e,r,o)=>{r.not={}},Mz=(t,e,r,o)=>{},Uz=(t,e,r,o)=>{},Lz=(t,e,r,o)=>{Sr(t,e,r,o,"Date cannot be represented in JSON Schema")},jz=(t,e,r,o)=>{let n=t._zod.def,i=ip(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},Fz=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Sr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Sr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},qz=(t,e,r,o)=>{Sr(t,e,r,o,"NaN cannot be represented in JSON Schema")},Vz=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Gz=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=br(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},Hz=(t,e,r,o)=>{r.type="boolean"},Bz=(t,e,r,o)=>{Sr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},Kz=(t,e,r,o)=>{Sr(t,e,r,o,"Function types cannot be represented in JSON Schema")},Zz=(t,e,r,o)=>{Sr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},Wz=(t,e,r,o)=>{Sr(t,e,r,o,"Map cannot be represented in JSON Schema")},Jz=(t,e,r,o)=>{Sr(t,e,r,o,"Set cannot be represented in JSON Schema")},Xz=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=br(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function qg(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?qg(e.out):e.type==="catch"?qg(e.innerType):t._zod.optin}var Yz=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Sr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)jr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?qg(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},x0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},Qz=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},eM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?qg(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:m}=br(t);typeof p=="number"&&(n.minItems=p),typeof m=="number"&&(n.maxItems=m)};function Rz(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let y=Rz(t,m,r);return y===m?e:y}for(let m of["anyOf","oneOf"]){let y=e[m];if(!Array.isArray(y))continue;let w=y.map(S=>Rz(t,S,r));w.some((S,b)=>S!==y[b])&&(e={...e,[m]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(m=>typeof m=="number"?String(m):m):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?ka:Qh).source)),p}var Iz=new WeakMap;function HTe(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of Iz.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=Rz(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var tM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=br(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)jr(n.patternProperties,F9(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=Iz.get(e);l||(l=[],Iz.set(e,l),e.deferred.push(()=>HTe(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&qg(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},rM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},nM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},oM=Symbol();function q9(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Sr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),oM):JSON.parse(s)}var iM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=q9(n.defaultValue,t,e,r,o);s!==oM&&(r.default=s)},sM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=q9(n.defaultValue,t,e,r,o);s!==oM&&(r._prefault=s)},aM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Sr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},cM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},uM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},lM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},E0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},dM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},b0={string:Az,number:Pz,boolean:kz,bigint:Tz,symbol:Cz,null:Oz,undefined:Dz,void:Nz,never:zz,any:Mz,unknown:Uz,date:Lz,enum:jz,literal:Fz,nan:qz,template_literal:Vz,file:Gz,success:Hz,custom:Bz,function:Kz,transform:Zz,map:Wz,set:Jz,array:Xz,object:Yz,union:x0,intersection:Qz,tuple:eM,record:tM,nullable:rM,nonoptional:nM,default:iM,prefault:sM,catch:aM,pipe:cM,readonly:uM,promise:lM,optional:E0,lazy:dM};function kl(t,e){if("_idmap"in t){let o=t,n=Rc({...e,processors:b0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Ic(n,l),jr(s,u,Ac(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Rc({...e,processors:b0});return Rt(t,r),Ic(r,t),Ac(r,t)}var $0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Rc({processors:b0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Ic(this.ctx,e);let o=Ac(this.ctx,e),{"~standard":n,...i}=o;return i}};var V9={};var Qp={};qt(Qp,{ZodAny:()=>kM,ZodArray:()=>DM,ZodBase64:()=>G0,ZodBase64URL:()=>H0,ZodBigInt:()=>Xp,ZodBigIntFormat:()=>Z0,ZodBoolean:()=>Jp,ZodCIDRv4:()=>q0,ZodCIDRv6:()=>V0,ZodCUID:()=>N0,ZodCUID2:()=>z0,ZodCatch:()=>QM,ZodCodec:()=>Xg,ZodCreditCard:()=>$M,ZodCustom:()=>Yg,ZodCustomStringFormat:()=>Cl,ZodDate:()=>Bg,ZodDefault:()=>KM,ZodDiscriminatedUnion:()=>zM,ZodE164:()=>B0,ZodEmail:()=>T0,ZodEmoji:()=>O0,ZodEnum:()=>Kp,ZodExactOptional:()=>X0,ZodFile:()=>VM,ZodFunction:()=>uU,ZodGUID:()=>C0,ZodIBAN:()=>RM,ZodIPv4:()=>j0,ZodIPv6:()=>F0,ZodISODate:()=>kc,ZodISODateTime:()=>Pc,ZodISODuration:()=>Cc,ZodISOTime:()=>Tc,ZodInstanceOf:()=>pU,ZodIntersection:()=>MM,ZodJWT:()=>K0,ZodKSUID:()=>L0,ZodLazy:()=>sU,ZodLiteral:()=>qM,ZodMAC:()=>EM,ZodMap:()=>jM,ZodNaN:()=>tU,ZodNanoID:()=>D0,ZodNever:()=>CM,ZodNonOptional:()=>Y0,ZodNull:()=>PM,ZodNullable:()=>BM,ZodNumber:()=>Wp,ZodNumberFormat:()=>Ol,ZodObject:()=>Kg,ZodOptional:()=>Dl,ZodPipe:()=>Jg,ZodPrefault:()=>WM,ZodPreprocess:()=>rU,ZodPromise:()=>cU,ZodReadonly:()=>nU,ZodRecord:()=>Bp,ZodSet:()=>FM,ZodString:()=>Zp,ZodStringFormat:()=>kt,ZodSuccess:()=>YM,ZodSymbol:()=>IM,ZodTemplateLiteral:()=>iU,ZodTransform:()=>GM,ZodTuple:()=>UM,ZodType:()=>Ae,ZodULID:()=>M0,ZodURL:()=>Gg,ZodUUID:()=>$s,ZodUndefined:()=>AM,ZodUnion:()=>Zg,ZodUnknown:()=>TM,ZodVoid:()=>OM,ZodXID:()=>U0,ZodXor:()=>NM,_ZodString:()=>k0,_default:()=>ZM,_function:()=>XZ,any:()=>CZ,array:()=>Le,base64:()=>pZ,base64url:()=>fZ,bigint:()=>IZ,boolean:()=>lr,catch:()=>eU,check:()=>YZ,cidrv4:()=>lZ,cidrv6:()=>dZ,codec:()=>KZ,creditCard:()=>hZ,cuid:()=>rZ,cuid2:()=>nZ,currencyCode:()=>SZ,custom:()=>Q0,date:()=>DZ,describe:()=>QZ,discriminatedUnion:()=>Wg,e164:()=>mZ,email:()=>B9,emoji:()=>eZ,enum:()=>Vr,exactOptional:()=>HM,file:()=>VZ,float32:()=>xZ,float64:()=>EZ,function:()=>XZ,guid:()=>K9,hash:()=>bZ,hex:()=>_Z,hostname:()=>wZ,httpUrl:()=>Q9,iban:()=>gZ,instanceof:()=>tW,int:()=>A0,int32:()=>$Z,int64:()=>AZ,intersection:()=>Yp,invertCodec:()=>ZZ,ipv4:()=>aZ,ipv6:()=>uZ,json:()=>nW,jwt:()=>yZ,keyof:()=>NZ,ksuid:()=>sZ,lazy:()=>aU,literal:()=>ie,looseObject:()=>qr,looseRecord:()=>LZ,mac:()=>cZ,map:()=>jZ,meta:()=>eW,nan:()=>BZ,nanoid:()=>tZ,nativeEnum:()=>qZ,never:()=>W0,nonoptional:()=>XM,null:()=>Hg,nullable:()=>Vg,nullish:()=>GZ,number:()=>ft,object:()=>J,optional:()=>Pt,partialRecord:()=>UZ,pipe:()=>P0,prefault:()=>JM,preprocess:()=>Qg,promise:()=>JZ,readonly:()=>oU,record:()=>Tt,refine:()=>lU,set:()=>FZ,strictObject:()=>zZ,string:()=>C,stringFormat:()=>vZ,stringbool:()=>rW,success:()=>HZ,superRefine:()=>dU,symbol:()=>kZ,templateLiteral:()=>WZ,transform:()=>J0,tuple:()=>LM,uint32:()=>RZ,uint64:()=>PZ,ulid:()=>oZ,undefined:()=>TZ,union:()=>It,unknown:()=>Mt,url:()=>Y9,uuid:()=>Z9,uuidv4:()=>W9,uuidv6:()=>J9,uuidv7:()=>X9,void:()=>OZ,xid:()=>iZ,xor:()=>MZ});var R0={};qt(R0,{endsWith:()=>Np,gt:()=>xs,gte:()=>go,includes:()=>Op,length:()=>Pl,lowercase:()=>Tp,lt:()=>bs,lte:()=>ho,maxLength:()=>Al,maxSize:()=>Ec,mime:()=>Mp,minLength:()=>Ta,minSize:()=>Es,multipleOf:()=>xc,negative:()=>d0,nonnegative:()=>f0,nonpositive:()=>p0,normalize:()=>Up,overwrite:()=>Ri,positive:()=>l0,properties:()=>zp,property:()=>m0,regex:()=>kp,size:()=>Il,slugify:()=>qp,startsWith:()=>Dp,toLowerCase:()=>jp,toUpperCase:()=>Fp,trim:()=>Lp,uppercase:()=>Cp});var G9=new WeakSet([Object.prototype,Error.prototype]);function I0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var H9=(t,e)=>{BN.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);G9.has(r)||(G9.add(r),I0(r,"format",o=>n=>Xh(o,n)),I0(r,"flatten",o=>n=>Jh(o,n)),I0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,sp,2)}),I0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,sp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},KTe=$("ZodError",H9),Yn=$("ZodError",H9,void 0,{Parent:Error});var pM=dp(Yn),fM=pp(Yn),mM=fp(Yn),hM=hp(Yn),gM=WS(Yn),yM=JS(Yn),vM=XS(Yn),wM=YS(Yn),_M=QS(Yn),SM=eb(Yn),bM=tb(Yn),xM=rb(Yn);function WTe(){Ir.localeError||or(Ox())}function Tl(){Ir.memoizer||or({memoizer:mg()})}var Ae=$("ZodType",(t,e)=>(WTe(),we.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(O.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return pt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(lU(t,e))},superRefine(t,e){return this.check(dU(t,e))},overwrite(t){return this.check(Ri(t))},optional(){return Pt(this)},exactOptional(){return HM(this)},nullable(){return Vg(this)},nullish(){return Pt(Vg(this))},nonoptional(t){return XM(this,t)},array(){return Le(this)},or(t){return It([this,t])},and(t){return Yp(this,t)},transform(t){return P0(this,J0(t))},default(t){return ZM(this,t)},prefault(t){return JM(this,t)},catch(t){return eU(this,t)},pipe(t){return P0(this,t)},readonly(){return oU(this)},describe(t){let e=this.clone();return Fr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Fr.get(this);let e=this.clone();return Fr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return O.hide(this,"~standard",{...fb(this),jsonSchema:{input:Vp(this,"input"),output:Vp(this,"output")}})},set"~standard"(t){O.own(this,"~standard",t)},parse:function t(e,r){return pM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await fM(this,e,r,{callee:t})},safeParse(t,e){return mM(this,t,e)},async safeParseAsync(t,e){return hM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){O.own(this,"spa",t)},validate(t,e){return yp(this,t,e)},validateAsync(t,e){return vp(this,t,e)},encode:function t(e,r){return gM(this,e,r,{callee:t})},decode:function t(e,r){return yM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await vM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await wM(this,e,r,{callee:t})},safeEncode(t,e){return _M(this,t,e)},safeDecode(t,e){return SM(this,t,e)},async safeEncodeAsync(t,e){return bM(this,t,e)},async safeDecodeAsync(t,e){return xM(this,t,e)},toJSONSchema(t){return $z(this,{})(t)},get description(){return Fr.get(this)?.description},get _def(){return this._zod.def}}),k0=$("_ZodString",(t,e)=>{bc.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Az(t,r,o,n)},O.derived({format:t=>br(t).format??null,minLength:t=>br(t).minimum??null,maxLength:t=>br(t).maximum??null},{regex(...t){return this.check(kp(...t))},includes(...t){return this.check(Op(...t))},startsWith(...t){return this.check(Dp(...t))},endsWith(...t){return this.check(Np(...t))},min(...t){return this.check(Ta(...t))},max(...t){return this.check(Al(...t))},length(...t){return this.check(Pl(...t))},nonempty(...t){return this.check(Ta(1,...t))},lowercase(t){return this.check(Tp(t))},uppercase(t){return this.check(Cp(t))},trim(){return this.check(Lp())},normalize(...t){return this.check(Up(...t))},toLowerCase(){return this.check(jp())},toUpperCase(){return this.check(Fp())},slugify(){return this.check(qp())}})),Zp=$("ZodString",(t,e)=>{bc.init(t,e),k0.init(t,e)},{email(t){return this.check(gg(T0,t))},url(t){return this.check(Pp(Gg,t))},jwt(t){return this.check(zg(K0,t))},emoji(t){return this.check(bg(O0,t))},guid(t){return this.check(yg(C0,t))},uuid(t){return this.check(vg($s,t))},uuidv4(t){return this.check(wg($s,t))},uuidv6(t){return this.check(_g($s,t))},uuidv7(t){return this.check(Sg($s,t))},nanoid(t){return this.check(xg(D0,t))},cuid(t){return this.check(Eg(N0,t))},cuid2(t){return this.check($g(z0,t))},ulid(t){return this.check(Rg(M0,t))},base64(t){return this.check(Og(G0,t))},base64url(t){return this.check(Dg(H0,t))},xid(t){return this.check(Ig(U0,t))},ksuid(t){return this.check(Ag(L0,t))},ipv4(t){return this.check(Pg(j0,t))},ipv6(t){return this.check(kg(F0,t))},cidrv4(t){return this.check(Tg(q0,t))},cidrv6(t){return this.check(Cg(V0,t))},e164(t){return this.check(Ng(B0,t))},datetime(t){return this.check(Mg(Pc,t))},date(t){return this.check(Ug(kc,t))},time(t){return this.check(Lg(Tc,t))},duration(t){return this.check(jg(Cc,t))}});function C(t){return Fx(Zp,t)}var kt=$("ZodStringFormat",(t,e)=>{_t.init(t,e),k0.init(t,e)}),Pc=$("ZodISODateTime",(t,e)=>{tz.init(t,e),kt.init(t,e)}),kc=$("ZodISODate",(t,e)=>{rz.init(t,e),kt.init(t,e)}),Tc=$("ZodISOTime",(t,e)=>{nz.init(t,e),kt.init(t,e)}),Cc=$("ZodISODuration",(t,e)=>{oz.init(t,e),kt.init(t,e)}),T0=$("ZodEmail",(t,e)=>{gb.init(t,e),kt.init(t,e)});function B9(t){return gg(T0,t)}var C0=$("ZodGUID",(t,e)=>{mb.init(t,e),kt.init(t,e)});function K9(t){return yg(C0,t)}var $s=$("ZodUUID",(t,e)=>{hb.init(t,e),kt.init(t,e)});function Z9(t){return vg($s,t)}function W9(t){return wg($s,t)}function J9(t){return _g($s,t)}function X9(t){return Sg($s,t)}var Gg=$("ZodURL",(t,e)=>{_b.init(t,e),kt.init(t,e)});function Y9(t){return Pp(Gg,t)}function Q9(t){return Pp(Gg,{protocol:Yh,hostname:h1,...O.normalizeParams(t)})}var O0=$("ZodEmoji",(t,e)=>{Sb.init(t,e),kt.init(t,e)});function eZ(t){return bg(O0,t)}var D0=$("ZodNanoID",(t,e)=>{bb.init(t,e),kt.init(t,e)});function tZ(t){return xg(D0,t)}var N0=$("ZodCUID",(t,e)=>{xb.init(t,e),kt.init(t,e)});function rZ(t){return Eg(N0,t)}var z0=$("ZodCUID2",(t,e)=>{Eb.init(t,e),kt.init(t,e)});function nZ(t){return $g(z0,t)}var M0=$("ZodULID",(t,e)=>{$b.init(t,e),kt.init(t,e)});function oZ(t){return Rg(M0,t)}var U0=$("ZodXID",(t,e)=>{Rb.init(t,e),kt.init(t,e)});function iZ(t){return Ig(U0,t)}var L0=$("ZodKSUID",(t,e)=>{Ib.init(t,e),kt.init(t,e)});function sZ(t){return Ag(L0,t)}var j0=$("ZodIPv4",(t,e)=>{Ab.init(t,e),kt.init(t,e)});function aZ(t){return Pg(j0,t)}var EM=$("ZodMAC",(t,e)=>{kb.init(t,e),kt.init(t,e)});function cZ(t){return qx(EM,t)}var F0=$("ZodIPv6",(t,e)=>{Pb.init(t,e),kt.init(t,e)});function uZ(t){return kg(F0,t)}var q0=$("ZodCIDRv4",(t,e)=>{Tb.init(t,e),kt.init(t,e)});function lZ(t){return Tg(q0,t)}var V0=$("ZodCIDRv6",(t,e)=>{Ob.init(t,e),kt.init(t,e)});function dZ(t){return Cg(V0,t)}var G0=$("ZodBase64",(t,e)=>{Nb.init(t,e),kt.init(t,e)});function pZ(t){return Og(G0,t)}var H0=$("ZodBase64URL",(t,e)=>{Mb.init(t,e),kt.init(t,e)});function fZ(t){return Dg(H0,t)}var B0=$("ZodE164",(t,e)=>{Ub.init(t,e),kt.init(t,e)});function mZ(t){return Ng(B0,t)}var $M=$("ZodCreditCard",(t,e)=>{jb.init(t,e),kt.init(t,e)});function hZ(t){return Vx($M,t)}var RM=$("ZodIBAN",(t,e)=>{qb.init(t,e),kt.init(t,e)});function gZ(t){return Gx(RM,t)}var K0=$("ZodJWT",(t,e)=>{Gb.init(t,e),kt.init(t,e)});function yZ(t){return zg(K0,t)}var Cl=$("ZodCustomStringFormat",(t,e)=>{Hb.init(t,e),kt.init(t,e)});function vZ(t,e,r={}){return $c(Cl,t,e,r)}function wZ(t){return $c(Cl,"hostname",m1,t)}function _Z(t){return $c(Cl,"hex",P1,t)}function SZ(t){return $c(Cl,"currency_code",y1,t)}function bZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=mo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return $c(Cl,o,n,e)}var Wp=$("ZodNumber",(t,e)=>{ag.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Pz(t,r,o,n),t.isFinite=!0},O.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=br(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=br(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=br(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>br(t).format??null},{gt(t,e){return this.check(xs(t,e))},gte(t,e){return this.check(go(t,e))},min(t,e){return this.check(go(t,e))},lt(t,e){return this.check(bs(t,e))},lte(t,e){return this.check(ho(t,e))},max(t,e){return this.check(ho(t,e))},int(t){return this.check(A0(t))},safe(t){return this.check(A0(t))},positive(t){return this.check(xs(0,t))},nonnegative(t){return this.check(go(0,t))},negative(t){return this.check(bs(0,t))},nonpositive(t){return this.check(ho(0,t))},multipleOf(t,e){return this.check(xc(t,e))},step(t,e){return this.check(xc(t,e))},finite(){return this}}));function ft(t){return Hx(Wp,t)}var Ol=$("ZodNumberFormat",(t,e)=>{Bb.init(t,e),Wp.init(t,e)});function A0(t){return Bx(Ol,t)}function xZ(t){return Kx(Ol,t)}function EZ(t){return Zx(Ol,t)}function $Z(t){return Wx(Ol,t)}function RZ(t){return Jx(Ol,t)}var Jp=$("ZodBoolean",(t,e)=>{Sp.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kz(t,r,o,n)});function lr(t){return Xx(Jp,t)}var Xp=$("ZodBigInt",(t,e)=>{cg.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tz(t,r,o,n)},O.derived({minValue:t=>br(t).minimum??null,maxValue:t=>br(t).maximum??null,format:t=>br(t).format??null},{gte(t,e){return this.check(go(t,e))},min(t,e){return this.check(go(t,e))},gt(t,e){return this.check(xs(t,e))},lt(t,e){return this.check(bs(t,e))},lte(t,e){return this.check(ho(t,e))},max(t,e){return this.check(ho(t,e))},positive(t){return this.check(xs(BigInt(0),t))},negative(t){return this.check(bs(BigInt(0),t))},nonpositive(t){return this.check(ho(BigInt(0),t))},nonnegative(t){return this.check(go(BigInt(0),t))},multipleOf(t,e){return this.check(xc(t,e))}}));function IZ(t){return Yx(Xp,t)}var Z0=$("ZodBigIntFormat",(t,e)=>{Kb.init(t,e),Xp.init(t,e)});function AZ(t){return Qx(Z0,t)}function PZ(t){return e0(Z0,t)}var IM=$("ZodSymbol",(t,e)=>{Zb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Cz(t,r,o,n)});function kZ(t){return t0(IM,t)}var AM=$("ZodUndefined",(t,e)=>{Wb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Dz(t,r,o,n)});function TZ(t){return r0(AM,t)}var PM=$("ZodNull",(t,e)=>{Jb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Oz(t,r,o,n)});function Hg(t){return n0(PM,t)}var kM=$("ZodAny",(t,e)=>{Xb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Mz(t,r,o,n)});function CZ(){return o0(kM)}var TM=$("ZodUnknown",(t,e)=>{Yb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Uz(t,r,o,n)});function Mt(){return i0(TM)}var CM=$("ZodNever",(t,e)=>{Qb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zz(t,r,o,n)});function W0(t){return s0(CM,t)}var OM=$("ZodVoid",(t,e)=>{ex.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Nz(t,r,o,n)});function OZ(t){return a0(OM,t)}var Bg=$("ZodDate",(t,e)=>{tx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Lz(t,r,o,n),t.min=(r,o)=>t.check(go(r,o)),t.max=(r,o)=>t.check(ho(r,o))},O.derived({minDate:t=>{let{minimum:e}=br(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=br(t);return e?new Date(e):null}},{}));function DZ(t){return c0(Bg,t)}var DM=$("ZodArray",(t,e)=>{Tl(),rx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Xz(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ta(t,e))},nonempty(t){return this.check(Ta(1,t))},max(t,e){return this.check(Al(t,e))},length(t,e){return this.check(Pl(t,e))},unwrap(){return this.element}});function Le(t,e){return xz(DM,t,e)}function NZ(t){let e=t._zod.def.shape;return Vr(Object.keys(e))}var Kg=$("ZodObject",(t,e)=>{Tl(),iz.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Yz(t,r,o,n),O.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Vr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(O.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(O.mergeDefs(this._zod.def,{catchall:Mt()}))},loose(){return this.clone(O.mergeDefs(this._zod.def,{catchall:Mt()}))},strict(){return this.clone(O.mergeDefs(this._zod.def,{catchall:W0()}))},strip(){return this.clone(O.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return O.extend(this,t)},safeExtend(t){return O.safeExtend(this,t)},merge(t){return O.merge(this,t)},pick(t){return O.pick(this,t)},omit(t){return O.omit(this,t)},partial(...t){return O.partial(Dl,this,t[0])},exactPartial(...t){return O.partial(X0,this,t[0],"exactPartial")},required(...t){return O.required(Y0,this,t[0])}});function J(t,e){let r={type:"object",shape:t??{},...O.normalizeParams(e)};return new Kg(r)}function zZ(t,e){return new Kg({type:"object",shape:t,catchall:W0(),...O.normalizeParams(e)})}function qr(t,e){return new Kg({type:"object",shape:t,catchall:Mt(),...O.normalizeParams(e)})}var Zg=$("ZodUnion",(t,e)=>{bp.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>x0(t,r,o,n),t.options=e.options});function It(t,e){return new Zg({type:"union",options:t,...O.normalizeParams(e)})}var NM=$("ZodXor",(t,e)=>{Zg.init(t,e),ox.init(t,e),t._zod.processJSONSchema=(r,o,n)=>x0(t,r,o,n),t.options=e.options});function MZ(t,e){return new NM({type:"union",options:t,inclusive:!1,...O.normalizeParams(e)})}var zM=$("ZodDiscriminatedUnion",(t,e)=>{Zg.init(t,e),ix.init(t,e)});function Wg(t,e,r){return new zM({type:"union",options:e,discriminator:t,...O.normalizeParams(r)})}var MM=$("ZodIntersection",(t,e)=>{sx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Qz(t,r,o,n)});function Yp(t,e){return new MM({type:"intersection",left:t,right:e})}var UM=$("ZodTuple",(t,e)=>{Tl(),ug.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Dl({type:"optional",innerType:e}))})}});function LM(t,e,r){let o=e instanceof we,n=o?r:e,i=o?e:null;return new UM({type:"tuple",items:t,rest:i,...O.normalizeParams(n)})}var Bp=$("ZodRecord",(t,e)=>{Tl(),ax.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Tt(t,e,r){return!e||!e._zod?new Bp({type:"record",keyType:C(),valueType:t,...O.normalizeParams(e)}):new Bp({type:"record",keyType:t,valueType:e,...O.normalizeParams(r)})}function UZ(t,e,r){return new Bp({type:"record",keyType:t,valueType:e,...O.normalizeParams(r),partial:!0})}function LZ(t,e,r){return new Bp({type:"record",keyType:t,valueType:e,mode:"loose",...O.normalizeParams(r)})}var jM=$("ZodMap",(t,e)=>{Tl(),cx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Wz(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Es(...r)),t.nonempty=r=>t.check(Es(1,r)),t.max=(...r)=>t.check(Ec(...r)),t.size=(...r)=>t.check(Il(...r))});function jZ(t,e,r){return new jM({type:"map",keyType:t,valueType:e,...O.normalizeParams(r)})}var FM=$("ZodSet",(t,e)=>{Tl(),ux.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Jz(t,r,o,n),t.min=(...r)=>t.check(Es(...r)),t.nonempty=r=>t.check(Es(1,r)),t.max=(...r)=>t.check(Ec(...r)),t.size=(...r)=>t.check(Il(...r))});function FZ(t,e){return new FM({type:"set",valueType:t,...O.normalizeParams(e)})}var Kp=$("ZodEnum",(t,e)=>{lx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(o,n,i)=>jz(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Kp({...e,checks:[],...O.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Kp({...e,checks:[],...O.normalizeParams(n),entries:i})}});function Vr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Kp({type:"enum",entries:r,...O.normalizeParams(e)})}function qZ(t,e){return new Kp({type:"enum",entries:t,...O.normalizeParams(e)})}var qM=$("ZodLiteral",(t,e)=>{dx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Fz(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ie(t,e){return new qM({type:"literal",values:Array.isArray(t)?t:[t],...O.normalizeParams(e)})}var VM=$("ZodFile",(t,e)=>{px.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Gz(t,r,o,n),t.min=(r,o)=>t.check(Es(r,o)),t.max=(r,o)=>t.check(Ec(r,o)),t.mime=(r,o)=>t.check(Mp(Array.isArray(r)?r:[r],o))});function VZ(t){return h0(VM,t)}var GM=$("ZodTransform",(t,e)=>{Tl(),fx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Zz(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Sc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(O.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(O.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function J0(t){return new GM({type:"transform",transform:t})}var Dl=$("ZodOptional",(t,e)=>{lg.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>E0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Pt(t){return new Dl({type:"optional",innerType:t})}var X0=$("ZodExactOptional",(t,e)=>{mx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>E0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function HM(t){return new X0({type:"optional",innerType:t})}var BM=$("ZodNullable",(t,e)=>{hx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Vg(t){return new BM({type:"nullable",innerType:t})}function GZ(t){return Pt(Vg(t))}var KM=$("ZodDefault",(t,e)=>{gx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function ZM(t,e){return new KM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():O.shallowClone(e)}})}var WM=$("ZodPrefault",(t,e)=>{yx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function JM(t,e){return new WM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():O.shallowClone(e)}})}var Y0=$("ZodNonOptional",(t,e)=>{vx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function XM(t,e){return new Y0({type:"nonoptional",innerType:t,...O.normalizeParams(e)})}var YM=$("ZodSuccess",(t,e)=>{wx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Hz(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function HZ(t){return new YM({type:"success",innerType:t})}var QM=$("ZodCatch",(t,e)=>{_x.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function eU(t,e){return new QM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:O.constantCatch(e)})}var tU=$("ZodNaN",(t,e)=>{Sx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qz(t,r,o,n)});function BZ(t){return u0(tU,t)}var Jg=$("ZodPipe",(t,e)=>{dg.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cM(t,r,o,n),t.in=e.in,t.out=e.out});function P0(t,e){return new Jg({type:"pipe",in:t,out:e})}var Xg=$("ZodCodec",(t,e)=>{Jg.init(t,e),xp.init(t,e)});function KZ(t,e,r){return new Xg({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function ZZ(t){let e=t._zod.def;return new Xg({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var rU=$("ZodPreprocess",(t,e)=>{Jg.init(t,e),az.init(t,e)}),nU=$("ZodReadonly",(t,e)=>{bx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function oU(t){return new nU({type:"readonly",innerType:t})}var iU=$("ZodTemplateLiteral",(t,e)=>{xx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Vz(t,r,o,n)});function WZ(t,e){return new iU({type:"template_literal",parts:t,...O.normalizeParams(e)})}var sU=$("ZodLazy",(t,e)=>{Ep.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function aU(t){return new sU({type:"lazy",getter:t})}var cU=$("ZodPromise",(t,e)=>{$x.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function JZ(t){return new cU({type:"promise",innerType:t})}var uU=$("ZodFunction",(t,e)=>{Ex.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Kz(t,r,o,n)});function XZ(t){return new uU({type:"function",input:Array.isArray(t?.input)?LM(t?.input):t?.input??Le(Mt()),output:t?.output??Mt()})}var Yg=$("ZodCustom",(t,e)=>{Rx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Bz(t,r,o,n)});function YZ(t){let e=new At({check:"custom"});return e._zod.check=t,e}function Q0(t,e){return g0(Yg,t??(()=>!0),e)}function lU(t,e={}){return y0(Yg,t,e)}function dU(t,e){return v0(t,e)}var QZ=w0,eW=_0,pU=$("ZodInstanceOf",(t,e)=>{Yg.init(t,e)},{properties(t,e){return this.check(zp(t,e))}});function tW(t,e={}){let r=new pU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...O.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var rW=(...t)=>S0({Codec:Xg,Boolean:Jp,String:Zp},...t);function nW(t){let e=aU(()=>It([C(t),ft(),lr(),Hg(),Le(e),Tt(C(),e)]));return e}function Qg(t,e){return new rU({type:"pipe",in:J0(t),out:e})}var JTe={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 XTe(t){or({customError:t})}function YTe(){return or().customError}var fU;fU||(fU={});var Nl={};qt(Nl,{ZodISODate:()=>kc,ZodISODateTime:()=>Pc,ZodISODuration:()=>Cc,ZodISOTime:()=>Tc,date:()=>eCe,datetime:()=>QTe,duration:()=>rCe,time:()=>tCe});function QTe(t){return Mg(Pc,t)}function eCe(t){return Ug(kc,t)}function tCe(t){return Lg(Tc,t)}function rCe(t){return jg(Cc,t)}var W={...Qp,...R0,iso:Nl},nCe=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 oCe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function oW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function iCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function sCe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:iCe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function aCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function mU(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=mU(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=mU(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var cCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),uCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function ey(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(ey):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>cCe.has(e)?ey(r):!uCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(ey))}function iW(t){return t===1?"element":"elements"}function lCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=mU(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${iW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${iW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function sW(t,e){if(t!==!1)return t===void 0||t===!0?W.any():On(t,e)}var dCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function aW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return W.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=sCe(n,e),s=On(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return W.null();if(n.length===0)return W.never();if(n.length===1)return W.literal(n[0]);if(n.every(s=>typeof s=="string"))return W.enum(n);let i=n.map(s=>W.literal(s));return i.length<2?i[0]:W.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return W.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return aW(s,e)});return n.length===0?W.never():n.length===1?n[0]:W.union(n)}if(!r)return W.any();let o;switch(r){case"string":{let n=W.string();if(t.format){let i=t.format;i==="email"?n=n.check(W.email()):i==="uri"||i==="uri-reference"?n=n.check(W.url()):i==="uuid"||i==="guid"?n=n.check(W.uuid()):i==="date-time"?n=n.check(W.iso.datetime({offset:!0})):i==="date"?n=n.check(W.iso.date()):i==="time"?n=n.check(W.regex(dCe)):i==="duration"?n=n.check(W.iso.duration()):i==="hostname"?n=n.check(W.hostname()):i==="ipv4"?n=n.check(W.ipv4()):i==="ipv6"?n=n.check(W.ipv6()):i==="mac"?n=n.check(W.mac()):i==="cidr"?n=n.check(W.cidrv4()):i==="cidr-v6"?n=n.check(W.cidrv6()):i==="base64"?n=n.check(W.base64()):i==="base64url"?n=n.check(W.base64url()):i==="e164"?n=n.check(W.e164()):i==="credit_card"?n=n.check(W.creditCard()):i==="iban"?n=n.check(W.iban()):i==="jwt"?n=n.check(W.jwt()):i==="emoji"?n=n.check(W.emoji()):i==="nanoid"?n=n.check(W.nanoid()):i==="cuid"?n=n.check(W.cuid()):i==="cuid2"?n=n.check(W.cuid2()):i==="ulid"?n=n.check(W.ulid()):i==="xid"?n=n.check(W.xid()):i==="ksuid"&&(n=n.check(W.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?W.number().int():W.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=W.boolean();break}case"null":{o=W.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?On(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=On(f,e);jr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let y of f){let w=On(d[y],e),S=W.string().regex(new RegExp(y));p.push(W.looseRecord(S,w))}let m=[];if(Object.keys(n).length>0&&m.push(W.object(n).passthrough()),m.push(...p),m.length===0)o=W.object({}).passthrough();else if(m.length===1)o=m[0];else{let y=W.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)y=W.intersection(y,m[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=f.map(b=>new RegExp(b)),S=o;o=o.check(b=>{if(!Vo(b.value))return;let x=[];for(let k of Object.keys(b.value))y.includes(k)||w.some(T=>T.test(k))||x.push(k);x.length&&b.issues.push({code:"unrecognized_keys",keys:x,input:b.value,inst:S})})}}else{let d=W.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=On(f,e)}o=aCe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>On(d,e)),c=oW(a,s),u=Array.isArray(i)?void 0:sW(i,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>On(d,e)),c=oW(a,s),u=sW(t.additionalItems,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(i!==void 0){let s=On(i,e),a=W.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=W.array(W.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=lCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?On(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function On(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r=aW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>On(u,e)),c=W.union(a);r=o?W.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>On(u,e)),c=W.xor(a);r=o?W.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:W.any();else{let a=o?r:On(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=W.intersection(a,On(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=W.nullable(r)),t.readOnly===!0&&(r=W.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!ey(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!ey(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))nCe.has(a)||jr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function cW(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=oCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Fr};return On(r,i)}var uW=Symbol("z.visit/resolving");function ty(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===uW)return new Ep({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,uW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let m of l){let y=n(u[m]);y!==u[m]&&(d=!0),f[m]=y}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?pt(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:pt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let m=n(p);m!==p&&(l=!0),d.push(m)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?pt(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:pt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:pt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?pt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:pt(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:pt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:pt(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:pt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return pt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function lW(t){return ty(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function pCe(t,e){if(!e?.length)return t;let r=t._zod.def;return pt(t,qo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function dW(t){return pCe(t.out,t.checks)}function fCe(t){return t.in._zod.traits.has("$ZodTransform")?dW(t):t.in}function pW(t){return ty(t,{pipe:e=>fCe(e._zod.def),default:(e,r)=>r?Pt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function fW(t){return ty(t,{pipe:e=>dW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var hU={};qt(hU,{bigint:()=>yCe,boolean:()=>gCe,date:()=>vCe,number:()=>hCe,string:()=>mCe});function mCe(t){return yz(Zp,t)}function hCe(t){return wz(Wp,t)}function gCe(t){return _z(Jp,t)}function yCe(t){return Sz(Xp,t)}function vCe(t){return bz(Bg,t)}var ry={name:"@tomato414941/foundation",version:"5.0.1",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&g.config({jitless:!0});function _Ce(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var ny=g.string().trim().max(8192).refine(t=>_Ce(t)!==null,"Use an OpenSSH public key from a .pub file."),oy=g.object({authorizedKeys:g.array(ny).max(32)}).strict(),rgt=oy.extend({revision:g.number().int().positive().optional()}),gU=oy.extend({host:g.string().min(1).max(253),port:g.number().int().min(1024).max(65535),username:g.literal("root"),workingDirectory:g.literal("/workspace"),hostKey:ny.nullable(),fingerprint:g.string().nullable(),revision:g.number().int().positive(),appliedRevision:g.number().int().nonnegative(),activeSessions:g.number().int().min(0).max(1024)}).strict(),ngt=gU.extend({state:g.enum(["starting","configuring","ready","disabled","stopped"])}),ogt=g.object({hostKey:ny,appliedRevision:g.number().int().nonnegative(),activeSessions:g.number().int().min(0).max(1024)}).strict(),SCe=oy.extend({port:g.number().int().min(1024).max(65535),revision:g.number().int().positive()}).strict(),eE=g.object({configuration:SCe.nullable()}).strict();var ef=new TextEncoder,tf=new TextDecoder,mW=new TextDecoder("utf-8",{fatal:!0}),tE=2**32;function Dn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function yU(t,e,r){if(e<0||e>=tE)throw new RangeError(`value must be >= 0 and <= ${tE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function vU(t){let e=Math.floor(t/tE),r=t%tE,o=new Uint8Array(8);return yU(o,e,0),yU(o,r,4),o}function rE(t){let e=new Uint8Array(4);return yU(e,t),e}var bCe=/[^\x00-\x7f]/;function Gr(t){if(typeof t=="string"&&t.length>=128){if(bCe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return ef.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function hW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function gW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function nE(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ca=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var zl=class extends Ca{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ct=class extends Ca{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Oc=class extends Ca{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends Ca{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Zt=class extends Ca{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var iy=class extends Ca{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var oE=class extends Ca{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var xCe="The input to be decoded is not correctly encoded.";function Ml(t){try{return gW(typeof t=="string"?t:tf.decode(t),!0)}catch(e){throw new TypeError(xCe,{cause:e})}}function Qt(t){return hW(typeof t=="string"?ef.encode(t):t,!0)}function yo(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function fr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Dc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Ho(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function Qn(t,e,r){try{return Ml(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function iE(t,e,r){try{return Gr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function rf(t,e,r){let o;try{o=JSON.parse(mW.decode(Ml(t)))}catch{throw new e(r)}if(!fr(o))throw new e(r);return o}var sE={__proto__:null,b64:!0},aE={__proto__:null};function sy(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function cE(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Nc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ct(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function uE(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Zt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Ul(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!fr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var ECe=t=>t[Symbol.toStringTag],$Ce=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function Ai(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(fr(e)){if(s=EU(e),typeof s.kty!="string")throw yW(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if($Ce(t,s,r),s.kty==="oct")return Ml(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!SU(e))throw yW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${ECe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(zc(e))return e;if(a=e,a.type==="secret")return a.export()}wU||=new WeakMap;let c=e,u=wU.get(c);if(u?.[o])return u[o];if(u||wU.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=RCe[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await of(t,s)}var wU,RCe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function dE(t){if(!zc(t))throw new Error("CryptoKey instance expected")}var zc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},_U=t=>t?.[Symbol.toStringTag]==="KeyObject",SU=t=>zc(t)||_U(t);function vW(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Oa=(t,...e)=>vW("Key must be ",t,...e);function yW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(vW(`Key for the ${t} algorithm must be `,e,...o))}var lE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function bU(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function nf(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function xU(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw lE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw lE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw lE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw lE(e.length,"algorithm.length");bU(t,r)}function pE(t){return{__proto__:null,...t}}function EU(t){let e=pE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function fE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function of(t,e,r){if(!t.kty.includes(e.kty))throw new Ct('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Pi(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),xU(t,e,r),t}var Ll=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function mE(t,e){let r=t.byteLength<<3;if(r!==e)throw new H(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var ICe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function wW(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function _W(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Oa(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function SW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function ACe(t,e,r,o,n){let[i,s,a]=await _W(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Dn(n,o,c,vU(n.length*8)),l=await SW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function PCe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function kCe(t,e,r,o,n,i){let[s,a,c]=await _W(t,e,"decrypt"),u=Dn(i,o,r,vU(i.length*8)),l=await SW(a,u,c);try{if(await PCe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Oc}async function hE(t,e,r,o,n){if(!zc(r)&&!(r instanceof Uint8Array))throw new TypeError(Oa(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?wW(t,o):o=ICe(t),r instanceof Uint8Array&&mE(r,t.cekBits),t.cbc)return ACe(t,e,r,o,n);let i=await Pi(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function gE(t,e,r,o,n,i){if(!zc(e)&&!(e instanceof Uint8Array))throw new TypeError(Oa(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new H("JWE Initialization Vector missing");if(!n)throw new H("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new H("Invalid Authentication Tag length");if(wW(t,o),e instanceof Uint8Array&&mE(e,t.cekBits),t.cbc)return kCe(t,e,r,o,n,i);let s=await Pi(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Dn(r,n)))}catch{throw new Oc}}function ay(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var TCe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],CCe=[[],["deriveBits"]],wE=[[],[]];function yE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:TCe,ops:["wrapKey","unwrapKey"]}}function vE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ct('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:CCe,ops:[void 0,"deriveBits"]}}function sf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:wE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function $U(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:wE,ops:["deriveBits","deriveBits"]}}var Da=ay({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:wE,ops:["encrypt","decrypt"]},"RSA-OAEP":yE(1),"RSA-OAEP-256":yE(256),"RSA-OAEP-384":yE(384),"RSA-OAEP-512":yE(512),"ECDH-ES":vE("direct-key-agreement"),"ECDH-ES+A128KW":vE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":vE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":vE("key-agreement-with-key-wrapping"),A128KW:sf(128),A192KW:sf(192),A256KW:sf(256),A128GCMKW:sf(128,!0),A192GCMKW:sf(192,!0),A256GCMKW:sf(256,!0),"PBES2-HS256+A128KW":$U(),"PBES2-HS384+A192KW":$U(),"PBES2-HS512+A256KW":$U()}),OCe=["encrypt","decrypt"];function af(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:wE,ops:OCe,cekBits:t,ivBits:e?128:96,cbc:e}}var DCe=ay({A128GCM:af(128),A192GCM:af(192),A256GCM:af(256),"A128CBC-HS256":af(256,!0),"A192CBC-HS384":af(384,!0),"A256CBC-HS512":af(512,!0)});function bW(t,e){throw new Ct(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function ki(t){return(typeof t=="string"?Da[t]:void 0)??bW("alg","Algorithm")}function Ti(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function jl(t){return(typeof t=="string"?DCe[t]:void 0)??bW("enc","Encryption Algorithm")}function xW(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");bU(t,e)}async function NCe(t,e,r){let o=await Pi(e,ki(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function zCe(t,e,r){let o=await Pi(e,ki(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function $W(t,e,r){xU(e,ki(t).subtle,r),nf(t,e)}async function RW(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new H("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new H("PBES2 Count Input must be a positive integer");let n=Dn(Gr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Pi(o,ki(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function RU(t){return Dn(rE(t.length),t)}async function MCe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await nE("sha256",Dn(rE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function IW(t,e,r,o,n=new Uint8Array,i=new Uint8Array){xW(t),xW(e,"deriveBits");let s=Dn(RU(Gr(r)),RU(n),RU(i),rE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return MCe(a,o,s)}function AW(t){dE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ct("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function _E(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new H(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return Qn(r,e,H)}}function PW(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new H('JOSE Header "apu" and "apv" values must be distinct')}}function UCe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function EW(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function LCe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function kW(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return EW(o),r;let c=a==="direct-key-agreement";switch(c?EW(o):UCe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!fr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');AW(r);let l=await of(t,u),d=_E(n,"apu"),f=_E(n,"apv");PW(d,f);let p=await IW(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return dE(r),$W(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new H('JOSE Header "p2c" (PBES2 Count) missing or invalid');LCe(i);let u=i??1e4;if(n.p2c>u)throw new H('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new H('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=Qn(n.p2s,"p2s",H);r=await RW(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new H('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new H('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=Qn(n.iv,"iv",H),l=Qn(n.tag,"tag",H);if(u.byteLength!==12)throw new H("Invalid Initialization Vector length");if(l.byteLength!==16)throw new H("Invalid Authentication Tag length");return gE(jl(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return zCe(s.slice(-6),r,o)}async function SE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Ti(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Ai(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Ll(e):void 0;l&&mE(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{AW(u);let{apu:p,apv:m}=i;p!==void 0&&yo(p,'"apu"'),m!==void 0&&yo(m,'"apv"');let y=p??_E(o,"apu"),w=m??_E(o,"apv");PW(y,w);let S;i.epk!==void 0?S=await Ai(t,i.epk,"decrypt"):S=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,x=S;if(!x.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await b.getPublicKey(S,[])}let{x:k,y:T,crv:U,kty:X}=await b.exportKey("jwk",x),ue=a==="direct-key-agreement",Me=await IW(u,S,ue?e.alg:s,ue?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),De={x:k,crv:U,kty:X};if(X==="EC"&&(De.y=T),f={epk:De},p!==void 0&&(f.apu=Qt(p)),m!==void 0&&(f.apv=Qt(m)),ue)return[Me,void 0,f];u=Me;break}case"RSA-OAEP":{dE(u),$W(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await RW(m,s,p,u),f={p2c:p,p2s:Qt(m)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await hE(jl(s.slice(0,-2)),l,u,p,new Uint8Array);d=m.ciphertext,f={iv:Qt(m.iv),tag:Qt(m.tag)}}}if(d??=await NCe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,f]}function bE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ct('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function TW(t){if(typeof globalThis[t]>"u")throw new Ct(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function CW(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new H("Decompressed plaintext exceeded the configured limit")}return Dn(...n)}async function OW(t){return TW("CompressionStream"),CW(new CompressionStream("deflate-raw"),t)}async function DW(t,e){return TW("DecompressionStream"),CW(new DecompressionStream("deflate-raw"),t,e)}function NW(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new H("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new H("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new H("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new H("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new H("JWE AAD incorrect type");if(s!==void 0&&!fr(s))throw new H("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function zW(t){let e,r;try{let{header:o}=t;if(fr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function MW(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new H("JWE Encrypted Key incorrect type");if(r!==void 0&&!fr(r))throw new H("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new H("JOSE Header missing")}function IU(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=rf(e,H,"JWE Protected Header is invalid")),[s,Qn(r,"ciphertext",H),o!==void 0?Qn(o,"iv",H):void 0,n!==void 0?Qn(n,"tag",H):void 0,iE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function xE(t){return[t&&sy("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&sy("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function AU(t,e,r,o=IU(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Dc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,m,y,w,S]=e,{encrypted_key:b}=t;Nc(H,aE,y,n,f),bE(f,n);let{alg:x,enc:k}=f;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Da[x];if(b===""&&(!T||!Ti(T)))throw new H("JWE Encrypted Key incorrect type");let U=T?.mode==="integrated-encryption";if(!U&&(typeof k!="string"||!k))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(x)||!p&&x.startsWith("PBES2"))throw new zl('"alg" (Algorithm) Header Parameter value not allowed');let X;if(U){if(k!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new H("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new H("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(k))throw new zl('"enc" (Encryption Algorithm) Header Parameter value not allowed');X=jl(k)}let ue;if(b!==void 0)try{ue=Qn(b,"encrypted_key",H)}catch(Ue){if(!T||!Ti(T))throw Ue;ue=new Uint8Array}let Me=!1;typeof r=="function"&&(r=await r(n,t),Me=!0);let De=T??ki(x);Ti(De)&&ue===void 0&&(ue=new Uint8Array);let $t=await Ai(De.mode==="direct-encryption"?X:De,r,"decrypt"),at;if(De.mode==="integrated-encryption")at=await De.decrypt($t,ue,i,c,n,f);else{let Ue=X,oe;try{oe=await kW(De,Ue,$t,ue,f,w),Ti(De)&&oe instanceof Uint8Array&&oe.byteLength<<3!==Ue.cekBits&&(oe=Ll(Ue))}catch(Xt){if(Xt instanceof TypeError||Xt instanceof H||Xt instanceof Ct)throw Xt;oe=Ll(Ue)}at=await gE(Ue,oe,i,s,a,c)}if(f.zip==="DEF"){let Ue=S??25e4;if(Ue===0)throw new Ct('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ue!==1/0&&(!Number.isSafeInteger(Ue)||Ue<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");at=await DW(at,Ue).catch(oe=>{throw oe instanceof H?oe:new H("Failed to decompress plaintext",{cause:oe})})}return{plaintext:at,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:Qn(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Me&&{key:$t}}}async function UW(t,e,r){if(t instanceof Uint8Array&&(t=tf.decode(t)),typeof t!="string")throw new H("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new H("Invalid Compact JWE");return AU({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function cy(t,e,r){return UW(t,xE(r),e)}async function PU(t,e,r){if(!fr(t))throw new H("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new H("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(fr))throw new H("JWE Recipients missing or incorrect type");if(!n.length)throw new H("JWE Recipients has no members");let i,s,a;try{i=xE(r),s=NW(t),a=IU(s)}catch{throw new Oc}let c=n.map(u=>zW(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Da[l]:void 0;if(d&&!Ti(d))throw new H(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return MW(l),await AU(l,i,e,a)}catch{}throw new Oc}function EE(t,e,r){if(!Dc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function kU(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new H("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&yo(s,"JWE Additional Authenticated Data"),a!==void 0&&yo(a,"JWE Content Encryption Key"),c!==void 0&&yo(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Ul(H,o)[0],t[1]=o),n!==void 0&&(n=Ul(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=Ul(H,i)[0],t[3]=i),u!==void 0&&!fr(u))throw new TypeError("JWE Key Management Parameters must be an object");EE(o,n,i);let d={...o,...n,...i};cE(H,o),Nc(H,aE,l,o,d),bE(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Da[f];if(m?.mode==="integrated-encryption"){if(p!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!="string"||!p)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,jl(p),m]}async function TU(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,m]=t,y=a,w=c,S=i??ki(o.alg),b,x,k;S.mode==="integrated-encryption"?k=await Ai(S,r,"encrypt"):[k,b,x]=await SE(S,n,r,o,d,p),x&&(m?w=w?{...w,...x}:x:y=y?{...y,...x}:x,EE(y,w,u));let T=y?Qt(JSON.stringify(y)):"",U=l?.byteLength?Qt(l):void 0,X=Gr(U?`${T}.${U}`:T),ue=s;o.zip==="DEF"&&(ue=await OW(ue).catch(Ue=>{throw new H("Failed to compress plaintext",{cause:Ue})}));let Me,De,$t;S.mode==="integrated-encryption"?[b,Me]=await S.encrypt(k,ue,X,y,o,p):{ciphertext:Me,tag:De,iv:$t}=await hE(n,ue,k,f,X);let at={ciphertext:Qt(Me)};return $t&&(at.iv=Qt($t)),De&&(at.tag=Qt(De)),b?.byteLength&&(at.encrypted_key=Qt(b)),U&&(at.aad=U),y&&(at.protected=T),u&&(at.unprotected=u),w&&(at.header=w),at}async function LW(t,e,r){return TU(t,kU(t,r),e)}function jW(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var CU=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Ho(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Ho(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},uy=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new CU(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Ho(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Ho(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new H("at least one recipient must be added");yo(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[y,w,S,b]=m.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,b,e],k=kU(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,k,S]);let[{alg:T,enc:U},,X]=k;if(e&&X&&!Ti(X))throw new H(`"${T}" alg may only have a single recipient`);if(!r)r=U;else if(r!==U)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=ki(m[0].alg);let[s,a,c]=i[0],u=e?Ll(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await TU(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let m=1;m<i.length;m++){let[y,[w,S,b],x]=i[m],k=y[2],[,T,U]=await SE(b,S,x,w,u,y[7]),X={encrypted_key:Qt(T)};if(k||U){let ue={...k,...U};U&&EE(y[1],ue,y[3]),X.header=ue}p.recipients.push(X)}return p}};var ly=[["verify"],["sign"]];function OU(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:ly}}function cf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:ly,minRsaBits:2048}}function DU(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:ly}}function FW(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:ly}}function NU(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:ly}}var zU=ay({HS256:OU(256),HS384:OU(384),HS512:OU(512),RS256:cf(256),RS384:cf(384),RS512:cf(512),PS256:cf(256,32),PS384:cf(384,48),PS512:cf(512,64),ES256:DU("P-256",256),ES384:DU("P-384",384),ES512:DU("P-521",512),EdDSA:FW(),Ed25519:FW(),"ML-DSA-44":NU(44),"ML-DSA-65":NU(65),"ML-DSA-87":NU(87)});function $E(t){let e=typeof t=="string"?zU[t]:void 0;if(!e)throw new Ct(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function qW(t){return[t&&sy("algorithms",t.algorithms),t?.crit]}function jCe(t){return t===void 0?{}:rf(t,Zt,"JWS Protected Header is invalid")}function FCe(t){try{return Gr(t)}catch{throw new Zt("JWS Compact Serialization payload must use only ASCII characters")}}async function qCe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??jCe(i);if(!Dc(c,s))throw new Zt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=uE(c,Nc(Zt,sE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Zt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new zl('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Zt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Zt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let m=$E(d),y=Dn(i!==void 0?Gr(i):new Uint8Array,Gr("."),typeof f=="string"?e[2]??=iE(f,"payload",Zt):f),w=Qn(t.signature,"signature",Zt),S=await Ai(m,r,"verify"),b=await Pi(S,m.subtle,"verify");m.minRsaBits&&nf(m.alg,b);let x=!1;try{x=await crypto.subtle.verify(m.signing,b,w,y)}catch{}if(!x)throw new oE;let k={payload:typeof f=="string"?Qn(f,"payload",Zt):f};return i!==void 0&&(k.protectedHeader=c),s!==void 0&&(k.unprotectedHeader=s),p?[{...k,key:S},l]:[k,l]}async function VW(t,e,r){if(t instanceof Uint8Array&&(t=tf.decode(t)),typeof t!="string")throw new Zt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Zt("Invalid Compact JWS");return qCe({payload:n,protected:o,signature:i},e,r,FCe)}async function MU(t,e,r){let[o]=await VW(t,qW(r),e);return o}var uf=class{#e;constructor(e){yo(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Ho(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Ho(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Ho(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Ho(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return jW(await LW([...this.#e],e,r))}};async function VCe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let S=Ul(Zt,n);n=S[0],a=Qt(S[1])}if(i!==void 0&&(i=Ul(Zt,i)[0]),!n&&!i)throw new Zt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Dc(n,i))throw new Zt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};cE(Zt,n);let u=uE(n,Nc(Zt,sE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Zt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=$E(l),f="",p=o,m;if(u){let S=t[4];S?(f=S[0]??=Qt(o),p=S[1]??=Gr(f)):(f=Qt(o),m=ef.encode(`${a}.${f}`))}m??=Dn(Gr(a),Gr("."),p);let y=await Pi(await Ai(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&nf(d.alg,y);let w={signature:Qt(new Uint8Array(await crypto.subtle.sign(d.signing,y,m))),payload:f};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function GW(t,e,r,o,n){let[i]=await VCe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var dy=class{#e;#t;constructor(e){yo(e,"payload"),this.#e=e}setProtectedHeader(e){return Ho(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return GW(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var UU='"alg" (Algorithm)';function LU(t='JWK "alg" (Algorithm) Parameter'){throw new Ct(`Invalid or unsupported ${t} value`)}function py(t,e){return(typeof t=="string"?zU[t]??Da[t]:void 0)??LU(e)}async function Mc(t){if(_U(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Qt(t)};if(!zc(t))throw new TypeError(Oa(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var Na=(t,e)=>{if(typeof t!="string"||!t)throw new iy(`${e} missing or invalid`)};async function jU(t,e){let r;if(fr(t)){if(r=pE(t),typeof r.kty!="string")throw new TypeError(Oa(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(SU(t))r=pE(await Mc(t));else throw new TypeError(Oa(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":Na(r.alg,'"alg" (Algorithm) Parameter'),Na(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Na(r.crv,'"crv" (Curve) Parameter'),Na(r.x,'"x" (X Coordinate) Parameter'),Na(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Na(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Na(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Na(r.e,'"e" (Exponent) Parameter'),Na(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new iy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ct('"kty" (Key Type) Parameter missing or unsupported')}let n=Gr(JSON.stringify(o));return Qt(await nE(e,n))}async function Bo(t,e,r){if(!fr(t))throw new TypeError("JWK must be an object");let o=EU(t),n=fE(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return Ml(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return of(py(e),o,n)}case"RSA":case"EC":case"OKP":return of(py(e),o,n);default:throw new Ct('Unsupported "kty" (Key Type) Parameter value')}}function FU(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return rf(e,TypeError,r)}function GCe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ct("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function fy(t,e){let r=fE(e?.extractable),o=py(t,UU);o.secret&&LU(UU);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ct("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ct(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:GCe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var ZW=g.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),WW=g.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),HW=g.string().min(1).max(128),BW=g.string().min(1).max(16384),HCe=g.discriminatedUnion("kind",[g.object({kind:g.literal("access_key"),accessKeyId:HW,secretAccessKey:BW}).strict(),g.object({kind:g.literal("session"),accessKeyId:HW,secretAccessKey:BW,sessionToken:g.string().min(1).max(16384),expiresAt:g.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),g.object({kind:g.literal("environment")}).strict()]),BCe=g.object({arn:WW,externalId:g.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),za=g.object({authentication:HCe,region:ZW,role:BCe.optional()}).strict(),RE=g.object({accountId:g.string().regex(/^\d{12}$/),principalId:g.string().min(1).max(256),arn:g.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),IE=za.extend({sourceIdentity:RE,identity:RE}).strict();function lf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function KW(t){return{...t,arn:lf(t.arn)}}function JW(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,sourceIdentity:KW(t.sourceIdentity),identity:KW(t.identity)}}var AE=g.object({authentication:g.enum(["access_key","session","environment"]),region:ZW,sourceAccountId:g.string().regex(/^\d{12}$/),sourceArn:g.string().max(2e3),roleArn:WW.optional(),expiresAt:g.number().int().positive().optional()}).strict();function XW(t){return{authentication:t.authentication.kind,region:t.region,sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn,...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}typeof window<"u"&&g.config({jitless:!0});var E=g.uuid(),pe=g.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),nt=g.iso.datetime(),ln=g.json(),er=g.record(g.string(),ln),QW=g.enum(["ja","en"]),e5=g.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var t5=g.enum(["variable","connection","service","method","app","object","environment","function"]),dn=g.object({kty:g.literal("EC"),crv:g.literal("P-256"),x:g.string().min(40).max(50),y:g.string().min(40).max(50)}).strict(),KCe=g.object({alg:g.literal("dir"),enc:g.literal("A256GCM"),sub:E}).strict(),TE=g.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return KCe.safeParse(FU(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),vo=g.object({protected:g.string().max(2048),iv:g.string().max(64),ciphertext:g.string().max(2e6),tag:g.string().max(64),aad:g.string().max(2048).optional(),recipients:g.array(g.object({encrypted_key:g.string().max(2048),header:g.object({kid:E,epk:dn.optional(),alg:g.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Mvt=g.object({id:E,name:pe,publicKey:dn}),df=g.object({id:E,name:pe,owner:g.object({id:E,name:pe}).nullable(),createdAt:nt,permissions:g.array(e5),createKinds:g.array(t5),publicKey:dn.nullable()}),r5=g.object({id:E,kind:g.enum(["passkey","email","key"]),name:g.string(),createdAt:nt,lastUsedAt:nt.nullable(),expiresAt:nt.nullable(),canOpen:g.boolean()}),n5=g.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ZCe=g.object({subjectId:E,relation:n5,objectId:E}).strict(),Uvt=ZCe.extend({objectType:g.enum(["principal",...t5.options]),subjectName:pe,objectName:pe,createdAt:nt}),Lvt=g.object({error:g.object({code:g.string(),message:g.string(),details:ln.optional()})}),jvt=g.object({ok:g.literal(!0)}),o5=g.object({name:g.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:g.string(),secret:g.boolean().optional(),required:g.boolean().optional(),placeholder:g.string().optional(),note:g.string().optional(),pattern:g.string().optional()}),i5=g.record(g.string().regex(/^[A-Z_][A-Z0-9_]*$/),g.string()),WCe=g.object({values:g.array(g.object({id:g.string(),name:g.string(),description:g.string().optional()})).optional(),default:g.array(g.string()).default([]),required:g.array(g.string()).optional(),separator:g.string().default(" "),docs:g.url().optional()}),PE=g.string().min(1).max(4096),YW=g.union([g.string(),g.array(g.string()).min(1)]),JCe=g.object({application:g.enum(["required","implicit"]).default("required"),grantType:g.enum(["authorization_code","client_credentials"]).optional(),issuer:g.url().optional(),authorizeUrl:PE.optional(),tokenUrl:PE,identity:g.object({url:PE.optional(),from:g.enum(["token","app"]).optional(),method:g.enum(["GET","POST"]).default("GET"),id:YW.default("/id"),name:YW.default("/name"),headers:g.record(g.string(),g.string()).default({})}).optional(),revoke:g.object({url:PE,style:g.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:g.enum(["body","basic","none"]).optional()}).optional(),clientAuth:g.enum(["body","basic","none"]).default("body"),pkce:g.boolean().default(!0),tokenFormat:g.enum(["form","json"]).default("form"),okPointer:g.string().optional(),authorizeParams:g.record(g.string(),g.string()).default({}),tokenParams:g.record(g.string(),g.string()).default({}),defaults:g.record(g.string(),g.string()).default({}),scopes:WCe.default({default:[],separator:" "}),fields:g.array(o5).default([]),outputs:i5.default({ACCESS_TOKEN:"/accessToken"}),adapter:g.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:g.array(g.string()).default([]),hint:g.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),XCe=g.object({fields:g.array(o5).min(1),outputs:i5,console:g.url().optional(),instructions:g.string().optional(),hint:g.string().optional()}),VU=g.enum(["oauth","token","aws"]),YCe=g.object({hint:g.string().optional()}).strict(),GU={name:pe,docs:g.url().optional(),console:g.url().optional()},CE=g.object({...GU,kind:g.literal("oauth"),config:JCe}).strict(),OE=g.object({...GU,kind:g.literal("token"),config:XCe}).strict(),DE=g.object({...GU,kind:g.literal("aws"),config:YCe}).strict(),Fl=g.discriminatedUnion("kind",[CE,OE,DE]),qU={id:g.string().min(1),builtin:g.boolean(),availability:g.enum(["ready","app-required","unavailable"])},my=g.discriminatedUnion("kind",[CE.extend(qU),OE.extend(qU),DE.extend(qU)]),HU=g.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),BU=g.object({name:pe,logo:g.string().regex(/^[a-z0-9-]+$/).optional(),api:g.url().optional(),docs:g.url().optional(),console:g.url().optional()}).strict(),QCe=BU.extend({methods:g.record(HU,g.string().min(1))}).strict(),s5=BU.extend({methods:g.record(HU,g.union([g.string().min(1),Fl]))}).strict(),Fvt=BU.extend({id:g.string(),builtin:g.boolean(),methods:g.record(HU,my)}),a5=g.object({id:E,output:g.string().min(1).max(100).optional()}).strict(),c5=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),KU=g.object({name:g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:a5,format:g.enum(["text","file","json"]).default("text"),pointer:g.string().optional()}).strict(),eOe=g.object({pointer:g.string().max(500),parts:g.array(g.union([g.string().max(8192),a5])).min(1).max(32)}).strict(),Ma=g.object({url:g.string().max(4096),method:g.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:g.record(g.string(),g.string().max(8192)).default({}),body:g.string().max(1e6).optional(),json:ln.optional(),form:g.record(g.string(),g.string()).optional(),bindings:g.array(eOe).max(32).default([])}).strict(),Ua=g.object({command:g.array(g.string().max(8192)).min(1).max(100),stdin:g.string().max(1e6).optional(),timeoutSeconds:g.number().int().min(1).max(3600).default(60),inputs:g.array(KU).max(32).default([])}).strict(),tOe=g.discriminatedUnion("kind",[Ua.omit({stdin:!0}).extend({kind:g.literal("command")}).strict(),g.object({kind:g.literal("http"),request:Ma}).strict()]),ql=g.object({description:g.string().max(2e3).default(""),environmentId:E,program:tOe,parameters:g.array(g.object({name:g.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:g.string().max(100),type:g.enum(["string","number","boolean","json"]).default("string"),required:g.boolean().default(!0),default:ln.optional()}).strict()).max(32).default([]),result:g.enum(["text","json"]).default("json")}).strict(),Uc={id:E,ownerId:E,name:pe,createdAt:nt,updatedAt:nt,version:g.number().int().positive(),permissions:g.array(e5)},rOe=g.enum(["starting","running","stopping","stopped","failed"]),nOe=g.object({state:g.enum(["pending","failed","complete"]),error:g.string().nullable()}),oOe=g.object({idleSeconds:g.number().int().min(60).max(86400).default(3600),maxSeconds:g.number().int().min(60).max(86400).default(3600)}).strict(),u5=g.object({image:g.string().min(1).max(300).optional(),size:g.enum(["small","medium","large"]).default("small"),lifetime:oOe.default({idleSeconds:3600,maxSeconds:3600}),ssh:oy.optional()}).strict(),ZU={recipients:g.array(E).default([]),executors:g.array(E).default([]),custodyRevision:g.number().int().positive().nullable().default(null)},iOe=g.object({...Uc,kind:g.literal("variable"),data:g.object({...ZU,bytes:g.number().int().nonnegative()})}),sOe=g.object({...Uc,kind:g.literal("connection"),data:g.object({...ZU,methodId:g.string(),methodName:g.string(),methodKind:VU,services:g.array(g.object({id:g.string(),name:pe})).default([]),account:g.string(),accountId:g.string().nullable().default(null),accountVerified:g.boolean().default(!1),scopes:g.array(g.string()),scopesStatus:g.enum(["unknown","requested","reported"]).default("unknown"),outputs:g.array(g.string()),state:g.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:g.string().optional(),aws:AE.optional()})}),aOe=g.object({...Uc,kind:g.literal("service"),data:QCe}),cOe=g.object({...Uc,kind:g.literal("method"),data:Fl}),uOe=g.object({...Uc,kind:g.literal("app"),data:g.object({...ZU,methodId:g.string(),clientId:g.string(),fields:g.record(g.string(),g.string()).default({}),generation:E.optional()})}),lOe=g.object({...Uc,kind:g.literal("object"),data:g.object({size:g.number().int().nonnegative(),contentType:g.string()})}),dOe=g.object({...Uc,kind:g.literal("environment"),data:u5.extend({executorId:E.optional(),operatorId:E.optional(),driver:g.enum(["attached","managed"]).optional(),capabilities:g.array(g.string()).optional(),isolation:g.enum(["process","container"]).optional(),manifestDigest:g.string().optional(),processes:g.object({workingDirectory:g.string()}).optional(),ssh:gU.optional(),awsPrincipal:g.string().optional(),state:rOe,deletion:nOe.optional(),startedAt:nt.nullable(),stoppedAt:nt.nullable(),lastActiveAt:nt,error:g.string().nullable()})}),pOe=g.object({...Uc,kind:g.literal("function"),data:ql}),pn=g.discriminatedUnion("kind",[iOe,sOe,aOe,cOe,uOe,lOe,dOe,pOe]),qvt=g.discriminatedUnion("kind",[g.object({kind:g.literal("service"),name:pe,definition:s5}).strict(),g.object({kind:g.literal("method"),name:pe,definition:Fl}).strict(),g.object({kind:g.literal("environment"),name:pe.optional(),options:u5}).strict()]),Vvt=g.object({version:g.number().int().positive(),name:pe.optional(),definition:g.union([s5,Fl]).optional()}).strict(),Ci=g.object({name:g.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:er}).strict(),l5=Ci.extend({inputs:g.array(g.object({pointer:g.string(),label:g.string().min(1).max(100),secret:g.boolean().default(!1),multiline:g.boolean().default(!1),site:g.url().optional()}).strict()).max(16).default([])}),WU=g.object({ja:g.string(),en:g.string()}).strict(),d5=g.object({to:E.optional(),message:g.string().max(1e3).default(""),operations:g.array(l5).min(1).max(8),expiresInMinutes:g.number().int().min(1).max(1440).default(30)}).strict(),kE=g.object({id:E,name:pe}),fOe=g.discriminatedUnion("kind",[g.object({kind:g.literal("line"),subject:kE,relation:n5,object:kE}),g.object({kind:g.literal("transfer"),item:kE,to:kE})]),pf=g.object({id:E,from:df.pick({id:!0,name:!0}),to:df.pick({id:!0,name:!0}).nullable(),message:g.string(),proposal:fOe.nullable(),operations:g.array(l5.extend({title:WU,execution:g.enum(["server","keyholder"])})),state:g.enum(["pending","running","approved","declined","cancelled","expired"]),results:g.array(ln.nullable()),createdAt:nt,expiresAt:nt,url:g.url(),code:g.string().optional(),returnUrl:g.url().nullable(),refreshUrl:g.url().nullable(),canRespond:g.boolean(),waiting:g.object({index:g.number().int().nonnegative(),invocation:Ci,approval:g.object({id:E,index:g.number().int().nonnegative()}).strict().optional(),continuation:g.object({kind:g.enum(["connection","run"]),id:E}).strict().nullable()}).strict().nullable()}),Gvt=g.object({id:E,name:pe,publicKey:dn,state:g.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:nt,expiresAt:nt}),Hvt=g.object({available:g.boolean(),required:g.boolean(),active:g.boolean(),payer:df.pick({id:!0,name:!0}).nullable()}),Bvt=g.object({storageBytes:g.number().nonnegative(),storageLimit:g.number().positive(),computeSeconds:g.number().nonnegative(),computeLimit:g.number().positive(),month:g.string()}),Kvt=g.object({id:g.string(),actorId:E.nullable(),action:g.string(),targetId:E.nullable(),createdAt:nt,details:er}),Zvt=g.object({returnUrl:g.url().optional(),refreshUrl:g.url().optional()}).strict(),wo=t=>g.object({items:g.array(t),next:g.string().nullable().default(null)}),Wvt=g.object({id:E}),Jvt=g.object({owner:E}),mOe=g.object({limit:g.coerce.number().int().min(1).max(200).default(100),after:g.string().optional()}),Xvt=mOe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var hOe=g.object({email:g.boolean(),environments:g.boolean(),ssh:g.boolean(),objects:g.boolean(),payments:g.boolean()}),NE=g.object({principal:df.nullable(),credentialId:E.nullable(),wrappedKey:TE.nullable(),requestId:E.nullable(),server:g.object({name:pe}),features:hOe,principals:g.array(df)}),twt=g.object({email:g.email().max(254),returnTo:g.string().max(2048).optional(),locale:QW.default("ja"),principalId:E.optional()}).strict(),rwt=g.object({intent:g.enum(["register","authenticate"]),name:pe.optional(),principalId:E.optional(),returnTo:g.string().max(2048).optional()}).strict(),nwt=g.object({challengeId:E,credential:g.json(),publicKey:dn.optional(),existingPublicKey:dn.optional(),wrappedKey:TE.optional()}).strict();var gOe=new TextEncoder,yOe=new TextDecoder,hy="ECDH-ES+A256KW",JU="A256GCM",mt=t=>gOe.encode(t),La=t=>yOe.decode(t);function Lc(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function p5(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function zE(){let t=await fy(hy,{crv:"P-256",extractable:!0});return{publicKey:dn.parse(await Mc(t.publicKey)),privateKey:await Mc(t.privateKey)}}async function ja(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new uy(t).setProtectedHeader({enc:JU}).setAdditionalAuthenticatedData(mt(r));for(let n of e)o.addRecipient(await Bo(n.publicKey,hy)).setUnprotectedHeader({alg:hy,kid:n.id});return vo.parse(await o.encrypt())}async function Ko(t,e,r,o){if(t.aad!==Lc(mt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await Bo(e,hy);return(await PU({...t,recipients:[n]},i,{keyManagementAlgorithms:[hy],contentEncryptionAlgorithms:[JU]})).plaintext}async function vOe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:mt("Foundation"),info:mt("passkey encryption key")},e,256))}async function f5(t,e,r){let o=await cy(t,await vOe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[JU]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(La(o.plaintext))}var Ar=g.string().regex(/^[A-Za-z0-9_-]{43}$/),Nn=g.string().min(100).max(4e6),m5=dn.extend({d:g.string().regex(/^[A-Za-z0-9_-]{43}$/)}),gy=g.object({encryption:m5,signing:m5}).strict(),Pr=g.object({id:E,principalId:E,generation:g.number().int().positive(),previous:Ar.nullable(),encryption:dn,signing:dn}).strict();function D(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,D).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+D(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function ff(t){return jU(dn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function me(t){return Lc(new Uint8Array(await crypto.subtle.digest("SHA-256",mt(D(t)))))}async function Vl(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",mt(D(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function UE(){let[t,e]=await Promise.all([zE(),fy("ES256",{crv:"P-256",extractable:!0})]),r=await Mc(e.privateKey);return gy.parse({encryption:t.privateKey,signing:r})}function ME(t){return dn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function LE(t,e){return Pr.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:ME(e.encryption),signing:ME(e.signing)})}async function fn(t,e,r){let o=e instanceof CryptoKey?e:await Bo(e,"ES256");return new dy(mt(D(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function eo(t,e,r,o){if(D(await XU(e,r,o))!==D(t))throw new Error("The signature does not authorize this content.")}async function XU(t,e,r){let o=await MU(t,await Bo(dn.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(D(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Rs=g.object({binding:Pr,signature:Nn}).strict();async function yy(t,e){if(await jc(t),await ff(e.encryption)!==await ff(t.encryption)||await ff(e.signing)!==await ff(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await fn(t,e.signing,"key-binding")}}async function jc(t){let e=Pr.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await ff(e.encryption)===await ff(e.signing))throw new Error("Use separate encryption and signing keys.");await Bo(e.encryption,"ECDH-ES+A256KW"),await Bo(e.signing,"ES256")}async function YU(t){let{binding:e,signature:r}=Rs.parse(t);return await jc(e),await eo(e,r,e.signing,"key-binding"),e}var h5=g.object({ownerId:E,name:pe,resourceId:E.optional(),version:g.number().int().positive().optional(),environmentIds:g.array(E).max(32).optional()}).strict(),g5=h5.extend({value:g.literal("").optional()}),QU=h5.extend({methodId:g.string().min(1).max(200),clientId:g.string().max(1e3),fields:g.record(g.string(),g.literal("")).default({}),clientSecret:g.literal("").optional()}),jE=g.object({ownerId:E,name:pe,definition:ql,resourceId:E.optional(),version:g.number().int().positive().optional()}).strict(),FE=g.object({ownerId:E,methodId:g.string().min(1).max(200),connectionId:E.optional(),environmentId:E.optional(),name:pe.optional(),appId:E.optional(),environments:g.array(E).max(32).optional(),redirectUri:g.url().optional(),methodDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:g.string().max(1e3).optional(),fields:g.record(g.string(),g.literal("")).optional(),clientSecret:g.literal("").optional()}).strict(),vy=g.object({ownerId:E,environmentId:E.optional(),operation:g.union([g.object({kind:g.literal("http"),request:Ma}).strict(),Ua.extend({kind:g.literal("command")}),g.object({kind:g.literal("function"),functionId:E,definitionDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),arguments:er.default({})}).strict(),g.object({kind:g.enum(["http","command","function"]),programId:E,programDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/),functionId:E.optional(),definitionDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/).optional()}).strict()]),save:g.record(g.string(),pe).default({})}).strict().superRefine((t,e)=>{t.operation.kind!=="function"&&!t.environmentId&&e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."}),t.operation.kind==="function"&&!t.operation.functionId&&e.addIssue({code:"custom",path:["operation","functionId"],message:"Choose a saved function."})}),eL=g.object({name:Ci.shape.name,title:WU,execution:g.enum(["server","keyholder"]),input:er}).strict(),mf=g.object({index:g.number().int().nonnegative(),invocation:Ci,approval:g.object({id:E,index:g.number().int().nonnegative()}).strict().optional(),continuation:g.object({kind:g.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),_o=g.object({id:E,actorId:E,index:g.number().int().nonnegative(),state:g.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:g.enum(["approval","input"]).nullable(),waiting:mf.nullable(),results:g.array(ln.nullable()),createdAt:g.iso.datetime(),expiresAt:g.iso.datetime()}).strict(),y5=g.object({id:E,index:g.number().int().nonnegative(),invocation:Ci,continuationId:E.optional()}).strict();var hf=g.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ht={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632"},wOe=g.enum([ht.value,ht.tokenSet,ht.clientCredential]),le={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"},wy=g.enum([le.http,le.command,le.function,le.connect,le.refresh,le.revoke]);var _Oe={[ht.value]:[le.http,le.command,le.function],[ht.tokenSet]:[le.http,le.command,le.function,le.refresh,le.revoke],[ht.clientCredential]:[le.connect,le.refresh,le.revoke]},qE=t=>_Oe[t],tL=t=>qE(t).filter(e=>e===le.function||e===le.refresh),rL=t=>t===ht.tokenSet,SOe=g.object({id:E,digest:Ar}).strict(),bOe=g.object({actor:Pr,executor:Pr,operations:g.array(wy).min(1).max(6),functionDigests:g.array(Ar).max(100).default([]),origins:g.array(hf).max(100).default([]),callerProgram:g.boolean().default(!1),expiresAt:nt}).strict(),xOe=g.object({function:SOe,executor:Pr,operations:g.array(wy).min(1).max(6),expiresAt:nt}).strict(),EOe=g.union([bOe,xOe]),Di=g.object({format:g.literal(2),origin:hf,id:E,ownerId:E,contentType:wOe,revision:g.number().int().positive(),authorities:g.array(Pr).min(1).max(100),readers:g.array(Pr).min(1).max(100),grants:g.array(EOe).max(100),observers:g.array(E).max(100).optional(),producers:g.array(g.object({executor:Pr,runId:E,expiresAt:nt,materialRevision:g.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),v5=g.object({ownerId:E,authorities:g.array(Pr).min(1).max(100)}).strict(),w5=g.object({origin:hf,id:E,revision:g.number().int().positive(),from:v5,to:v5,policyDigest:Ar,previous:Ar.nullable(),signerId:E}).strict(),$Oe=w5.extend({signature:Nn}),nL=g.array($Oe).max(16),_y=g.object({policy:Di,authorityId:E,signature:Nn,lineage:nL.optional()}).strict(),So=g.object({policy:Di,authorityId:E,authorization:Nn,lineage:nL.optional(),materialRevision:g.number().int().positive(),updatedAt:nt,creationRunId:E.nullable(),metadata:er,sealed:vo,signerId:E,signature:Nn}).strict(),Gl=t=>({ownerId:t.ownerId,authorities:t.authorities});async function _5(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||D(r.to)!==D(o.from))||o.previous!==(r?await me(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await eo(i,n,s.signing,"authority-handoff"),r=o}if(r&&D(r.to)!==D(Gl(t)))throw new Error("Use the authorities approved by the latest handoff.")}function oL(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function S5(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=D(Gl(t));return r===D(Gl(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&D(o.from)===r)}async function b5(t,e,r,o){let n=[...t?.lineage??[]];if(t&&D(Gl(t.policy))!==D(Gl(e))){if(await Oi(t),!t.policy.authorities.some(s=>D(s)===D(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=w5.parse({origin:e.origin,id:e.id,revision:e.revision,from:Gl(t.policy),to:Gl(e),policyDigest:await me(e),previous:n.length?await me(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await fn(i,o.signing,"authority-handoff")})}return n.length?{lineage:nL.parse(n)}:{}}async function VE(t){let e=Di.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await jc(n);let i=D(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!qE(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==le.function&&i!==le.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===le.http||i===le.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(le.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function GE(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function gf(t,e){return D({purpose:"resource",policyDigest:await me(t),materialRevision:e})}async function HE(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await VE(e),c=await b5(s,a,o,n);if(!a.authorities.some(f=>D(f)===D(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await ja(t,GE(a).map(f=>({id:f.id,publicKey:f.encryption})),await gf(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await fn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ht.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=So.parse({...l,signature:await fn(l,n.signing,"resource")});return await Oi(d),d}async function Oi(t){let e=So.parse(t),{signature:r,...o}=e;await VE(e.policy),await _5(e.policy,e.lineage);let n=oL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await me(e.policy))throw new Error("The handoff approves a different access policy.");await eo(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor??(rL(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(le.refresh)&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await eo(o,r,s.signing,"resource");let a=GE(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(D(a)!==D(c)||e.sealed.aad!==Lc(mt(await gf(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function x5(t,e,r,o,n=t.metadata){let i=await Oi(t);if(!rL(i.policy.contentType)||!(i.policy.authorities.some(f=>D(f)===D(r))||i.policy.grants.some(f=>D(f.executor)===D(r)&&f.operations.includes(le.refresh)&&Date.parse(f.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await ja(e,GE(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await gf(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await fn(l,o.signing,"resource")};return await Oi(d),d}async function BE(t,e,r,o){let n=await VE(t);if(!n.authorities.some(s=>D(s)===D(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await b5(o,n,e,r),authorityId:e.id,signature:await fn(n,r.signing,"access-policy")};return await yf(i),i}async function yf(t){let e=_y.parse(t);await VE(e.policy),await _5(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await me(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await eo(e.policy,e.signature,o.signing,"access-policy"),e}async function Sy(t,e,r,o,n,i){let s=await yf(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&D(f.executor)===D(o)&&Date.parse(f.expiresAt)>Date.now());if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let u=await ja(t,GE(a).map(f=>({id:f.id,publicKey:f.encryption})),await gf(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await fn(l,n.signing,"resource")};return await Oi(d),d}async function KE(t,e,r){let o=await Oi(t);if(!o.policy.readers.some(n=>D(n)===D(e)))throw new Error("This identity cannot reveal the content.");return Ko(o.sealed,r,e.id,await gf(o.policy,o.materialRevision))}var ROe=g.object({id:E,policyDigest:Ar,materialRevision:g.number().int().positive(),authorizationDigest:Ar.optional()}).strict();async function iL(t,e){return e.id===t.policy.id&&e.policyDigest===await me(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||rL(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var ZE=g.object({format:g.literal(2),id:E,origin:hf,ownerId:E,approval:g.object({id:E,index:g.number().int().min(0).max(7)}).strict().optional(),operationContext:y5.optional(),actor:Pr,environmentId:E,executor:Pr,environmentDigest:Ar,operation:wy,functionDigest:Ar.nullable(),functionId:E.optional(),operationDigest:Ar,sources:g.array(ROe).max(100),resultRecipients:g.array(Pr).min(1).max(100),createdAt:nt,expiresAt:nt}).strict(),Fc=g.object({intent:ZE,signature:Nn,sealed:vo}).strict();async function Hl(t,e){return D({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await me(t)})}async function E5(t,e,r){if(ZE.parse(t),await me(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await ja(mt(D(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Hl(t,"input"))};return Fc.parse({...o,signature:await fn(o,r.signing,"run")})}async function IOe(t,e=Date.now()){let r=Fc.parse(t),{signature:o,...n}=r;await eo(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Lc(mt(await Hl(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function $5(t,e,r){let o=await IOe(t);if(D(o.intent.executor)!==D(e))throw new Error("This operation belongs to another executor.");let n=await Ko(o.sealed,r.encryption,e.id,await Hl(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(D(s)!==i||await me(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function Bl(t,e,r={}){let o=await Oi(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await iL(o,i))throw new Error("The input changed after this execution was authorized.");if(D(e.actor)===D(e.executor)&&n.readers.some(c=>D(c)===D(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?D(c.actor)===D(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&D(c.executor)===D(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===le.function||e.operation===le.refresh:e.operation===le.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==le.command&&e.operation!==le.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function qc(t,e,r,o={}){return await Bl(t,e,o),Ko(t.sealed,r.encryption,e.executor.id,await gf(t.policy,t.materialRevision))}var sL=g.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),I5=g.object({format:g.literal(3),id:E,origin:hf,ownerId:E,name:pe,executor:Pr,operatorId:E,driver:g.enum(["attached","managed"]),capabilities:g.array(wy).min(1).max(6),functionVersion:g.literal(1).optional(),isolation:g.enum(["process","container"]),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:sL.optional(),revision:g.number().int().positive()}).strict(),WE=g.object({manifest:I5,signature:Nn}).strict();async function aL(t,e){let r=I5.parse(t),o={manifest:r,signature:await fn(r,e.signing,"environment")};return await Kl(o),o}async function Kl(t){let e=WE.parse(t),{manifest:r}=e;if(await jc(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(le.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(le.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await eo(r,e.signature,r.executor.signing,"environment"),e}async function JE(t,e){let{manifest:r}=await Kl(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await me(r)||D(e.executor)!==D(r.executor)||!r.capabilities.includes(e.operation)||e.operation===le.function&&r.functionVersion!==1)throw new Error("This environment does not authorize the requested execution.")}var AOe=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),A5=g.object({ok:g.boolean(),result:ln.nullable(),error:g.object({code:g.string().max(100),message:g.string().max(1e3)}).nullable()}).strict(),xy=g.object({id:E,intentDigest:Ar,executorId:E,state:g.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:nt,sealed:vo,signature:Nn}).strict(),by=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function vf(t,e,r,o){let n=A5.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=mt(D(n));if(i.byteLength>14e5)throw new by;let s=await ja(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Hl(t,"result")),a={id:t.id,intentDigest:await me(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return xy.parse({...a,signature:await fn(a,o.signing,"receipt")})}async function POe(t,e){let r=xy.parse(t),{signature:o,...n}=r;if(await eo(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await me(e)||r.executorId!==e.executor.id||r.sealed.aad!==Lc(mt(await Hl(e,"result")))||D(r.sealed.recipients.map(i=>i.header.kid).sort())!==D(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function P5(t,e,r,o){await POe(t,e);let n=await Ko(t.sealed,o.encryption,r,await Hl(e,"result")),i=A5.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var kOe=g.enum(["http","command","function","connect","refresh","revoke"]),zn=g.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:kOe,state:AOe,intent:ZE,requestSignature:Nn,receipt:xy.nullable(),error:g.string().nullable(),createdAt:nt,startedAt:nt.nullable(),finishedAt:nt.nullable()}).strict(),R5=g.object({name:pe,approval:_y}).strict(),Is=g.discriminatedUnion("kind",[g.object({kind:g.literal("http"),request:Ma,save:g.record(g.string(),R5).default({})}).strict(),g.object({kind:g.literal("command"),...Ua.shape}).strict(),g.object({kind:g.literal("function"),functionId:E,definition:ql,arguments:er.default({}),outputs:g.record(g.string(),R5).default({})}).strict(),g.object({kind:g.enum(["connect","refresh","revoke"]),input:ln}).strict()]);var Vc=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Fa=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=g.object({error:g.object({code:g.string(),message:g.string()})}).parse(await n.json())}catch{throw new Vc("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new Vc(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await(await this.response(e,r)).json();return o?o.parse(n):n}async session(){return this.json("/api/session",{},NE)}};import{chmod as TOe,lstat as COe,mkdir as OOe,open as cL,readFile as T5,rename as DOe,rm as NOe}from"node:fs/promises";import{dirname as zOe,join as uL,resolve as MOe}from"node:path";import{homedir as UOe}from"node:os";import{randomUUID as LOe}from"node:crypto";var lL=g.object({origin:g.url(),principalId:g.uuid(),token:g.string().min(20),keys:gy.nullable(),binding:Pr.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),C5=g.object({current:g.uuid(),identities:g.array(lL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function qa(){return uL(process.env.XDG_CONFIG_HOME||uL(UOe(),".config"),"foundation","identity.json")}function Gc(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function XE(t){let e;try{let n=qa(),i=await COe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await TOe(n,384);let s=C5.parse(JSON.parse(await T5(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=Gc(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Gc(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return lL.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==Gc(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Ey(t){let e=qa(),r;try{r=C5.parse(JSON.parse(await T5(e,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=lL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await wf(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
128
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function T9(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;T9(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var C9=new Set(["type","properties","required","additionalProperties"]),P9=["oneOf","anyOf"];function k9(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function Ez(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!C9.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??k9(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:Ez(a)??{allOf:a};jr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=k9(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function FTe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of C9)if(n in t)return;let r=e.filter(n=>P9.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Ez(e);else{let n=r[0],i=P9.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>Ez([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,Fg(t,o))}function Ac(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Fg(u,m),Fg(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&p.def)for(let w in u)w==="$ref"||w==="allOf"||w in p.def&&JSON.stringify(u[w])===JSON.stringify(p.def[w])&&delete u[w]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())T9(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])FTe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Fg(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,jr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Vp(e,"input",t.processors),output:Vp(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Cn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Cn(o.element,r);if(o.type==="set")return Cn(o.valueType,r);if(o.type==="lazy")return Cn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Cn(o.innerType,r);if(o.type==="intersection")return Cn(o.left,r)||Cn(o.right,r);if(o.type==="record"||o.type==="map")return Cn(o.keyType,r)||Cn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Cn(o.in,r)||Cn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Cn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Cn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Cn(n,r))return!0;return!!(o.rest&&Cn(o.rest,r))}return!1}var $z=(t,e={})=>r=>{let o=Rc({...r,processors:e});return Rt(t,o),Ic(o,t),Ac(o,t)},Vp=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Rc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Ic(s,t),Ac(s,t)};var Gp=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},Hp=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},O9=(t,e)=>{Gp(t,"minimum",e),Hp(t,"maximum",e)},M9=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},U9=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},L9=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},j9=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},D9=(t,e)=>Gp(t,"minimum",e.minimum),N9=(t,e)=>Hp(t,"maximum",e.maximum),z9=t=>(e,r)=>{j9(e,r.format);let[o,n]=t[r.format];Gp(e,"minimum",o),Hp(e,"maximum",n)},qTe={greater_than:(t,e)=>Gp(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>Hp(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>M9(t,e.value),number_format:z9(Hh),bigint_format:z9(Bh),min_length:D9,max_length:N9,length_equals:(t,e)=>O9(t,e.length),min_size:D9,max_size:N9,size_equals:(t,e)=>O9(t,e.size),string_format:(t,e)=>{j9(t,e.format),e.pattern&&U9(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>L9(t,e.mime)};function br(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)qTe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Gp(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Gp(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Hp(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Hp(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&M9(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&L9(e,n.mime);for(let i of n.patterns??[])U9(e,i);return e}var VTe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},GTe=new Map([[Db,p1],[sg,f1]]),F9=t=>GTe.get(t)??t,Az=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=br(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=VTe[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(F9);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Pz=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=br(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let S of a)Number.isFinite(S)&&S!==0?m.add(Math.abs(S)):Sr(t,e,n,o,`A multipleOf divisor of ${S} cannot be represented in JSON Schema`);let[y,...w]=m;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(S=>({multipleOf:S}))])}},kz=(t,e,r,o)=>{r.type="boolean"},Tz=(t,e,r,o)=>{Sr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},Cz=(t,e,r,o)=>{Sr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},Oz=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Dz=(t,e,r,o)=>{Sr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},Nz=(t,e,r,o)=>{Sr(t,e,r,o,"Void cannot be represented in JSON Schema")},zz=(t,e,r,o)=>{r.not={}},Mz=(t,e,r,o)=>{},Uz=(t,e,r,o)=>{},Lz=(t,e,r,o)=>{Sr(t,e,r,o,"Date cannot be represented in JSON Schema")},jz=(t,e,r,o)=>{let n=t._zod.def,i=ip(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},Fz=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Sr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Sr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},qz=(t,e,r,o)=>{Sr(t,e,r,o,"NaN cannot be represented in JSON Schema")},Vz=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Gz=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=br(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},Hz=(t,e,r,o)=>{r.type="boolean"},Bz=(t,e,r,o)=>{Sr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},Kz=(t,e,r,o)=>{Sr(t,e,r,o,"Function types cannot be represented in JSON Schema")},Zz=(t,e,r,o)=>{Sr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},Wz=(t,e,r,o)=>{Sr(t,e,r,o,"Map cannot be represented in JSON Schema")},Jz=(t,e,r,o)=>{Sr(t,e,r,o,"Set cannot be represented in JSON Schema")},Xz=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=br(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function qg(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?qg(e.out):e.type==="catch"?qg(e.innerType):t._zod.optin}var Yz=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Sr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)jr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?qg(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},x0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},Qz=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},eM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?qg(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:m}=br(t);typeof p=="number"&&(n.minItems=p),typeof m=="number"&&(n.maxItems=m)};function Rz(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let y=Rz(t,m,r);return y===m?e:y}for(let m of["anyOf","oneOf"]){let y=e[m];if(!Array.isArray(y))continue;let w=y.map(S=>Rz(t,S,r));w.some((S,b)=>S!==y[b])&&(e={...e,[m]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(m=>typeof m=="number"?String(m):m):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?ka:Qh).source)),p}var Iz=new WeakMap;function HTe(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of Iz.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=Rz(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var tM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=br(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)jr(n.patternProperties,F9(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=Iz.get(e);l||(l=[],Iz.set(e,l),e.deferred.push(()=>HTe(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&qg(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},rM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},nM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},oM=Symbol();function q9(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Sr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),oM):JSON.parse(s)}var iM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=q9(n.defaultValue,t,e,r,o);s!==oM&&(r.default=s)},sM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=q9(n.defaultValue,t,e,r,o);s!==oM&&(r._prefault=s)},aM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Sr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},cM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},uM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},lM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},E0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},dM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},b0={string:Az,number:Pz,boolean:kz,bigint:Tz,symbol:Cz,null:Oz,undefined:Dz,void:Nz,never:zz,any:Mz,unknown:Uz,date:Lz,enum:jz,literal:Fz,nan:qz,template_literal:Vz,file:Gz,success:Hz,custom:Bz,function:Kz,transform:Zz,map:Wz,set:Jz,array:Xz,object:Yz,union:x0,intersection:Qz,tuple:eM,record:tM,nullable:rM,nonoptional:nM,default:iM,prefault:sM,catch:aM,pipe:cM,readonly:uM,promise:lM,optional:E0,lazy:dM};function kl(t,e){if("_idmap"in t){let o=t,n=Rc({...e,processors:b0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Ic(n,l),jr(s,u,Ac(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Rc({...e,processors:b0});return Rt(t,r),Ic(r,t),Ac(r,t)}var $0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Rc({processors:b0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Ic(this.ctx,e);let o=Ac(this.ctx,e),{"~standard":n,...i}=o;return i}};var V9={};var Qp={};qt(Qp,{ZodAny:()=>kM,ZodArray:()=>DM,ZodBase64:()=>G0,ZodBase64URL:()=>H0,ZodBigInt:()=>Xp,ZodBigIntFormat:()=>Z0,ZodBoolean:()=>Jp,ZodCIDRv4:()=>q0,ZodCIDRv6:()=>V0,ZodCUID:()=>N0,ZodCUID2:()=>z0,ZodCatch:()=>QM,ZodCodec:()=>Xg,ZodCreditCard:()=>$M,ZodCustom:()=>Yg,ZodCustomStringFormat:()=>Cl,ZodDate:()=>Bg,ZodDefault:()=>KM,ZodDiscriminatedUnion:()=>zM,ZodE164:()=>B0,ZodEmail:()=>T0,ZodEmoji:()=>O0,ZodEnum:()=>Kp,ZodExactOptional:()=>X0,ZodFile:()=>VM,ZodFunction:()=>uU,ZodGUID:()=>C0,ZodIBAN:()=>RM,ZodIPv4:()=>j0,ZodIPv6:()=>F0,ZodISODate:()=>kc,ZodISODateTime:()=>Pc,ZodISODuration:()=>Cc,ZodISOTime:()=>Tc,ZodInstanceOf:()=>pU,ZodIntersection:()=>MM,ZodJWT:()=>K0,ZodKSUID:()=>L0,ZodLazy:()=>sU,ZodLiteral:()=>qM,ZodMAC:()=>EM,ZodMap:()=>jM,ZodNaN:()=>tU,ZodNanoID:()=>D0,ZodNever:()=>CM,ZodNonOptional:()=>Y0,ZodNull:()=>PM,ZodNullable:()=>BM,ZodNumber:()=>Wp,ZodNumberFormat:()=>Ol,ZodObject:()=>Kg,ZodOptional:()=>Dl,ZodPipe:()=>Jg,ZodPrefault:()=>WM,ZodPreprocess:()=>rU,ZodPromise:()=>cU,ZodReadonly:()=>nU,ZodRecord:()=>Bp,ZodSet:()=>FM,ZodString:()=>Zp,ZodStringFormat:()=>kt,ZodSuccess:()=>YM,ZodSymbol:()=>IM,ZodTemplateLiteral:()=>iU,ZodTransform:()=>GM,ZodTuple:()=>UM,ZodType:()=>Ae,ZodULID:()=>M0,ZodURL:()=>Gg,ZodUUID:()=>$s,ZodUndefined:()=>AM,ZodUnion:()=>Zg,ZodUnknown:()=>TM,ZodVoid:()=>OM,ZodXID:()=>U0,ZodXor:()=>NM,_ZodString:()=>k0,_default:()=>ZM,_function:()=>XZ,any:()=>CZ,array:()=>Le,base64:()=>pZ,base64url:()=>fZ,bigint:()=>IZ,boolean:()=>lr,catch:()=>eU,check:()=>YZ,cidrv4:()=>lZ,cidrv6:()=>dZ,codec:()=>KZ,creditCard:()=>hZ,cuid:()=>rZ,cuid2:()=>nZ,currencyCode:()=>SZ,custom:()=>Q0,date:()=>DZ,describe:()=>QZ,discriminatedUnion:()=>Wg,e164:()=>mZ,email:()=>B9,emoji:()=>eZ,enum:()=>Vr,exactOptional:()=>HM,file:()=>VZ,float32:()=>xZ,float64:()=>EZ,function:()=>XZ,guid:()=>K9,hash:()=>bZ,hex:()=>_Z,hostname:()=>wZ,httpUrl:()=>Q9,iban:()=>gZ,instanceof:()=>tW,int:()=>A0,int32:()=>$Z,int64:()=>AZ,intersection:()=>Yp,invertCodec:()=>ZZ,ipv4:()=>aZ,ipv6:()=>uZ,json:()=>nW,jwt:()=>yZ,keyof:()=>NZ,ksuid:()=>sZ,lazy:()=>aU,literal:()=>ie,looseObject:()=>qr,looseRecord:()=>LZ,mac:()=>cZ,map:()=>jZ,meta:()=>eW,nan:()=>BZ,nanoid:()=>tZ,nativeEnum:()=>qZ,never:()=>W0,nonoptional:()=>XM,null:()=>Hg,nullable:()=>Vg,nullish:()=>GZ,number:()=>ft,object:()=>J,optional:()=>Pt,partialRecord:()=>UZ,pipe:()=>P0,prefault:()=>JM,preprocess:()=>Qg,promise:()=>JZ,readonly:()=>oU,record:()=>Tt,refine:()=>lU,set:()=>FZ,strictObject:()=>zZ,string:()=>C,stringFormat:()=>vZ,stringbool:()=>rW,success:()=>HZ,superRefine:()=>dU,symbol:()=>kZ,templateLiteral:()=>WZ,transform:()=>J0,tuple:()=>LM,uint32:()=>RZ,uint64:()=>PZ,ulid:()=>oZ,undefined:()=>TZ,union:()=>It,unknown:()=>Mt,url:()=>Y9,uuid:()=>Z9,uuidv4:()=>W9,uuidv6:()=>J9,uuidv7:()=>X9,void:()=>OZ,xid:()=>iZ,xor:()=>MZ});var R0={};qt(R0,{endsWith:()=>Np,gt:()=>xs,gte:()=>go,includes:()=>Op,length:()=>Pl,lowercase:()=>Tp,lt:()=>bs,lte:()=>ho,maxLength:()=>Al,maxSize:()=>Ec,mime:()=>Mp,minLength:()=>Ta,minSize:()=>Es,multipleOf:()=>xc,negative:()=>d0,nonnegative:()=>f0,nonpositive:()=>p0,normalize:()=>Up,overwrite:()=>Ri,positive:()=>l0,properties:()=>zp,property:()=>m0,regex:()=>kp,size:()=>Il,slugify:()=>qp,startsWith:()=>Dp,toLowerCase:()=>jp,toUpperCase:()=>Fp,trim:()=>Lp,uppercase:()=>Cp});var G9=new WeakSet([Object.prototype,Error.prototype]);function I0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var H9=(t,e)=>{BN.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);G9.has(r)||(G9.add(r),I0(r,"format",o=>n=>Xh(o,n)),I0(r,"flatten",o=>n=>Jh(o,n)),I0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,sp,2)}),I0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,sp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},KTe=$("ZodError",H9),Yn=$("ZodError",H9,void 0,{Parent:Error});var pM=dp(Yn),fM=pp(Yn),mM=fp(Yn),hM=hp(Yn),gM=WS(Yn),yM=JS(Yn),vM=XS(Yn),wM=YS(Yn),_M=QS(Yn),SM=eb(Yn),bM=tb(Yn),xM=rb(Yn);function WTe(){Ir.localeError||or(Ox())}function Tl(){Ir.memoizer||or({memoizer:mg()})}var Ae=$("ZodType",(t,e)=>(WTe(),we.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(O.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return pt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(lU(t,e))},superRefine(t,e){return this.check(dU(t,e))},overwrite(t){return this.check(Ri(t))},optional(){return Pt(this)},exactOptional(){return HM(this)},nullable(){return Vg(this)},nullish(){return Pt(Vg(this))},nonoptional(t){return XM(this,t)},array(){return Le(this)},or(t){return It([this,t])},and(t){return Yp(this,t)},transform(t){return P0(this,J0(t))},default(t){return ZM(this,t)},prefault(t){return JM(this,t)},catch(t){return eU(this,t)},pipe(t){return P0(this,t)},readonly(){return oU(this)},describe(t){let e=this.clone();return Fr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Fr.get(this);let e=this.clone();return Fr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return O.hide(this,"~standard",{...fb(this),jsonSchema:{input:Vp(this,"input"),output:Vp(this,"output")}})},set"~standard"(t){O.own(this,"~standard",t)},parse:function t(e,r){return pM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await fM(this,e,r,{callee:t})},safeParse(t,e){return mM(this,t,e)},async safeParseAsync(t,e){return hM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){O.own(this,"spa",t)},validate(t,e){return yp(this,t,e)},validateAsync(t,e){return vp(this,t,e)},encode:function t(e,r){return gM(this,e,r,{callee:t})},decode:function t(e,r){return yM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await vM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await wM(this,e,r,{callee:t})},safeEncode(t,e){return _M(this,t,e)},safeDecode(t,e){return SM(this,t,e)},async safeEncodeAsync(t,e){return bM(this,t,e)},async safeDecodeAsync(t,e){return xM(this,t,e)},toJSONSchema(t){return $z(this,{})(t)},get description(){return Fr.get(this)?.description},get _def(){return this._zod.def}}),k0=$("_ZodString",(t,e)=>{bc.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Az(t,r,o,n)},O.derived({format:t=>br(t).format??null,minLength:t=>br(t).minimum??null,maxLength:t=>br(t).maximum??null},{regex(...t){return this.check(kp(...t))},includes(...t){return this.check(Op(...t))},startsWith(...t){return this.check(Dp(...t))},endsWith(...t){return this.check(Np(...t))},min(...t){return this.check(Ta(...t))},max(...t){return this.check(Al(...t))},length(...t){return this.check(Pl(...t))},nonempty(...t){return this.check(Ta(1,...t))},lowercase(t){return this.check(Tp(t))},uppercase(t){return this.check(Cp(t))},trim(){return this.check(Lp())},normalize(...t){return this.check(Up(...t))},toLowerCase(){return this.check(jp())},toUpperCase(){return this.check(Fp())},slugify(){return this.check(qp())}})),Zp=$("ZodString",(t,e)=>{bc.init(t,e),k0.init(t,e)},{email(t){return this.check(gg(T0,t))},url(t){return this.check(Pp(Gg,t))},jwt(t){return this.check(zg(K0,t))},emoji(t){return this.check(bg(O0,t))},guid(t){return this.check(yg(C0,t))},uuid(t){return this.check(vg($s,t))},uuidv4(t){return this.check(wg($s,t))},uuidv6(t){return this.check(_g($s,t))},uuidv7(t){return this.check(Sg($s,t))},nanoid(t){return this.check(xg(D0,t))},cuid(t){return this.check(Eg(N0,t))},cuid2(t){return this.check($g(z0,t))},ulid(t){return this.check(Rg(M0,t))},base64(t){return this.check(Og(G0,t))},base64url(t){return this.check(Dg(H0,t))},xid(t){return this.check(Ig(U0,t))},ksuid(t){return this.check(Ag(L0,t))},ipv4(t){return this.check(Pg(j0,t))},ipv6(t){return this.check(kg(F0,t))},cidrv4(t){return this.check(Tg(q0,t))},cidrv6(t){return this.check(Cg(V0,t))},e164(t){return this.check(Ng(B0,t))},datetime(t){return this.check(Mg(Pc,t))},date(t){return this.check(Ug(kc,t))},time(t){return this.check(Lg(Tc,t))},duration(t){return this.check(jg(Cc,t))}});function C(t){return Fx(Zp,t)}var kt=$("ZodStringFormat",(t,e)=>{_t.init(t,e),k0.init(t,e)}),Pc=$("ZodISODateTime",(t,e)=>{tz.init(t,e),kt.init(t,e)}),kc=$("ZodISODate",(t,e)=>{rz.init(t,e),kt.init(t,e)}),Tc=$("ZodISOTime",(t,e)=>{nz.init(t,e),kt.init(t,e)}),Cc=$("ZodISODuration",(t,e)=>{oz.init(t,e),kt.init(t,e)}),T0=$("ZodEmail",(t,e)=>{gb.init(t,e),kt.init(t,e)});function B9(t){return gg(T0,t)}var C0=$("ZodGUID",(t,e)=>{mb.init(t,e),kt.init(t,e)});function K9(t){return yg(C0,t)}var $s=$("ZodUUID",(t,e)=>{hb.init(t,e),kt.init(t,e)});function Z9(t){return vg($s,t)}function W9(t){return wg($s,t)}function J9(t){return _g($s,t)}function X9(t){return Sg($s,t)}var Gg=$("ZodURL",(t,e)=>{_b.init(t,e),kt.init(t,e)});function Y9(t){return Pp(Gg,t)}function Q9(t){return Pp(Gg,{protocol:Yh,hostname:h1,...O.normalizeParams(t)})}var O0=$("ZodEmoji",(t,e)=>{Sb.init(t,e),kt.init(t,e)});function eZ(t){return bg(O0,t)}var D0=$("ZodNanoID",(t,e)=>{bb.init(t,e),kt.init(t,e)});function tZ(t){return xg(D0,t)}var N0=$("ZodCUID",(t,e)=>{xb.init(t,e),kt.init(t,e)});function rZ(t){return Eg(N0,t)}var z0=$("ZodCUID2",(t,e)=>{Eb.init(t,e),kt.init(t,e)});function nZ(t){return $g(z0,t)}var M0=$("ZodULID",(t,e)=>{$b.init(t,e),kt.init(t,e)});function oZ(t){return Rg(M0,t)}var U0=$("ZodXID",(t,e)=>{Rb.init(t,e),kt.init(t,e)});function iZ(t){return Ig(U0,t)}var L0=$("ZodKSUID",(t,e)=>{Ib.init(t,e),kt.init(t,e)});function sZ(t){return Ag(L0,t)}var j0=$("ZodIPv4",(t,e)=>{Ab.init(t,e),kt.init(t,e)});function aZ(t){return Pg(j0,t)}var EM=$("ZodMAC",(t,e)=>{kb.init(t,e),kt.init(t,e)});function cZ(t){return qx(EM,t)}var F0=$("ZodIPv6",(t,e)=>{Pb.init(t,e),kt.init(t,e)});function uZ(t){return kg(F0,t)}var q0=$("ZodCIDRv4",(t,e)=>{Tb.init(t,e),kt.init(t,e)});function lZ(t){return Tg(q0,t)}var V0=$("ZodCIDRv6",(t,e)=>{Ob.init(t,e),kt.init(t,e)});function dZ(t){return Cg(V0,t)}var G0=$("ZodBase64",(t,e)=>{Nb.init(t,e),kt.init(t,e)});function pZ(t){return Og(G0,t)}var H0=$("ZodBase64URL",(t,e)=>{Mb.init(t,e),kt.init(t,e)});function fZ(t){return Dg(H0,t)}var B0=$("ZodE164",(t,e)=>{Ub.init(t,e),kt.init(t,e)});function mZ(t){return Ng(B0,t)}var $M=$("ZodCreditCard",(t,e)=>{jb.init(t,e),kt.init(t,e)});function hZ(t){return Vx($M,t)}var RM=$("ZodIBAN",(t,e)=>{qb.init(t,e),kt.init(t,e)});function gZ(t){return Gx(RM,t)}var K0=$("ZodJWT",(t,e)=>{Gb.init(t,e),kt.init(t,e)});function yZ(t){return zg(K0,t)}var Cl=$("ZodCustomStringFormat",(t,e)=>{Hb.init(t,e),kt.init(t,e)});function vZ(t,e,r={}){return $c(Cl,t,e,r)}function wZ(t){return $c(Cl,"hostname",m1,t)}function _Z(t){return $c(Cl,"hex",P1,t)}function SZ(t){return $c(Cl,"currency_code",y1,t)}function bZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=mo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return $c(Cl,o,n,e)}var Wp=$("ZodNumber",(t,e)=>{ag.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Pz(t,r,o,n),t.isFinite=!0},O.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=br(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=br(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=br(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>br(t).format??null},{gt(t,e){return this.check(xs(t,e))},gte(t,e){return this.check(go(t,e))},min(t,e){return this.check(go(t,e))},lt(t,e){return this.check(bs(t,e))},lte(t,e){return this.check(ho(t,e))},max(t,e){return this.check(ho(t,e))},int(t){return this.check(A0(t))},safe(t){return this.check(A0(t))},positive(t){return this.check(xs(0,t))},nonnegative(t){return this.check(go(0,t))},negative(t){return this.check(bs(0,t))},nonpositive(t){return this.check(ho(0,t))},multipleOf(t,e){return this.check(xc(t,e))},step(t,e){return this.check(xc(t,e))},finite(){return this}}));function ft(t){return Hx(Wp,t)}var Ol=$("ZodNumberFormat",(t,e)=>{Bb.init(t,e),Wp.init(t,e)});function A0(t){return Bx(Ol,t)}function xZ(t){return Kx(Ol,t)}function EZ(t){return Zx(Ol,t)}function $Z(t){return Wx(Ol,t)}function RZ(t){return Jx(Ol,t)}var Jp=$("ZodBoolean",(t,e)=>{Sp.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kz(t,r,o,n)});function lr(t){return Xx(Jp,t)}var Xp=$("ZodBigInt",(t,e)=>{cg.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tz(t,r,o,n)},O.derived({minValue:t=>br(t).minimum??null,maxValue:t=>br(t).maximum??null,format:t=>br(t).format??null},{gte(t,e){return this.check(go(t,e))},min(t,e){return this.check(go(t,e))},gt(t,e){return this.check(xs(t,e))},lt(t,e){return this.check(bs(t,e))},lte(t,e){return this.check(ho(t,e))},max(t,e){return this.check(ho(t,e))},positive(t){return this.check(xs(BigInt(0),t))},negative(t){return this.check(bs(BigInt(0),t))},nonpositive(t){return this.check(ho(BigInt(0),t))},nonnegative(t){return this.check(go(BigInt(0),t))},multipleOf(t,e){return this.check(xc(t,e))}}));function IZ(t){return Yx(Xp,t)}var Z0=$("ZodBigIntFormat",(t,e)=>{Kb.init(t,e),Xp.init(t,e)});function AZ(t){return Qx(Z0,t)}function PZ(t){return e0(Z0,t)}var IM=$("ZodSymbol",(t,e)=>{Zb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Cz(t,r,o,n)});function kZ(t){return t0(IM,t)}var AM=$("ZodUndefined",(t,e)=>{Wb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Dz(t,r,o,n)});function TZ(t){return r0(AM,t)}var PM=$("ZodNull",(t,e)=>{Jb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Oz(t,r,o,n)});function Hg(t){return n0(PM,t)}var kM=$("ZodAny",(t,e)=>{Xb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Mz(t,r,o,n)});function CZ(){return o0(kM)}var TM=$("ZodUnknown",(t,e)=>{Yb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Uz(t,r,o,n)});function Mt(){return i0(TM)}var CM=$("ZodNever",(t,e)=>{Qb.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zz(t,r,o,n)});function W0(t){return s0(CM,t)}var OM=$("ZodVoid",(t,e)=>{ex.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Nz(t,r,o,n)});function OZ(t){return a0(OM,t)}var Bg=$("ZodDate",(t,e)=>{tx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Lz(t,r,o,n),t.min=(r,o)=>t.check(go(r,o)),t.max=(r,o)=>t.check(ho(r,o))},O.derived({minDate:t=>{let{minimum:e}=br(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=br(t);return e?new Date(e):null}},{}));function DZ(t){return c0(Bg,t)}var DM=$("ZodArray",(t,e)=>{Tl(),rx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Xz(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ta(t,e))},nonempty(t){return this.check(Ta(1,t))},max(t,e){return this.check(Al(t,e))},length(t,e){return this.check(Pl(t,e))},unwrap(){return this.element}});function Le(t,e){return xz(DM,t,e)}function NZ(t){let e=t._zod.def.shape;return Vr(Object.keys(e))}var Kg=$("ZodObject",(t,e)=>{Tl(),iz.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Yz(t,r,o,n),O.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Vr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(O.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(O.mergeDefs(this._zod.def,{catchall:Mt()}))},loose(){return this.clone(O.mergeDefs(this._zod.def,{catchall:Mt()}))},strict(){return this.clone(O.mergeDefs(this._zod.def,{catchall:W0()}))},strip(){return this.clone(O.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return O.extend(this,t)},safeExtend(t){return O.safeExtend(this,t)},merge(t){return O.merge(this,t)},pick(t){return O.pick(this,t)},omit(t){return O.omit(this,t)},partial(...t){return O.partial(Dl,this,t[0])},exactPartial(...t){return O.partial(X0,this,t[0],"exactPartial")},required(...t){return O.required(Y0,this,t[0])}});function J(t,e){let r={type:"object",shape:t??{},...O.normalizeParams(e)};return new Kg(r)}function zZ(t,e){return new Kg({type:"object",shape:t,catchall:W0(),...O.normalizeParams(e)})}function qr(t,e){return new Kg({type:"object",shape:t,catchall:Mt(),...O.normalizeParams(e)})}var Zg=$("ZodUnion",(t,e)=>{bp.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>x0(t,r,o,n),t.options=e.options});function It(t,e){return new Zg({type:"union",options:t,...O.normalizeParams(e)})}var NM=$("ZodXor",(t,e)=>{Zg.init(t,e),ox.init(t,e),t._zod.processJSONSchema=(r,o,n)=>x0(t,r,o,n),t.options=e.options});function MZ(t,e){return new NM({type:"union",options:t,inclusive:!1,...O.normalizeParams(e)})}var zM=$("ZodDiscriminatedUnion",(t,e)=>{Zg.init(t,e),ix.init(t,e)});function Wg(t,e,r){return new zM({type:"union",options:e,discriminator:t,...O.normalizeParams(r)})}var MM=$("ZodIntersection",(t,e)=>{sx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Qz(t,r,o,n)});function Yp(t,e){return new MM({type:"intersection",left:t,right:e})}var UM=$("ZodTuple",(t,e)=>{Tl(),ug.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Dl({type:"optional",innerType:e}))})}});function LM(t,e,r){let o=e instanceof we,n=o?r:e,i=o?e:null;return new UM({type:"tuple",items:t,rest:i,...O.normalizeParams(n)})}var Bp=$("ZodRecord",(t,e)=>{Tl(),ax.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Tt(t,e,r){return!e||!e._zod?new Bp({type:"record",keyType:C(),valueType:t,...O.normalizeParams(e)}):new Bp({type:"record",keyType:t,valueType:e,...O.normalizeParams(r)})}function UZ(t,e,r){return new Bp({type:"record",keyType:t,valueType:e,...O.normalizeParams(r),partial:!0})}function LZ(t,e,r){return new Bp({type:"record",keyType:t,valueType:e,mode:"loose",...O.normalizeParams(r)})}var jM=$("ZodMap",(t,e)=>{Tl(),cx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Wz(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Es(...r)),t.nonempty=r=>t.check(Es(1,r)),t.max=(...r)=>t.check(Ec(...r)),t.size=(...r)=>t.check(Il(...r))});function jZ(t,e,r){return new jM({type:"map",keyType:t,valueType:e,...O.normalizeParams(r)})}var FM=$("ZodSet",(t,e)=>{Tl(),ux.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Jz(t,r,o,n),t.min=(...r)=>t.check(Es(...r)),t.nonempty=r=>t.check(Es(1,r)),t.max=(...r)=>t.check(Ec(...r)),t.size=(...r)=>t.check(Il(...r))});function FZ(t,e){return new FM({type:"set",valueType:t,...O.normalizeParams(e)})}var Kp=$("ZodEnum",(t,e)=>{lx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(o,n,i)=>jz(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Kp({...e,checks:[],...O.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Kp({...e,checks:[],...O.normalizeParams(n),entries:i})}});function Vr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Kp({type:"enum",entries:r,...O.normalizeParams(e)})}function qZ(t,e){return new Kp({type:"enum",entries:t,...O.normalizeParams(e)})}var qM=$("ZodLiteral",(t,e)=>{dx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Fz(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ie(t,e){return new qM({type:"literal",values:Array.isArray(t)?t:[t],...O.normalizeParams(e)})}var VM=$("ZodFile",(t,e)=>{px.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Gz(t,r,o,n),t.min=(r,o)=>t.check(Es(r,o)),t.max=(r,o)=>t.check(Ec(r,o)),t.mime=(r,o)=>t.check(Mp(Array.isArray(r)?r:[r],o))});function VZ(t){return h0(VM,t)}var GM=$("ZodTransform",(t,e)=>{Tl(),fx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Zz(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Sc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(O.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(O.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function J0(t){return new GM({type:"transform",transform:t})}var Dl=$("ZodOptional",(t,e)=>{lg.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>E0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Pt(t){return new Dl({type:"optional",innerType:t})}var X0=$("ZodExactOptional",(t,e)=>{mx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>E0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function HM(t){return new X0({type:"optional",innerType:t})}var BM=$("ZodNullable",(t,e)=>{hx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Vg(t){return new BM({type:"nullable",innerType:t})}function GZ(t){return Pt(Vg(t))}var KM=$("ZodDefault",(t,e)=>{gx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function ZM(t,e){return new KM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():O.shallowClone(e)}})}var WM=$("ZodPrefault",(t,e)=>{yx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function JM(t,e){return new WM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():O.shallowClone(e)}})}var Y0=$("ZodNonOptional",(t,e)=>{vx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function XM(t,e){return new Y0({type:"nonoptional",innerType:t,...O.normalizeParams(e)})}var YM=$("ZodSuccess",(t,e)=>{wx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Hz(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function HZ(t){return new YM({type:"success",innerType:t})}var QM=$("ZodCatch",(t,e)=>{_x.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function eU(t,e){return new QM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:O.constantCatch(e)})}var tU=$("ZodNaN",(t,e)=>{Sx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qz(t,r,o,n)});function BZ(t){return u0(tU,t)}var Jg=$("ZodPipe",(t,e)=>{dg.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cM(t,r,o,n),t.in=e.in,t.out=e.out});function P0(t,e){return new Jg({type:"pipe",in:t,out:e})}var Xg=$("ZodCodec",(t,e)=>{Jg.init(t,e),xp.init(t,e)});function KZ(t,e,r){return new Xg({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function ZZ(t){let e=t._zod.def;return new Xg({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var rU=$("ZodPreprocess",(t,e)=>{Jg.init(t,e),az.init(t,e)}),nU=$("ZodReadonly",(t,e)=>{bx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function oU(t){return new nU({type:"readonly",innerType:t})}var iU=$("ZodTemplateLiteral",(t,e)=>{xx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Vz(t,r,o,n)});function WZ(t,e){return new iU({type:"template_literal",parts:t,...O.normalizeParams(e)})}var sU=$("ZodLazy",(t,e)=>{Ep.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function aU(t){return new sU({type:"lazy",getter:t})}var cU=$("ZodPromise",(t,e)=>{$x.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function JZ(t){return new cU({type:"promise",innerType:t})}var uU=$("ZodFunction",(t,e)=>{Ex.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Kz(t,r,o,n)});function XZ(t){return new uU({type:"function",input:Array.isArray(t?.input)?LM(t?.input):t?.input??Le(Mt()),output:t?.output??Mt()})}var Yg=$("ZodCustom",(t,e)=>{Rx.init(t,e),Ae.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Bz(t,r,o,n)});function YZ(t){let e=new At({check:"custom"});return e._zod.check=t,e}function Q0(t,e){return g0(Yg,t??(()=>!0),e)}function lU(t,e={}){return y0(Yg,t,e)}function dU(t,e){return v0(t,e)}var QZ=w0,eW=_0,pU=$("ZodInstanceOf",(t,e)=>{Yg.init(t,e)},{properties(t,e){return this.check(zp(t,e))}});function tW(t,e={}){let r=new pU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...O.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var rW=(...t)=>S0({Codec:Xg,Boolean:Jp,String:Zp},...t);function nW(t){let e=aU(()=>It([C(t),ft(),lr(),Hg(),Le(e),Tt(C(),e)]));return e}function Qg(t,e){return new rU({type:"pipe",in:J0(t),out:e})}var JTe={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 XTe(t){or({customError:t})}function YTe(){return or().customError}var fU;fU||(fU={});var Nl={};qt(Nl,{ZodISODate:()=>kc,ZodISODateTime:()=>Pc,ZodISODuration:()=>Cc,ZodISOTime:()=>Tc,date:()=>eCe,datetime:()=>QTe,duration:()=>rCe,time:()=>tCe});function QTe(t){return Mg(Pc,t)}function eCe(t){return Ug(kc,t)}function tCe(t){return Lg(Tc,t)}function rCe(t){return jg(Cc,t)}var W={...Qp,...R0,iso:Nl},nCe=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 oCe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function oW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function iCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function sCe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:iCe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function aCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function mU(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=mU(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=mU(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var cCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),uCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function ey(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(ey):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>cCe.has(e)?ey(r):!uCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(ey))}function iW(t){return t===1?"element":"elements"}function lCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=mU(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${iW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${iW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function sW(t,e){if(t!==!1)return t===void 0||t===!0?W.any():On(t,e)}var dCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function aW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return W.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=sCe(n,e),s=On(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return W.null();if(n.length===0)return W.never();if(n.length===1)return W.literal(n[0]);if(n.every(s=>typeof s=="string"))return W.enum(n);let i=n.map(s=>W.literal(s));return i.length<2?i[0]:W.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return W.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return aW(s,e)});return n.length===0?W.never():n.length===1?n[0]:W.union(n)}if(!r)return W.any();let o;switch(r){case"string":{let n=W.string();if(t.format){let i=t.format;i==="email"?n=n.check(W.email()):i==="uri"||i==="uri-reference"?n=n.check(W.url()):i==="uuid"||i==="guid"?n=n.check(W.uuid()):i==="date-time"?n=n.check(W.iso.datetime({offset:!0})):i==="date"?n=n.check(W.iso.date()):i==="time"?n=n.check(W.regex(dCe)):i==="duration"?n=n.check(W.iso.duration()):i==="hostname"?n=n.check(W.hostname()):i==="ipv4"?n=n.check(W.ipv4()):i==="ipv6"?n=n.check(W.ipv6()):i==="mac"?n=n.check(W.mac()):i==="cidr"?n=n.check(W.cidrv4()):i==="cidr-v6"?n=n.check(W.cidrv6()):i==="base64"?n=n.check(W.base64()):i==="base64url"?n=n.check(W.base64url()):i==="e164"?n=n.check(W.e164()):i==="credit_card"?n=n.check(W.creditCard()):i==="iban"?n=n.check(W.iban()):i==="jwt"?n=n.check(W.jwt()):i==="emoji"?n=n.check(W.emoji()):i==="nanoid"?n=n.check(W.nanoid()):i==="cuid"?n=n.check(W.cuid()):i==="cuid2"?n=n.check(W.cuid2()):i==="ulid"?n=n.check(W.ulid()):i==="xid"?n=n.check(W.xid()):i==="ksuid"&&(n=n.check(W.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?W.number().int():W.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=W.boolean();break}case"null":{o=W.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?On(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=On(f,e);jr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let y of f){let w=On(d[y],e),S=W.string().regex(new RegExp(y));p.push(W.looseRecord(S,w))}let m=[];if(Object.keys(n).length>0&&m.push(W.object(n).passthrough()),m.push(...p),m.length===0)o=W.object({}).passthrough();else if(m.length===1)o=m[0];else{let y=W.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)y=W.intersection(y,m[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=f.map(b=>new RegExp(b)),S=o;o=o.check(b=>{if(!Vo(b.value))return;let x=[];for(let k of Object.keys(b.value))y.includes(k)||w.some(T=>T.test(k))||x.push(k);x.length&&b.issues.push({code:"unrecognized_keys",keys:x,input:b.value,inst:S})})}}else{let d=W.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=On(f,e)}o=aCe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>On(d,e)),c=oW(a,s),u=Array.isArray(i)?void 0:sW(i,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>On(d,e)),c=oW(a,s),u=sW(t.additionalItems,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(i!==void 0){let s=On(i,e),a=W.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=W.array(W.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=lCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?On(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function On(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r=aW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>On(u,e)),c=W.union(a);r=o?W.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>On(u,e)),c=W.xor(a);r=o?W.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:W.any();else{let a=o?r:On(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=W.intersection(a,On(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=W.nullable(r)),t.readOnly===!0&&(r=W.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!ey(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!ey(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))nCe.has(a)||jr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function cW(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=oCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Fr};return On(r,i)}var uW=Symbol("z.visit/resolving");function ty(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===uW)return new Ep({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,uW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let m of l){let y=n(u[m]);y!==u[m]&&(d=!0),f[m]=y}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?pt(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:pt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let m=n(p);m!==p&&(l=!0),d.push(m)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?pt(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:pt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:pt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?pt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:pt(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:pt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:pt(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:pt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return pt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function lW(t){return ty(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function pCe(t,e){if(!e?.length)return t;let r=t._zod.def;return pt(t,qo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function dW(t){return pCe(t.out,t.checks)}function fCe(t){return t.in._zod.traits.has("$ZodTransform")?dW(t):t.in}function pW(t){return ty(t,{pipe:e=>fCe(e._zod.def),default:(e,r)=>r?Pt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function fW(t){return ty(t,{pipe:e=>dW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var hU={};qt(hU,{bigint:()=>yCe,boolean:()=>gCe,date:()=>vCe,number:()=>hCe,string:()=>mCe});function mCe(t){return yz(Zp,t)}function hCe(t){return wz(Wp,t)}function gCe(t){return _z(Jp,t)}function yCe(t){return Sz(Xp,t)}function vCe(t){return bz(Bg,t)}var ry={name:"@tomato414941/foundation",version:"5.1.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&g.config({jitless:!0});function _Ce(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var ny=g.string().trim().max(8192).refine(t=>_Ce(t)!==null,"Use an OpenSSH public key from a .pub file."),oy=g.object({authorizedKeys:g.array(ny).max(32)}).strict(),rgt=oy.extend({revision:g.number().int().positive().optional()}),gU=oy.extend({host:g.string().min(1).max(253).nullable(),port:g.number().int().min(1).max(65535),username:g.literal("root"),workingDirectory:g.literal("/workspace"),hostKey:ny.nullable(),fingerprint:g.string().nullable(),revision:g.number().int().positive(),appliedRevision:g.number().int().nonnegative(),activeSessions:g.number().int().min(0).max(1024)}).strict(),ngt=gU.extend({state:g.enum(["starting","configuring","ready","disabled","stopped"])}),ogt=g.object({hostKey:ny,appliedRevision:g.number().int().nonnegative(),activeSessions:g.number().int().min(0).max(1024)}).strict(),SCe=oy.extend({port:g.number().int().min(1).max(65535),revision:g.number().int().positive()}).strict(),eE=g.object({configuration:SCe.nullable()}).strict();var ef=new TextEncoder,tf=new TextDecoder,mW=new TextDecoder("utf-8",{fatal:!0}),tE=2**32;function Dn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function yU(t,e,r){if(e<0||e>=tE)throw new RangeError(`value must be >= 0 and <= ${tE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function vU(t){let e=Math.floor(t/tE),r=t%tE,o=new Uint8Array(8);return yU(o,e,0),yU(o,r,4),o}function rE(t){let e=new Uint8Array(4);return yU(e,t),e}var bCe=/[^\x00-\x7f]/;function Gr(t){if(typeof t=="string"&&t.length>=128){if(bCe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return ef.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function hW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function gW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function nE(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ca=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var zl=class extends Ca{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ct=class extends Ca{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Oc=class extends Ca{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends Ca{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Zt=class extends Ca{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var iy=class extends Ca{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var oE=class extends Ca{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var xCe="The input to be decoded is not correctly encoded.";function Ml(t){try{return gW(typeof t=="string"?t:tf.decode(t),!0)}catch(e){throw new TypeError(xCe,{cause:e})}}function Qt(t){return hW(typeof t=="string"?ef.encode(t):t,!0)}function yo(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function fr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Dc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Ho(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function Qn(t,e,r){try{return Ml(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function iE(t,e,r){try{return Gr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function rf(t,e,r){let o;try{o=JSON.parse(mW.decode(Ml(t)))}catch{throw new e(r)}if(!fr(o))throw new e(r);return o}var sE={__proto__:null,b64:!0},aE={__proto__:null};function sy(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function cE(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Nc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ct(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function uE(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Zt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Ul(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!fr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var ECe=t=>t[Symbol.toStringTag],$Ce=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function Ai(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(fr(e)){if(s=EU(e),typeof s.kty!="string")throw yW(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if($Ce(t,s,r),s.kty==="oct")return Ml(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!SU(e))throw yW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${ECe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(zc(e))return e;if(a=e,a.type==="secret")return a.export()}wU||=new WeakMap;let c=e,u=wU.get(c);if(u?.[o])return u[o];if(u||wU.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=RCe[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await of(t,s)}var wU,RCe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function dE(t){if(!zc(t))throw new Error("CryptoKey instance expected")}var zc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},_U=t=>t?.[Symbol.toStringTag]==="KeyObject",SU=t=>zc(t)||_U(t);function vW(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Oa=(t,...e)=>vW("Key must be ",t,...e);function yW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(vW(`Key for the ${t} algorithm must be `,e,...o))}var lE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function bU(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function nf(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function xU(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw lE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw lE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw lE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw lE(e.length,"algorithm.length");bU(t,r)}function pE(t){return{__proto__:null,...t}}function EU(t){let e=pE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function fE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function of(t,e,r){if(!t.kty.includes(e.kty))throw new Ct('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Pi(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),xU(t,e,r),t}var Ll=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function mE(t,e){let r=t.byteLength<<3;if(r!==e)throw new H(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var ICe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function wW(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function _W(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Oa(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function SW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function ACe(t,e,r,o,n){let[i,s,a]=await _W(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Dn(n,o,c,vU(n.length*8)),l=await SW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function PCe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function kCe(t,e,r,o,n,i){let[s,a,c]=await _W(t,e,"decrypt"),u=Dn(i,o,r,vU(i.length*8)),l=await SW(a,u,c);try{if(await PCe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Oc}async function hE(t,e,r,o,n){if(!zc(r)&&!(r instanceof Uint8Array))throw new TypeError(Oa(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?wW(t,o):o=ICe(t),r instanceof Uint8Array&&mE(r,t.cekBits),t.cbc)return ACe(t,e,r,o,n);let i=await Pi(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function gE(t,e,r,o,n,i){if(!zc(e)&&!(e instanceof Uint8Array))throw new TypeError(Oa(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new H("JWE Initialization Vector missing");if(!n)throw new H("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new H("Invalid Authentication Tag length");if(wW(t,o),e instanceof Uint8Array&&mE(e,t.cekBits),t.cbc)return kCe(t,e,r,o,n,i);let s=await Pi(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Dn(r,n)))}catch{throw new Oc}}function ay(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var TCe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],CCe=[[],["deriveBits"]],wE=[[],[]];function yE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:TCe,ops:["wrapKey","unwrapKey"]}}function vE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ct('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:CCe,ops:[void 0,"deriveBits"]}}function sf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:wE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function $U(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:wE,ops:["deriveBits","deriveBits"]}}var Da=ay({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:wE,ops:["encrypt","decrypt"]},"RSA-OAEP":yE(1),"RSA-OAEP-256":yE(256),"RSA-OAEP-384":yE(384),"RSA-OAEP-512":yE(512),"ECDH-ES":vE("direct-key-agreement"),"ECDH-ES+A128KW":vE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":vE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":vE("key-agreement-with-key-wrapping"),A128KW:sf(128),A192KW:sf(192),A256KW:sf(256),A128GCMKW:sf(128,!0),A192GCMKW:sf(192,!0),A256GCMKW:sf(256,!0),"PBES2-HS256+A128KW":$U(),"PBES2-HS384+A192KW":$U(),"PBES2-HS512+A256KW":$U()}),OCe=["encrypt","decrypt"];function af(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:wE,ops:OCe,cekBits:t,ivBits:e?128:96,cbc:e}}var DCe=ay({A128GCM:af(128),A192GCM:af(192),A256GCM:af(256),"A128CBC-HS256":af(256,!0),"A192CBC-HS384":af(384,!0),"A256CBC-HS512":af(512,!0)});function bW(t,e){throw new Ct(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function ki(t){return(typeof t=="string"?Da[t]:void 0)??bW("alg","Algorithm")}function Ti(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function jl(t){return(typeof t=="string"?DCe[t]:void 0)??bW("enc","Encryption Algorithm")}function xW(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");bU(t,e)}async function NCe(t,e,r){let o=await Pi(e,ki(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function zCe(t,e,r){let o=await Pi(e,ki(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function $W(t,e,r){xU(e,ki(t).subtle,r),nf(t,e)}async function RW(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new H("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new H("PBES2 Count Input must be a positive integer");let n=Dn(Gr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Pi(o,ki(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function RU(t){return Dn(rE(t.length),t)}async function MCe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await nE("sha256",Dn(rE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function IW(t,e,r,o,n=new Uint8Array,i=new Uint8Array){xW(t),xW(e,"deriveBits");let s=Dn(RU(Gr(r)),RU(n),RU(i),rE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return MCe(a,o,s)}function AW(t){dE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ct("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function _E(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new H(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return Qn(r,e,H)}}function PW(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new H('JOSE Header "apu" and "apv" values must be distinct')}}function UCe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function EW(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function LCe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function kW(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return EW(o),r;let c=a==="direct-key-agreement";switch(c?EW(o):UCe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!fr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');AW(r);let l=await of(t,u),d=_E(n,"apu"),f=_E(n,"apv");PW(d,f);let p=await IW(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return dE(r),$W(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new H('JOSE Header "p2c" (PBES2 Count) missing or invalid');LCe(i);let u=i??1e4;if(n.p2c>u)throw new H('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new H('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=Qn(n.p2s,"p2s",H);r=await RW(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new H('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new H('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=Qn(n.iv,"iv",H),l=Qn(n.tag,"tag",H);if(u.byteLength!==12)throw new H("Invalid Initialization Vector length");if(l.byteLength!==16)throw new H("Invalid Authentication Tag length");return gE(jl(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return zCe(s.slice(-6),r,o)}async function SE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Ti(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Ai(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Ll(e):void 0;l&&mE(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{AW(u);let{apu:p,apv:m}=i;p!==void 0&&yo(p,'"apu"'),m!==void 0&&yo(m,'"apv"');let y=p??_E(o,"apu"),w=m??_E(o,"apv");PW(y,w);let S;i.epk!==void 0?S=await Ai(t,i.epk,"decrypt"):S=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,x=S;if(!x.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await b.getPublicKey(S,[])}let{x:k,y:T,crv:U,kty:X}=await b.exportKey("jwk",x),ue=a==="direct-key-agreement",Me=await IW(u,S,ue?e.alg:s,ue?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),De={x:k,crv:U,kty:X};if(X==="EC"&&(De.y=T),f={epk:De},p!==void 0&&(f.apu=Qt(p)),m!==void 0&&(f.apv=Qt(m)),ue)return[Me,void 0,f];u=Me;break}case"RSA-OAEP":{dE(u),$W(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await RW(m,s,p,u),f={p2c:p,p2s:Qt(m)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await hE(jl(s.slice(0,-2)),l,u,p,new Uint8Array);d=m.ciphertext,f={iv:Qt(m.iv),tag:Qt(m.tag)}}}if(d??=await NCe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,f]}function bE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ct('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function TW(t){if(typeof globalThis[t]>"u")throw new Ct(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function CW(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new H("Decompressed plaintext exceeded the configured limit")}return Dn(...n)}async function OW(t){return TW("CompressionStream"),CW(new CompressionStream("deflate-raw"),t)}async function DW(t,e){return TW("DecompressionStream"),CW(new DecompressionStream("deflate-raw"),t,e)}function NW(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new H("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new H("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new H("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new H("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new H("JWE AAD incorrect type");if(s!==void 0&&!fr(s))throw new H("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function zW(t){let e,r;try{let{header:o}=t;if(fr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function MW(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new H("JWE Encrypted Key incorrect type");if(r!==void 0&&!fr(r))throw new H("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new H("JOSE Header missing")}function IU(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=rf(e,H,"JWE Protected Header is invalid")),[s,Qn(r,"ciphertext",H),o!==void 0?Qn(o,"iv",H):void 0,n!==void 0?Qn(n,"tag",H):void 0,iE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function xE(t){return[t&&sy("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&sy("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function AU(t,e,r,o=IU(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Dc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,m,y,w,S]=e,{encrypted_key:b}=t;Nc(H,aE,y,n,f),bE(f,n);let{alg:x,enc:k}=f;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Da[x];if(b===""&&(!T||!Ti(T)))throw new H("JWE Encrypted Key incorrect type");let U=T?.mode==="integrated-encryption";if(!U&&(typeof k!="string"||!k))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(x)||!p&&x.startsWith("PBES2"))throw new zl('"alg" (Algorithm) Header Parameter value not allowed');let X;if(U){if(k!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new H("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new H("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(k))throw new zl('"enc" (Encryption Algorithm) Header Parameter value not allowed');X=jl(k)}let ue;if(b!==void 0)try{ue=Qn(b,"encrypted_key",H)}catch(Ue){if(!T||!Ti(T))throw Ue;ue=new Uint8Array}let Me=!1;typeof r=="function"&&(r=await r(n,t),Me=!0);let De=T??ki(x);Ti(De)&&ue===void 0&&(ue=new Uint8Array);let $t=await Ai(De.mode==="direct-encryption"?X:De,r,"decrypt"),at;if(De.mode==="integrated-encryption")at=await De.decrypt($t,ue,i,c,n,f);else{let Ue=X,oe;try{oe=await kW(De,Ue,$t,ue,f,w),Ti(De)&&oe instanceof Uint8Array&&oe.byteLength<<3!==Ue.cekBits&&(oe=Ll(Ue))}catch(Xt){if(Xt instanceof TypeError||Xt instanceof H||Xt instanceof Ct)throw Xt;oe=Ll(Ue)}at=await gE(Ue,oe,i,s,a,c)}if(f.zip==="DEF"){let Ue=S??25e4;if(Ue===0)throw new Ct('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ue!==1/0&&(!Number.isSafeInteger(Ue)||Ue<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");at=await DW(at,Ue).catch(oe=>{throw oe instanceof H?oe:new H("Failed to decompress plaintext",{cause:oe})})}return{plaintext:at,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:Qn(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Me&&{key:$t}}}async function UW(t,e,r){if(t instanceof Uint8Array&&(t=tf.decode(t)),typeof t!="string")throw new H("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new H("Invalid Compact JWE");return AU({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function cy(t,e,r){return UW(t,xE(r),e)}async function PU(t,e,r){if(!fr(t))throw new H("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new H("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(fr))throw new H("JWE Recipients missing or incorrect type");if(!n.length)throw new H("JWE Recipients has no members");let i,s,a;try{i=xE(r),s=NW(t),a=IU(s)}catch{throw new Oc}let c=n.map(u=>zW(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Da[l]:void 0;if(d&&!Ti(d))throw new H(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return MW(l),await AU(l,i,e,a)}catch{}throw new Oc}function EE(t,e,r){if(!Dc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function kU(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new H("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&yo(s,"JWE Additional Authenticated Data"),a!==void 0&&yo(a,"JWE Content Encryption Key"),c!==void 0&&yo(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Ul(H,o)[0],t[1]=o),n!==void 0&&(n=Ul(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=Ul(H,i)[0],t[3]=i),u!==void 0&&!fr(u))throw new TypeError("JWE Key Management Parameters must be an object");EE(o,n,i);let d={...o,...n,...i};cE(H,o),Nc(H,aE,l,o,d),bE(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Da[f];if(m?.mode==="integrated-encryption"){if(p!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!="string"||!p)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,jl(p),m]}async function TU(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,m]=t,y=a,w=c,S=i??ki(o.alg),b,x,k;S.mode==="integrated-encryption"?k=await Ai(S,r,"encrypt"):[k,b,x]=await SE(S,n,r,o,d,p),x&&(m?w=w?{...w,...x}:x:y=y?{...y,...x}:x,EE(y,w,u));let T=y?Qt(JSON.stringify(y)):"",U=l?.byteLength?Qt(l):void 0,X=Gr(U?`${T}.${U}`:T),ue=s;o.zip==="DEF"&&(ue=await OW(ue).catch(Ue=>{throw new H("Failed to compress plaintext",{cause:Ue})}));let Me,De,$t;S.mode==="integrated-encryption"?[b,Me]=await S.encrypt(k,ue,X,y,o,p):{ciphertext:Me,tag:De,iv:$t}=await hE(n,ue,k,f,X);let at={ciphertext:Qt(Me)};return $t&&(at.iv=Qt($t)),De&&(at.tag=Qt(De)),b?.byteLength&&(at.encrypted_key=Qt(b)),U&&(at.aad=U),y&&(at.protected=T),u&&(at.unprotected=u),w&&(at.header=w),at}async function LW(t,e,r){return TU(t,kU(t,r),e)}function jW(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var CU=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Ho(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Ho(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},uy=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new CU(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Ho(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Ho(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new H("at least one recipient must be added");yo(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[y,w,S,b]=m.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,b,e],k=kU(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,k,S]);let[{alg:T,enc:U},,X]=k;if(e&&X&&!Ti(X))throw new H(`"${T}" alg may only have a single recipient`);if(!r)r=U;else if(r!==U)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=ki(m[0].alg);let[s,a,c]=i[0],u=e?Ll(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await TU(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let m=1;m<i.length;m++){let[y,[w,S,b],x]=i[m],k=y[2],[,T,U]=await SE(b,S,x,w,u,y[7]),X={encrypted_key:Qt(T)};if(k||U){let ue={...k,...U};U&&EE(y[1],ue,y[3]),X.header=ue}p.recipients.push(X)}return p}};var ly=[["verify"],["sign"]];function OU(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:ly}}function cf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:ly,minRsaBits:2048}}function DU(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:ly}}function FW(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:ly}}function NU(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:ly}}var zU=ay({HS256:OU(256),HS384:OU(384),HS512:OU(512),RS256:cf(256),RS384:cf(384),RS512:cf(512),PS256:cf(256,32),PS384:cf(384,48),PS512:cf(512,64),ES256:DU("P-256",256),ES384:DU("P-384",384),ES512:DU("P-521",512),EdDSA:FW(),Ed25519:FW(),"ML-DSA-44":NU(44),"ML-DSA-65":NU(65),"ML-DSA-87":NU(87)});function $E(t){let e=typeof t=="string"?zU[t]:void 0;if(!e)throw new Ct(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function qW(t){return[t&&sy("algorithms",t.algorithms),t?.crit]}function jCe(t){return t===void 0?{}:rf(t,Zt,"JWS Protected Header is invalid")}function FCe(t){try{return Gr(t)}catch{throw new Zt("JWS Compact Serialization payload must use only ASCII characters")}}async function qCe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??jCe(i);if(!Dc(c,s))throw new Zt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=uE(c,Nc(Zt,sE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Zt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new zl('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Zt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Zt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let m=$E(d),y=Dn(i!==void 0?Gr(i):new Uint8Array,Gr("."),typeof f=="string"?e[2]??=iE(f,"payload",Zt):f),w=Qn(t.signature,"signature",Zt),S=await Ai(m,r,"verify"),b=await Pi(S,m.subtle,"verify");m.minRsaBits&&nf(m.alg,b);let x=!1;try{x=await crypto.subtle.verify(m.signing,b,w,y)}catch{}if(!x)throw new oE;let k={payload:typeof f=="string"?Qn(f,"payload",Zt):f};return i!==void 0&&(k.protectedHeader=c),s!==void 0&&(k.unprotectedHeader=s),p?[{...k,key:S},l]:[k,l]}async function VW(t,e,r){if(t instanceof Uint8Array&&(t=tf.decode(t)),typeof t!="string")throw new Zt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Zt("Invalid Compact JWS");return qCe({payload:n,protected:o,signature:i},e,r,FCe)}async function MU(t,e,r){let[o]=await VW(t,qW(r),e);return o}var uf=class{#e;constructor(e){yo(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Ho(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Ho(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Ho(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Ho(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return jW(await LW([...this.#e],e,r))}};async function VCe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let S=Ul(Zt,n);n=S[0],a=Qt(S[1])}if(i!==void 0&&(i=Ul(Zt,i)[0]),!n&&!i)throw new Zt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Dc(n,i))throw new Zt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};cE(Zt,n);let u=uE(n,Nc(Zt,sE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Zt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=$E(l),f="",p=o,m;if(u){let S=t[4];S?(f=S[0]??=Qt(o),p=S[1]??=Gr(f)):(f=Qt(o),m=ef.encode(`${a}.${f}`))}m??=Dn(Gr(a),Gr("."),p);let y=await Pi(await Ai(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&nf(d.alg,y);let w={signature:Qt(new Uint8Array(await crypto.subtle.sign(d.signing,y,m))),payload:f};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function GW(t,e,r,o,n){let[i]=await VCe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var dy=class{#e;#t;constructor(e){yo(e,"payload"),this.#e=e}setProtectedHeader(e){return Ho(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return GW(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var UU='"alg" (Algorithm)';function LU(t='JWK "alg" (Algorithm) Parameter'){throw new Ct(`Invalid or unsupported ${t} value`)}function py(t,e){return(typeof t=="string"?zU[t]??Da[t]:void 0)??LU(e)}async function Mc(t){if(_U(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Qt(t)};if(!zc(t))throw new TypeError(Oa(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var Na=(t,e)=>{if(typeof t!="string"||!t)throw new iy(`${e} missing or invalid`)};async function jU(t,e){let r;if(fr(t)){if(r=pE(t),typeof r.kty!="string")throw new TypeError(Oa(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(SU(t))r=pE(await Mc(t));else throw new TypeError(Oa(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":Na(r.alg,'"alg" (Algorithm) Parameter'),Na(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Na(r.crv,'"crv" (Curve) Parameter'),Na(r.x,'"x" (X Coordinate) Parameter'),Na(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Na(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Na(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Na(r.e,'"e" (Exponent) Parameter'),Na(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new iy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ct('"kty" (Key Type) Parameter missing or unsupported')}let n=Gr(JSON.stringify(o));return Qt(await nE(e,n))}async function Bo(t,e,r){if(!fr(t))throw new TypeError("JWK must be an object");let o=EU(t),n=fE(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return Ml(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return of(py(e),o,n)}case"RSA":case"EC":case"OKP":return of(py(e),o,n);default:throw new Ct('Unsupported "kty" (Key Type) Parameter value')}}function FU(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return rf(e,TypeError,r)}function GCe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ct("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function fy(t,e){let r=fE(e?.extractable),o=py(t,UU);o.secret&&LU(UU);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ct("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ct(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:GCe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var ZW=g.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),WW=g.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),HW=g.string().min(1).max(128),BW=g.string().min(1).max(16384),HCe=g.discriminatedUnion("kind",[g.object({kind:g.literal("access_key"),accessKeyId:HW,secretAccessKey:BW}).strict(),g.object({kind:g.literal("session"),accessKeyId:HW,secretAccessKey:BW,sessionToken:g.string().min(1).max(16384),expiresAt:g.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),g.object({kind:g.literal("environment")}).strict()]),BCe=g.object({arn:WW,externalId:g.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),za=g.object({authentication:HCe,region:ZW,role:BCe.optional()}).strict(),RE=g.object({accountId:g.string().regex(/^\d{12}$/),principalId:g.string().min(1).max(256),arn:g.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),IE=za.extend({sourceIdentity:RE,identity:RE}).strict();function lf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function KW(t){return{...t,arn:lf(t.arn)}}function JW(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,sourceIdentity:KW(t.sourceIdentity),identity:KW(t.identity)}}var AE=g.object({authentication:g.enum(["access_key","session","environment"]),region:ZW,sourceAccountId:g.string().regex(/^\d{12}$/),sourceArn:g.string().max(2e3),roleArn:WW.optional(),expiresAt:g.number().int().positive().optional()}).strict();function XW(t){return{authentication:t.authentication.kind,region:t.region,sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn,...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}typeof window<"u"&&g.config({jitless:!0});var E=g.uuid(),pe=g.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),nt=g.iso.datetime(),ln=g.json(),er=g.record(g.string(),ln),QW=g.enum(["ja","en"]),e5=g.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var t5=g.enum(["variable","connection","service","method","app","object","environment","function"]),dn=g.object({kty:g.literal("EC"),crv:g.literal("P-256"),x:g.string().min(40).max(50),y:g.string().min(40).max(50)}).strict(),KCe=g.object({alg:g.literal("dir"),enc:g.literal("A256GCM"),sub:E}).strict(),TE=g.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return KCe.safeParse(FU(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),vo=g.object({protected:g.string().max(2048),iv:g.string().max(64),ciphertext:g.string().max(2e6),tag:g.string().max(64),aad:g.string().max(2048).optional(),recipients:g.array(g.object({encrypted_key:g.string().max(2048),header:g.object({kid:E,epk:dn.optional(),alg:g.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Mvt=g.object({id:E,name:pe,publicKey:dn}),df=g.object({id:E,name:pe,owner:g.object({id:E,name:pe}).nullable(),createdAt:nt,permissions:g.array(e5),createKinds:g.array(t5),publicKey:dn.nullable()}),r5=g.object({id:E,kind:g.enum(["passkey","email","key"]),name:g.string(),createdAt:nt,lastUsedAt:nt.nullable(),expiresAt:nt.nullable(),canOpen:g.boolean()}),n5=g.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),ZCe=g.object({subjectId:E,relation:n5,objectId:E}).strict(),Uvt=ZCe.extend({objectType:g.enum(["principal",...t5.options]),subjectName:pe,objectName:pe,createdAt:nt}),Lvt=g.object({error:g.object({code:g.string(),message:g.string(),details:ln.optional()})}),jvt=g.object({ok:g.literal(!0)}),o5=g.object({name:g.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:g.string(),secret:g.boolean().optional(),required:g.boolean().optional(),placeholder:g.string().optional(),note:g.string().optional(),pattern:g.string().optional()}),i5=g.record(g.string().regex(/^[A-Z_][A-Z0-9_]*$/),g.string()),WCe=g.object({values:g.array(g.object({id:g.string(),name:g.string(),description:g.string().optional()})).optional(),default:g.array(g.string()).default([]),required:g.array(g.string()).optional(),separator:g.string().default(" "),docs:g.url().optional()}),PE=g.string().min(1).max(4096),YW=g.union([g.string(),g.array(g.string()).min(1)]),JCe=g.object({application:g.enum(["required","implicit"]).default("required"),grantType:g.enum(["authorization_code","client_credentials"]).optional(),issuer:g.url().optional(),authorizeUrl:PE.optional(),tokenUrl:PE,identity:g.object({url:PE.optional(),from:g.enum(["token","app"]).optional(),method:g.enum(["GET","POST"]).default("GET"),id:YW.default("/id"),name:YW.default("/name"),headers:g.record(g.string(),g.string()).default({})}).optional(),revoke:g.object({url:PE,style:g.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:g.enum(["body","basic","none"]).optional()}).optional(),clientAuth:g.enum(["body","basic","none"]).default("body"),pkce:g.boolean().default(!0),tokenFormat:g.enum(["form","json"]).default("form"),okPointer:g.string().optional(),authorizeParams:g.record(g.string(),g.string()).default({}),tokenParams:g.record(g.string(),g.string()).default({}),defaults:g.record(g.string(),g.string()).default({}),scopes:WCe.default({default:[],separator:" "}),fields:g.array(o5).default([]),outputs:i5.default({ACCESS_TOKEN:"/accessToken"}),adapter:g.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:g.array(g.string()).default([]),hint:g.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),XCe=g.object({fields:g.array(o5).min(1),outputs:i5,console:g.url().optional(),instructions:g.string().optional(),hint:g.string().optional()}),VU=g.enum(["oauth","token","aws"]),YCe=g.object({hint:g.string().optional()}).strict(),GU={name:pe,docs:g.url().optional(),console:g.url().optional()},CE=g.object({...GU,kind:g.literal("oauth"),config:JCe}).strict(),OE=g.object({...GU,kind:g.literal("token"),config:XCe}).strict(),DE=g.object({...GU,kind:g.literal("aws"),config:YCe}).strict(),Fl=g.discriminatedUnion("kind",[CE,OE,DE]),qU={id:g.string().min(1),builtin:g.boolean(),availability:g.enum(["ready","app-required","unavailable"])},my=g.discriminatedUnion("kind",[CE.extend(qU),OE.extend(qU),DE.extend(qU)]),HU=g.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),BU=g.object({name:pe,logo:g.string().regex(/^[a-z0-9-]+$/).optional(),api:g.url().optional(),docs:g.url().optional(),console:g.url().optional()}).strict(),QCe=BU.extend({methods:g.record(HU,g.string().min(1))}).strict(),s5=BU.extend({methods:g.record(HU,g.union([g.string().min(1),Fl]))}).strict(),Fvt=BU.extend({id:g.string(),builtin:g.boolean(),methods:g.record(HU,my)}),a5=g.object({id:E,output:g.string().min(1).max(100).optional()}).strict(),c5=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),KU=g.object({name:g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:a5,format:g.enum(["text","file","json"]).default("text"),pointer:g.string().optional()}).strict(),eOe=g.object({pointer:g.string().max(500),parts:g.array(g.union([g.string().max(8192),a5])).min(1).max(32)}).strict(),Ma=g.object({url:g.string().max(4096),method:g.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:g.record(g.string(),g.string().max(8192)).default({}),body:g.string().max(1e6).optional(),json:ln.optional(),form:g.record(g.string(),g.string()).optional(),bindings:g.array(eOe).max(32).default([])}).strict(),Ua=g.object({command:g.array(g.string().max(8192)).min(1).max(100),stdin:g.string().max(1e6).optional(),timeoutSeconds:g.number().int().min(1).max(3600).default(60),inputs:g.array(KU).max(32).default([])}).strict(),tOe=g.discriminatedUnion("kind",[Ua.omit({stdin:!0}).extend({kind:g.literal("command")}).strict(),g.object({kind:g.literal("http"),request:Ma}).strict()]),ql=g.object({description:g.string().max(2e3).default(""),environmentId:E,program:tOe,parameters:g.array(g.object({name:g.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:g.string().max(100),type:g.enum(["string","number","boolean","json"]).default("string"),required:g.boolean().default(!0),default:ln.optional()}).strict()).max(32).default([]),result:g.enum(["text","json"]).default("json")}).strict(),Uc={id:E,ownerId:E,name:pe,createdAt:nt,updatedAt:nt,version:g.number().int().positive(),permissions:g.array(e5)},rOe=g.enum(["starting","running","stopping","stopped","failed"]),nOe=g.object({state:g.enum(["pending","failed","complete"]),error:g.string().nullable()}),oOe=g.object({idleSeconds:g.number().int().min(60).max(86400).default(3600),maxSeconds:g.number().int().min(60).max(86400).default(3600)}).strict(),u5=g.object({image:g.string().min(1).max(300).optional(),size:g.enum(["small","medium","large"]).default("small"),lifetime:oOe.default({idleSeconds:3600,maxSeconds:3600}),ssh:oy.optional()}).strict(),ZU={recipients:g.array(E).default([]),executors:g.array(E).default([]),custodyRevision:g.number().int().positive().nullable().default(null)},iOe=g.object({...Uc,kind:g.literal("variable"),data:g.object({...ZU,bytes:g.number().int().nonnegative()})}),sOe=g.object({...Uc,kind:g.literal("connection"),data:g.object({...ZU,methodId:g.string(),methodName:g.string(),methodKind:VU,services:g.array(g.object({id:g.string(),name:pe})).default([]),account:g.string(),accountId:g.string().nullable().default(null),accountVerified:g.boolean().default(!1),scopes:g.array(g.string()),scopesStatus:g.enum(["unknown","requested","reported"]).default("unknown"),outputs:g.array(g.string()),state:g.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:g.string().optional(),aws:AE.optional()})}),aOe=g.object({...Uc,kind:g.literal("service"),data:QCe}),cOe=g.object({...Uc,kind:g.literal("method"),data:Fl}),uOe=g.object({...Uc,kind:g.literal("app"),data:g.object({...ZU,methodId:g.string(),clientId:g.string(),fields:g.record(g.string(),g.string()).default({}),generation:E.optional()})}),lOe=g.object({...Uc,kind:g.literal("object"),data:g.object({size:g.number().int().nonnegative(),contentType:g.string()})}),dOe=g.object({...Uc,kind:g.literal("environment"),data:u5.extend({executorId:E.optional(),operatorId:E.optional(),driver:g.enum(["attached","managed"]).optional(),capabilities:g.array(g.string()).optional(),isolation:g.enum(["process","container"]).optional(),manifestDigest:g.string().optional(),processes:g.object({workingDirectory:g.string()}).optional(),ssh:gU.optional(),awsPrincipal:g.string().optional(),state:rOe,deletion:nOe.optional(),startedAt:nt.nullable(),stoppedAt:nt.nullable(),lastActiveAt:nt,error:g.string().nullable()})}),pOe=g.object({...Uc,kind:g.literal("function"),data:ql}),pn=g.discriminatedUnion("kind",[iOe,sOe,aOe,cOe,uOe,lOe,dOe,pOe]),qvt=g.discriminatedUnion("kind",[g.object({kind:g.literal("service"),name:pe,definition:s5}).strict(),g.object({kind:g.literal("method"),name:pe,definition:Fl}).strict(),g.object({kind:g.literal("environment"),name:pe.optional(),options:u5}).strict()]),Vvt=g.object({version:g.number().int().positive(),name:pe.optional(),definition:g.union([s5,Fl]).optional()}).strict(),Ci=g.object({name:g.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:er}).strict(),l5=Ci.extend({inputs:g.array(g.object({pointer:g.string(),label:g.string().min(1).max(100),secret:g.boolean().default(!1),multiline:g.boolean().default(!1),site:g.url().optional()}).strict()).max(16).default([])}),WU=g.object({ja:g.string(),en:g.string()}).strict(),d5=g.object({to:E.optional(),message:g.string().max(1e3).default(""),operations:g.array(l5).min(1).max(8),expiresInMinutes:g.number().int().min(1).max(1440).default(30)}).strict(),kE=g.object({id:E,name:pe}),fOe=g.discriminatedUnion("kind",[g.object({kind:g.literal("line"),subject:kE,relation:n5,object:kE}),g.object({kind:g.literal("transfer"),item:kE,to:kE})]),pf=g.object({id:E,from:df.pick({id:!0,name:!0}),to:df.pick({id:!0,name:!0}).nullable(),message:g.string(),proposal:fOe.nullable(),operations:g.array(l5.extend({title:WU,execution:g.enum(["server","keyholder"])})),state:g.enum(["pending","running","approved","declined","cancelled","expired"]),results:g.array(ln.nullable()),createdAt:nt,expiresAt:nt,url:g.url(),code:g.string().optional(),returnUrl:g.url().nullable(),refreshUrl:g.url().nullable(),canRespond:g.boolean(),waiting:g.object({index:g.number().int().nonnegative(),invocation:Ci,approval:g.object({id:E,index:g.number().int().nonnegative()}).strict().optional(),continuation:g.object({kind:g.enum(["connection","run"]),id:E}).strict().nullable()}).strict().nullable()}),Gvt=g.object({id:E,name:pe,publicKey:dn,state:g.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:nt,expiresAt:nt}),Hvt=g.object({available:g.boolean(),required:g.boolean(),active:g.boolean(),payer:df.pick({id:!0,name:!0}).nullable()}),Bvt=g.object({storageBytes:g.number().nonnegative(),storageLimit:g.number().positive(),computeSeconds:g.number().nonnegative(),computeLimit:g.number().positive(),month:g.string()}),Kvt=g.object({id:g.string(),actorId:E.nullable(),action:g.string(),targetId:E.nullable(),createdAt:nt,details:er}),Zvt=g.object({returnUrl:g.url().optional(),refreshUrl:g.url().optional()}).strict(),wo=t=>g.object({items:g.array(t),next:g.string().nullable().default(null)}),Wvt=g.object({id:E}),Jvt=g.object({owner:E}),mOe=g.object({limit:g.coerce.number().int().min(1).max(200).default(100),after:g.string().optional()}),Xvt=mOe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var hOe=g.object({email:g.boolean(),environments:g.boolean(),ssh:g.boolean(),objects:g.boolean(),payments:g.boolean()}),NE=g.object({principal:df.nullable(),credentialId:E.nullable(),wrappedKey:TE.nullable(),requestId:E.nullable(),server:g.object({name:pe}),features:hOe,principals:g.array(df)}),twt=g.object({email:g.email().max(254),returnTo:g.string().max(2048).optional(),locale:QW.default("ja"),principalId:E.optional()}).strict(),rwt=g.object({intent:g.enum(["register","authenticate"]),name:pe.optional(),principalId:E.optional(),returnTo:g.string().max(2048).optional()}).strict(),nwt=g.object({challengeId:E,credential:g.json(),publicKey:dn.optional(),existingPublicKey:dn.optional(),wrappedKey:TE.optional()}).strict();var gOe=new TextEncoder,yOe=new TextDecoder,hy="ECDH-ES+A256KW",JU="A256GCM",mt=t=>gOe.encode(t),La=t=>yOe.decode(t);function Lc(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function p5(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function zE(){let t=await fy(hy,{crv:"P-256",extractable:!0});return{publicKey:dn.parse(await Mc(t.publicKey)),privateKey:await Mc(t.privateKey)}}async function ja(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new uy(t).setProtectedHeader({enc:JU}).setAdditionalAuthenticatedData(mt(r));for(let n of e)o.addRecipient(await Bo(n.publicKey,hy)).setUnprotectedHeader({alg:hy,kid:n.id});return vo.parse(await o.encrypt())}async function Ko(t,e,r,o){if(t.aad!==Lc(mt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await Bo(e,hy);return(await PU({...t,recipients:[n]},i,{keyManagementAlgorithms:[hy],contentEncryptionAlgorithms:[JU]})).plaintext}async function vOe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:mt("Foundation"),info:mt("passkey encryption key")},e,256))}async function f5(t,e,r){let o=await cy(t,await vOe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[JU]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(La(o.plaintext))}var Ar=g.string().regex(/^[A-Za-z0-9_-]{43}$/),Nn=g.string().min(100).max(4e6),m5=dn.extend({d:g.string().regex(/^[A-Za-z0-9_-]{43}$/)}),gy=g.object({encryption:m5,signing:m5}).strict(),Pr=g.object({id:E,principalId:E,generation:g.number().int().positive(),previous:Ar.nullable(),encryption:dn,signing:dn}).strict();function D(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,D).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+D(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function ff(t){return jU(dn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function me(t){return Lc(new Uint8Array(await crypto.subtle.digest("SHA-256",mt(D(t)))))}async function Vl(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",mt(D(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function UE(){let[t,e]=await Promise.all([zE(),fy("ES256",{crv:"P-256",extractable:!0})]),r=await Mc(e.privateKey);return gy.parse({encryption:t.privateKey,signing:r})}function ME(t){return dn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function LE(t,e){return Pr.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:ME(e.encryption),signing:ME(e.signing)})}async function fn(t,e,r){let o=e instanceof CryptoKey?e:await Bo(e,"ES256");return new dy(mt(D(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function eo(t,e,r,o){if(D(await XU(e,r,o))!==D(t))throw new Error("The signature does not authorize this content.")}async function XU(t,e,r){let o=await MU(t,await Bo(dn.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(D(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Rs=g.object({binding:Pr,signature:Nn}).strict();async function yy(t,e){if(await jc(t),await ff(e.encryption)!==await ff(t.encryption)||await ff(e.signing)!==await ff(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await fn(t,e.signing,"key-binding")}}async function jc(t){let e=Pr.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await ff(e.encryption)===await ff(e.signing))throw new Error("Use separate encryption and signing keys.");await Bo(e.encryption,"ECDH-ES+A256KW"),await Bo(e.signing,"ES256")}async function YU(t){let{binding:e,signature:r}=Rs.parse(t);return await jc(e),await eo(e,r,e.signing,"key-binding"),e}var h5=g.object({ownerId:E,name:pe,resourceId:E.optional(),version:g.number().int().positive().optional(),environmentIds:g.array(E).max(32).optional()}).strict(),g5=h5.extend({value:g.literal("").optional()}),QU=h5.extend({methodId:g.string().min(1).max(200),clientId:g.string().max(1e3),fields:g.record(g.string(),g.literal("")).default({}),clientSecret:g.literal("").optional()}),jE=g.object({ownerId:E,name:pe,definition:ql,resourceId:E.optional(),version:g.number().int().positive().optional()}).strict(),FE=g.object({ownerId:E,methodId:g.string().min(1).max(200),connectionId:E.optional(),environmentId:E.optional(),name:pe.optional(),appId:E.optional(),environments:g.array(E).max(32).optional(),redirectUri:g.url().optional(),methodDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:g.string().max(1e3).optional(),fields:g.record(g.string(),g.literal("")).optional(),clientSecret:g.literal("").optional()}).strict(),vy=g.object({ownerId:E,environmentId:E.optional(),operation:g.union([g.object({kind:g.literal("http"),request:Ma}).strict(),Ua.extend({kind:g.literal("command")}),g.object({kind:g.literal("function"),functionId:E,definitionDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),arguments:er.default({})}).strict(),g.object({kind:g.enum(["http","command","function"]),programId:E,programDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/),functionId:E.optional(),definitionDigest:g.string().regex(/^[A-Za-z0-9_-]{43}$/).optional()}).strict()]),save:g.record(g.string(),pe).default({})}).strict().superRefine((t,e)=>{t.operation.kind!=="function"&&!t.environmentId&&e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."}),t.operation.kind==="function"&&!t.operation.functionId&&e.addIssue({code:"custom",path:["operation","functionId"],message:"Choose a saved function."})}),eL=g.object({name:Ci.shape.name,title:WU,execution:g.enum(["server","keyholder"]),input:er}).strict(),mf=g.object({index:g.number().int().nonnegative(),invocation:Ci,approval:g.object({id:E,index:g.number().int().nonnegative()}).strict().optional(),continuation:g.object({kind:g.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),_o=g.object({id:E,actorId:E,index:g.number().int().nonnegative(),state:g.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:g.enum(["approval","input"]).nullable(),waiting:mf.nullable(),results:g.array(ln.nullable()),createdAt:g.iso.datetime(),expiresAt:g.iso.datetime()}).strict(),y5=g.object({id:E,index:g.number().int().nonnegative(),invocation:Ci,continuationId:E.optional()}).strict();var hf=g.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ht={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632"},wOe=g.enum([ht.value,ht.tokenSet,ht.clientCredential]),le={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"},wy=g.enum([le.http,le.command,le.function,le.connect,le.refresh,le.revoke]);var _Oe={[ht.value]:[le.http,le.command,le.function],[ht.tokenSet]:[le.http,le.command,le.function,le.refresh,le.revoke],[ht.clientCredential]:[le.connect,le.refresh,le.revoke]},qE=t=>_Oe[t],tL=t=>qE(t).filter(e=>e===le.function||e===le.refresh),rL=t=>t===ht.tokenSet,SOe=g.object({id:E,digest:Ar}).strict(),bOe=g.object({actor:Pr,executor:Pr,operations:g.array(wy).min(1).max(6),functionDigests:g.array(Ar).max(100).default([]),origins:g.array(hf).max(100).default([]),callerProgram:g.boolean().default(!1),expiresAt:nt}).strict(),xOe=g.object({function:SOe,executor:Pr,operations:g.array(wy).min(1).max(6),expiresAt:nt}).strict(),EOe=g.union([bOe,xOe]),Di=g.object({format:g.literal(2),origin:hf,id:E,ownerId:E,contentType:wOe,revision:g.number().int().positive(),authorities:g.array(Pr).min(1).max(100),readers:g.array(Pr).min(1).max(100),grants:g.array(EOe).max(100),observers:g.array(E).max(100).optional(),producers:g.array(g.object({executor:Pr,runId:E,expiresAt:nt,materialRevision:g.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),v5=g.object({ownerId:E,authorities:g.array(Pr).min(1).max(100)}).strict(),w5=g.object({origin:hf,id:E,revision:g.number().int().positive(),from:v5,to:v5,policyDigest:Ar,previous:Ar.nullable(),signerId:E}).strict(),$Oe=w5.extend({signature:Nn}),nL=g.array($Oe).max(16),_y=g.object({policy:Di,authorityId:E,signature:Nn,lineage:nL.optional()}).strict(),So=g.object({policy:Di,authorityId:E,authorization:Nn,lineage:nL.optional(),materialRevision:g.number().int().positive(),updatedAt:nt,creationRunId:E.nullable(),metadata:er,sealed:vo,signerId:E,signature:Nn}).strict(),Gl=t=>({ownerId:t.ownerId,authorities:t.authorities});async function _5(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||D(r.to)!==D(o.from))||o.previous!==(r?await me(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await eo(i,n,s.signing,"authority-handoff"),r=o}if(r&&D(r.to)!==D(Gl(t)))throw new Error("Use the authorities approved by the latest handoff.")}function oL(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function S5(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=D(Gl(t));return r===D(Gl(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&D(o.from)===r)}async function b5(t,e,r,o){let n=[...t?.lineage??[]];if(t&&D(Gl(t.policy))!==D(Gl(e))){if(await Oi(t),!t.policy.authorities.some(s=>D(s)===D(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=w5.parse({origin:e.origin,id:e.id,revision:e.revision,from:Gl(t.policy),to:Gl(e),policyDigest:await me(e),previous:n.length?await me(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await fn(i,o.signing,"authority-handoff")})}return n.length?{lineage:nL.parse(n)}:{}}async function VE(t){let e=Di.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await jc(n);let i=D(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!qE(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==le.function&&i!==le.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===le.http||i===le.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(le.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function GE(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function gf(t,e){return D({purpose:"resource",policyDigest:await me(t),materialRevision:e})}async function HE(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await VE(e),c=await b5(s,a,o,n);if(!a.authorities.some(f=>D(f)===D(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await ja(t,GE(a).map(f=>({id:f.id,publicKey:f.encryption})),await gf(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await fn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ht.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=So.parse({...l,signature:await fn(l,n.signing,"resource")});return await Oi(d),d}async function Oi(t){let e=So.parse(t),{signature:r,...o}=e;await VE(e.policy),await _5(e.policy,e.lineage);let n=oL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await me(e.policy))throw new Error("The handoff approves a different access policy.");await eo(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor??(rL(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(le.refresh)&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await eo(o,r,s.signing,"resource");let a=GE(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(D(a)!==D(c)||e.sealed.aad!==Lc(mt(await gf(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function x5(t,e,r,o,n=t.metadata){let i=await Oi(t);if(!rL(i.policy.contentType)||!(i.policy.authorities.some(f=>D(f)===D(r))||i.policy.grants.some(f=>D(f.executor)===D(r)&&f.operations.includes(le.refresh)&&Date.parse(f.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await ja(e,GE(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await gf(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await fn(l,o.signing,"resource")};return await Oi(d),d}async function BE(t,e,r,o){let n=await VE(t);if(!n.authorities.some(s=>D(s)===D(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await b5(o,n,e,r),authorityId:e.id,signature:await fn(n,r.signing,"access-policy")};return await yf(i),i}async function yf(t){let e=_y.parse(t);await VE(e.policy),await _5(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await me(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await eo(e.policy,e.signature,o.signing,"access-policy"),e}async function Sy(t,e,r,o,n,i){let s=await yf(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&D(f.executor)===D(o)&&Date.parse(f.expiresAt)>Date.now());if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let u=await ja(t,GE(a).map(f=>({id:f.id,publicKey:f.encryption})),await gf(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await fn(l,n.signing,"resource")};return await Oi(d),d}async function KE(t,e,r){let o=await Oi(t);if(!o.policy.readers.some(n=>D(n)===D(e)))throw new Error("This identity cannot reveal the content.");return Ko(o.sealed,r,e.id,await gf(o.policy,o.materialRevision))}var ROe=g.object({id:E,policyDigest:Ar,materialRevision:g.number().int().positive(),authorizationDigest:Ar.optional()}).strict();async function iL(t,e){return e.id===t.policy.id&&e.policyDigest===await me(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||rL(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var ZE=g.object({format:g.literal(2),id:E,origin:hf,ownerId:E,approval:g.object({id:E,index:g.number().int().min(0).max(7)}).strict().optional(),operationContext:y5.optional(),actor:Pr,environmentId:E,executor:Pr,environmentDigest:Ar,operation:wy,functionDigest:Ar.nullable(),functionId:E.optional(),operationDigest:Ar,sources:g.array(ROe).max(100),resultRecipients:g.array(Pr).min(1).max(100),createdAt:nt,expiresAt:nt}).strict(),Fc=g.object({intent:ZE,signature:Nn,sealed:vo}).strict();async function Hl(t,e){return D({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await me(t)})}async function E5(t,e,r){if(ZE.parse(t),await me(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await ja(mt(D(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Hl(t,"input"))};return Fc.parse({...o,signature:await fn(o,r.signing,"run")})}async function IOe(t,e=Date.now()){let r=Fc.parse(t),{signature:o,...n}=r;await eo(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Lc(mt(await Hl(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function $5(t,e,r){let o=await IOe(t);if(D(o.intent.executor)!==D(e))throw new Error("This operation belongs to another executor.");let n=await Ko(o.sealed,r.encryption,e.id,await Hl(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(D(s)!==i||await me(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function Bl(t,e,r={}){let o=await Oi(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await iL(o,i))throw new Error("The input changed after this execution was authorized.");if(D(e.actor)===D(e.executor)&&n.readers.some(c=>D(c)===D(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?D(c.actor)===D(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&D(c.executor)===D(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===le.function||e.operation===le.refresh:e.operation===le.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==le.command&&e.operation!==le.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function qc(t,e,r,o={}){return await Bl(t,e,o),Ko(t.sealed,r.encryption,e.executor.id,await gf(t.policy,t.materialRevision))}var sL=g.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),I5=g.object({format:g.literal(3),id:E,origin:hf,ownerId:E,name:pe,executor:Pr,operatorId:E,driver:g.enum(["attached","managed"]),capabilities:g.array(wy).min(1).max(6),functionVersion:g.literal(1).optional(),isolation:g.enum(["process","container"]),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:sL.optional(),revision:g.number().int().positive()}).strict(),WE=g.object({manifest:I5,signature:Nn}).strict();async function aL(t,e){let r=I5.parse(t),o={manifest:r,signature:await fn(r,e.signing,"environment")};return await Kl(o),o}async function Kl(t){let e=WE.parse(t),{manifest:r}=e;if(await jc(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(le.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(le.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await eo(r,e.signature,r.executor.signing,"environment"),e}async function JE(t,e){let{manifest:r}=await Kl(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await me(r)||D(e.executor)!==D(r.executor)||!r.capabilities.includes(e.operation)||e.operation===le.function&&r.functionVersion!==1)throw new Error("This environment does not authorize the requested execution.")}var AOe=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),A5=g.object({ok:g.boolean(),result:ln.nullable(),error:g.object({code:g.string().max(100),message:g.string().max(1e3)}).nullable()}).strict(),xy=g.object({id:E,intentDigest:Ar,executorId:E,state:g.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:nt,sealed:vo,signature:Nn}).strict(),by=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function vf(t,e,r,o){let n=A5.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=mt(D(n));if(i.byteLength>14e5)throw new by;let s=await ja(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Hl(t,"result")),a={id:t.id,intentDigest:await me(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return xy.parse({...a,signature:await fn(a,o.signing,"receipt")})}async function POe(t,e){let r=xy.parse(t),{signature:o,...n}=r;if(await eo(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await me(e)||r.executorId!==e.executor.id||r.sealed.aad!==Lc(mt(await Hl(e,"result")))||D(r.sealed.recipients.map(i=>i.header.kid).sort())!==D(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function P5(t,e,r,o){await POe(t,e);let n=await Ko(t.sealed,o.encryption,r,await Hl(e,"result")),i=A5.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var kOe=g.enum(["http","command","function","connect","refresh","revoke"]),zn=g.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:kOe,state:AOe,intent:ZE,requestSignature:Nn,receipt:xy.nullable(),error:g.string().nullable(),createdAt:nt,startedAt:nt.nullable(),finishedAt:nt.nullable()}).strict(),R5=g.object({name:pe,approval:_y}).strict(),Is=g.discriminatedUnion("kind",[g.object({kind:g.literal("http"),request:Ma,save:g.record(g.string(),R5).default({})}).strict(),g.object({kind:g.literal("command"),...Ua.shape}).strict(),g.object({kind:g.literal("function"),functionId:E,definition:ql,arguments:er.default({}),outputs:g.record(g.string(),R5).default({})}).strict(),g.object({kind:g.enum(["connect","refresh","revoke"]),input:ln}).strict()]);var Vc=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Fa=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=g.object({error:g.object({code:g.string(),message:g.string()})}).parse(await n.json())}catch{throw new Vc("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new Vc(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await(await this.response(e,r)).json();return o?o.parse(n):n}async session(){return this.json("/api/session",{},NE)}};import{chmod as TOe,lstat as COe,mkdir as OOe,open as cL,readFile as T5,rename as DOe,rm as NOe}from"node:fs/promises";import{dirname as zOe,join as uL,resolve as MOe}from"node:path";import{homedir as UOe}from"node:os";import{randomUUID as LOe}from"node:crypto";var lL=g.object({origin:g.url(),principalId:g.uuid(),token:g.string().min(20),keys:gy.nullable(),binding:Pr.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),C5=g.object({current:g.uuid(),identities:g.array(lL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function qa(){return uL(process.env.XDG_CONFIG_HOME||uL(UOe(),".config"),"foundation","identity.json")}function Gc(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function XE(t){let e;try{let n=qa(),i=await COe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await TOe(n,384);let s=C5.parse(JSON.parse(await T5(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=Gc(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Gc(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return lL.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==Gc(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Ey(t){let e=qa(),r;try{r=C5.parse(JSON.parse(await T5(e,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=lL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await wf(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
129
129
|
`,!!r)}async function k5(t){if(process.platform==="win32")return;let e=await cL(t,"r");try{await e.sync()}finally{await e.close()}}async function wf(t,e,r){let o=MOe(t),n=zOe(o);if(await OOe(n,{recursive:!0,mode:448}),!r){let s=await cL(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await k5(n);return}let i=uL(n,".foundation-"+LOe());try{let s=await cL(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await DOe(i,o),await k5(n)}finally{await NOe(i,{force:!0})}}import{spawn as VOe}from"node:child_process";import{chmod as GOe,mkdtemp as HOe,rm as BOe,writeFile as KOe}from"node:fs/promises";import{tmpdir as ZOe}from"node:os";import{join as M5}from"node:path";import{StringDecoder as WOe}from"node:string_decoder";import{spawn as O5}from"node:child_process";import{mkdir as D5,mkdtemp as jOe,rm as FOe,writeFile as N5}from"node:fs/promises";import{tmpdir as qOe}from"node:os";import{join as $y}from"node:path";import{StringDecoder as z5}from"node:string_decoder";function Ni(t={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...t}}var Ry=class{constructor(e){this.options=e;if(e.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(e.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(e,r){r.throwIfAborted();let o=await jOe($y(qOe(),"foundation-job-")),n=$y(o,"files"),i="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=e.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await D5(n,{mode:448});let l={...e.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[f,p]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(f))throw new Error("Use valid file variable names.");await N5($y(n,f),Buffer.from(p,"base64"),{mode:384,flag:"wx"}),l[f]=s?"/run/foundation/"+f:$y(n,f)}let d=e.command;if(s){if(Object.entries(l).some(([m,y])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m)||y.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let f=Object.entries(l).filter(([,m])=>/[\r\n]/.test(m)),p=$y(o,"environment");await N5(p,Object.entries(l).filter(([,m])=>!/[\r\n]/.test(m)).map(([m,y])=>m+"="+y).join(`
|
|
130
|
-
`),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await D5(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",p,...f.flatMap(([m,y])=>["--env",m+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(f=>{let p=O5(d[0],d.slice(1),{env:Ni(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),m={stdout:new z5("utf8"),stderr:new z5("utf8")},y=0,w=!1,S=(T,U)=>{let X=Math.max(0,1e6-y);U.length>X&&(c.truncated=!0);let ue=U.subarray(0,X);y+=ue.length,c[T]+=m[T].write(ue)};p.stdout.on("data",T=>S("stdout",T)),p.stderr.on("data",T=>S("stderr",T)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let b=()=>{u=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,b()},e.timeoutSeconds*1e3);x.unref();let k=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",b),c.stdout+=m.stdout.end(),c.stderr+=m.stderr.end(),f())};r.addEventListener("abort",b,{once:!0}),r.aborted&&b(),p.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",k()}),p.once("close",(T,U)=>{c.exitCode=T,c.signal=U,k()})}),c}finally{s&&u&&await new Promise(l=>{let d=O5("docker",["rm","-f",i],{env:Ni(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await FOe(o,{recursive:!0,force:!0})}}};function JOe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var YE=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new WOe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function U5(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await HOe(M5(ZOe(),"foundation-"));await GOe(r,448);try{let o=Ni(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=M5(r,i);await KOe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=VOe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=JOe(n),u=new YE(c,m=>process.stdout.write(m)),l=new YE(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},f=()=>d("SIGINT"),p=()=>d("SIGTERM");process.on("SIGINT",f),process.on("SIGTERM",p),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,y)=>{process.off("SIGINT",f),process.off("SIGTERM",p),u.end(),l.end(),i(m??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await BOe(r,{recursive:!0,force:!0})}}import{dirname as $3e,join as xV}from"node:path";function Zo(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function QE(t,e){return[...new Set([...t.required??[],...e??t.default])]}function As(t){return Zo(t).requiresApp}var XOe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),L5=er.refine(t=>Object.keys(t).every(e=>!XOe.has(e)),"Keep method-specific facts separate from common facts."),dL=g.object({accountId:g.string().max(2e3).nullable(),accountName:g.string().max(2e3),accountVerified:g.boolean(),scopes:g.array(g.string().max(1e3)).max(200),scopesStatus:g.enum(["unknown","requested","reported"]),authorization:L5,details:L5}).strict();function pL(t){if(t.method.kind!=="oauth"||!t.oauth)throw new Error("Use OAuth connection material.");return dL.parse({accountId:t.oauth.account,accountName:t.oauth.accountName,accountVerified:t.oauth.accountVerified??!1,scopes:t.oauth.scopes,scopesStatus:t.oauth.scopesStatus??"unknown",authorization:{},details:{}})}function fL(t){if(t.method.kind!=="token"||!t.fields)throw new Error("Use token connection material.");return dL.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function mL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return dL.parse({accountId:lf(t.aws.identity.arn),accountName:t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1),accountVerified:!0,scopes:[],scopesStatus:"unknown",authorization:{aws:JW(t.aws)},details:{aws:XW(t.aws)}})}var YOe={oauth:pL,token:fL,aws:mL};function _f(t){return YOe[t.method.kind](t)}function j5(t,e=_f(t)){return e.accountVerified?e.accountId:null}function F5(t,e=_f(t)){return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...e.authorization,...t.state?{state:t.state}:{}}}var e$=g.record(g.string().max(100),g.string().max(16384)),Zl=g.object({format:g.literal(1),methodId:g.string().min(1),generation:E,clientId:g.string().max(1e3),clientSecret:g.string().max(16384).optional(),fields:e$}).strict(),gL=g.object({accessToken:g.string().min(1).max(16384),refreshToken:g.string().min(1).max(16384).optional(),expiresAt:g.number().nullable(),refreshExpiresAt:g.number().optional(),scopes:g.array(g.string()),requestedScopes:g.array(g.string()).optional(),account:g.string(),accountName:g.string(),accountVerified:g.boolean().optional(),scopesStatus:g.enum(["unknown","requested","reported"]).optional(),extra:e$,facts:er}).strict(),hL={format:g.literal(2),methodId:g.string().min(1),method:Fl,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:g.literal("reconnect").optional()},Sf=g.never().optional(),zi=g.union([g.object({...hL,method:CE,oauth:gL,fields:Sf,aws:Sf}).strict(),g.object({...hL,method:OE,fields:e$,oauth:Sf,aws:Sf}).strict(),g.object({...hL,method:DE,aws:IE,oauth:Sf,fields:Sf}).strict()]).superRefine((t,e)=>{t.method.kind==="oauth"&&As(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the OAuth application required by this connection."}),t.method.kind!=="oauth"&&t.appId!==null&&e.addIssue({code:"custom",message:"Only OAuth connections use an application."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),f_t=g.object({methodId:g.string().min(1).max(200),clientId:g.string().max(1e3),generation:E}).strict(),QOe=g.object({methodId:g.string().min(1).max(200),methodKind:VU,generation:E,authorizationDigest:Ar,appId:E.nullable(),accountId:g.string().max(2e3).nullable(),accountVerified:g.boolean(),scopes:g.array(g.string().max(1e3)).max(200),scopesStatus:g.enum(["unknown","requested","reported"]),outputs:g.array(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:g.enum(["ready","reconnect"]),aws:AE.optional()}).strict();async function q5(t,e=_f(t)){let r=Zo(t.method).outputs,o=await me(F5(t,e));return QOe.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:o,appId:t.appId,accountId:j5(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...e.details})}var V5=g.object({methodName:pe,account:g.string().max(2e3)}).strict();function G5(t,e=_f(t)){return{methodName:t.method.name,account:e.accountName}}var eDe=g.object({action:g.literal("start"),flowId:E,name:pe,methodId:g.string().min(1),method:Fl,appId:E.nullable(),fields:e$.default({}),scopes:g.array(g.string().max(1e3)).max(200).default([]),redirectUri:g.url().optional(),aws:za.optional()}).strict().superRefine((t,e)=>{t.aws&&t.method.kind!=="aws"&&e.addIssue({code:"custom",message:"Choose one authentication configuration for this connection method."})}),Iy=g.discriminatedUnion("action",[eDe,g.object({action:g.literal("exchange"),flowId:E,parameters:g.string().max(16384)}).strict(),g.object({action:g.literal("commit"),flowId:E,authorizationDigest:Ar,approval:_y}).strict(),g.object({action:g.literal("refresh"),id:E}).strict(),g.object({action:g.literal("revoke"),id:E}).strict()]);var H5=Rs.extend({name:pe}),b_t=g.object({bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Rs,token:g.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),B5=g.object({id:E,executorId:E,ownerId:E,name:pe,origin:g.url(),bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:g.object({port:g.number().int().min(1024).max(65535)}).strict().optional(),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),x_t=Rs.extend({previousSignature:Nn.optional()}).strict(),E_t=g.object({name:pe,content:So,labels:V5.optional(),version:g.number().int().positive().optional()}).strict(),yL=g.object({content:So,version:g.number().int().positive()}).strict(),K5=g.object({id:E,reason:g.enum(["grantExpired"])}).strict(),tDe=g.record(E,g.object({version:g.number().int().positive(),content:So}).strict()),Z5=g.object({functionId:E,contents:tDe}).strict(),W5=g.object({definition:ql,registration:WE,sources:g.array(So).max(100)}).strict(),$_t=g.object({id:E,name:pe,version:g.number().int().positive(),content:So,policy:Di}).strict(),J5=g.object({registration:WE,stoppedAt:g.iso.datetime().nullable(),heartbeatAt:g.iso.datetime().nullable()}).strict(),X5=g.object({lease:E,request:Fc,sources:g.array(So).max(100)}).strict().nullable(),rDe=g.object({lease:E}).strict(),R_t=rDe.extend({receipt:xy}).strict(),Ay=g.object({id:E,resource_id:E,executor_id:E,expected_revision:g.number().int().positive(),state:g.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:g.string().regex(/^\d+$/),result:So.nullable()}),I_t=g.object({id:E,resourceId:E,expectedRevision:g.number().int().positive()}).strict(),nDe=g.object({fence:g.string().regex(/^\d+$/)}).strict(),A_t=nDe.extend({content:So}).strict(),P_t=g.object({id:E,runId:E,stateDigest:Ar,expiresAt:nt}).strict(),t$=g.object({id:E,runId:E,context:g.string(),sealed:vo.nullable(),expiresAt:nt,receivedAt:nt.nullable()}).strict(),Y5=(t,e)=>"oauth-callback:"+t+":"+e;var Ga=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},oDe=class extends Ga{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},iDe=class extends Ga{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},sDe=class extends Ga{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},aDe=class extends Ga{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},cDe=class extends Ga{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},uDe=class extends Ga{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},lDe=class extends Ga{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},n$=class extends Ga{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},vL=class extends n${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},dDe=class extends n${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},pDe=class extends n${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},Q5=class extends n${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},fDe=class extends Ga{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},mDe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},hDe=class extends mDe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},gDe=["","+",".","/",";","?","&","#"],s8={"":{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}},yDe=new TextEncoder,e8="0123456789ABCDEF",t8=t=>Bc(mn(48,57),mn(65,70),mn(97,102))(t.charCodeAt(0)),Ty=(t,e)=>t[e]==="%"&&e+2<t.length&&t8(t[e+1])&&t8(t[e+2]);function wL(t,e){let r=t[e];return r==null?0:Bc(a8,c8,Wl("_"))(r)?1:Ty(t,e)?3:0}function vDe(t,e){if(Ty(t,e))return 3;let{char:r,size:o}=Cy(t,e);return _De(r)?o:0}function Cy(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var xL=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Ty(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Cy(e,o);r+=Bc(u8,s=>t&&wDe(s))(n)?n:l8(n),o+=i}return r};function bf(t){let e="";for(let r=0;r<t.length;){if(Ty(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Cy(t,r);e+=u8(o)?o:l8(o),r+=n}return e}function Py(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Ty(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Cy(t,n);r+=i,n+=s}return r}var a8=t=>Bc(mn(65,90),mn(97,122))(t.charCodeAt(0)),c8=t=>mn(48,57)(t.charCodeAt(0)),u8=t=>Bc(a8,c8,e=>"-._~".includes(e))(t),wDe=t=>":/?#[]@!$&'()*+,;=".includes(t),_De=t=>SDe(t.codePointAt(0)),SDe=t=>t!=null&&Bc(Wl(33),mn(35,36),Wl(38),mn(40,59),Wl(61),mn(63,91),Wl(93),Wl(95),mn(97,122),Wl(126),bDe,xDe)(t);function bDe(t){if(t<65536)return Bc(mn(160,55295),mn(63744,64975),mn(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var xDe=t=>Bc(mn(57344,63743),mn(983040,1048573),mn(1048576,1114109))(t),l8=t=>Array.from(yDe.encode(t)).map(e=>`%${e8[e>>4]}${e8[e&15]}`).join(""),mn=(t,e)=>r=>t<=r&&r<=e,Wl=t=>e=>t===e,Bc=(...t)=>e=>t.some(r=>r(e));function d8(t,e,r){return t.map(o=>o.kind==="literal"?o.text:EDe(o.vars,o.operator,e,r)).join("")}function EDe(t,e,r,o){let n=s8[e],i=t.flatMap(s=>$De(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function $De(t,e,r,o){if(e==null)return[];if(ODe(e)){let n=PDe(e,r.allowReserved);return n.length<1?[]:r8(t,"list",o)?IDe(t,n,r):[]}if(CDe(e)){let n=kDe(e,r.allowReserved);return n.length<1?[]:r8(t,"associative",o)?ADe(t,n,r):[]}return RDe(t,e,r)}function RDe(t,e,r){let o=String(e),n=t.prefix==null?o:Py(o,t.prefix),i=xL(r.allowReserved)(n);return r.named?[ky(bf(t.name),i,r)]:[i]}function IDe(t,e,r){let o=bf(t.name);if(t.explode)return r.named?e.map(i=>ky(o,i,r)):[...e];let n=e.join(",");return r.named?[ky(o,n,r)]:[n]}function ADe(t,e,r){if(t.explode)return e.map(([n,i])=>ky(n,i,r));let o=e.flat(1).join(",");return r.named?[ky(bf(t.name),o,r)]:[o]}var ky=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,PDe=(t,e)=>t.filter(r=>r!=null).map(String).map(xL(e)),kDe=(t,e)=>Object.entries(t).map(([r,o])=>[r,TDe(o)]).filter(([,r])=>r!=null).map(r=>r.map(xL(e)));function TDe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var CDe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ODe=t=>Array.isArray(t);function r8(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new hDe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function DDe(t,e,r){return _L(t,e,r,0,0,{})}function _L(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=aNe(i);return d8(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?_L(t,e,r,o+1,n+s.text.length,i):null;for(let a of NDe(t,e,o,n)){let c=e.slice(n,a);for(let u of MDe(s.vars,s.operator,c)){let l=EL(i,u);if(l==null)continue;let d=_L(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*NDe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*zDe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*zDe(t,e){for(let r=t;r>=e;r--)yield r}function*MDe(t,e,r){if(r===""){yield*UDe(t,e);return}let o=s8[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?KDe(t,o,n):LDe(t,o,n)}var UDe=(t,e)=>(e===""||e==="+")&&t.length===1?[Hc(t[0],"")]:[{}],LDe=(t,e,r)=>SL(t,e,$L(r,e.sep),0,0);function*SL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of jDe(i,e,r,n))for(let a of SL(t,e,r,o+1,s.index)){let c=EL(s.bindings,a);c!=null&&(yield c)}yield*SL(t,e,r,o+1,n)}function*jDe(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of FDe(t,e,s))yield{bindings:a,index:o+i}}}function*FDe(t,e,r){let o=p8(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*qDe(t,e,r)),yield*o}function*qDe(t,e,r){let o=f8(r,e.allowReserved);if(o==null)return;let n=VDe(r,e);n!=null&&(yield Hc(t,n)),yield Hc(t,o)}var VDe=(t,e)=>GDe(t.join(e.sep),e);function GDe(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=HDe(t,i,e.sep),a=Va(t.slice(o,n),e.allowReserved),c=Va(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function HDe(t,e,r){for(let o=e;o<t.length;o++)if(BDe(t,o,r))return o;return t.length}var BDe=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*p8(t,e,r){let o=Va(r,e.allowReserved);if(o==null)return;let n=Hc(t,o);if(t.prefix!=null){yield n;return}let i=$L(r,",");if(i.length<2){yield n;return}let s=f8(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?rNe(i,e.allowReserved):null;a!=null&&(yield Hc(t,a)),yield Hc(t,s),yield n}var KDe=(t,e,r)=>bL(t,e,$L(r,e.sep).map(tNe),0,0);function*bL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of ZDe(i,e,r,n,t))for(let a of bL(t,e,r,o+1,s.index)){let c=EL(s.bindings,a);c!=null&&(yield c)}yield*bL(t,e,r,o+1,n)}function*ZDe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*JDe(t,e,r,o,n);return}yield*WDe(t,e,r,o)}}function*WDe(t,e,r,o){let n=r[o];if(n.name===bf(t.name))for(let i of p8(t,e,n.value))yield{bindings:i,index:o+1}}function*JDe(t,e,r,o,n){yield*XDe(t,e,r,o),yield*QDe(t,e,r,o,n)}function*XDe(t,e,r,o){let n=[...YDe(bf(t.name),e,r,o)];n.length>0&&(yield{bindings:Hc(t,n),index:o+n.length})}function*YDe(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Va(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*QDe(t,e,r,o,n){let i=[...eNe(e,r,o,new Set(n.map(s=>bf(s.name))))];i.length>0&&(yield{bindings:Hc(t,Object.fromEntries(i)),index:o+i.length})}function*eNe(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=Va(i.name,t.allowReserved),a=Va(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function tNe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function rNe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Va(t[o],e),i=Va(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function f8(t,e){let r=[];for(let o of t){let n=Va(o,e);if(n==null)return null;r.push(n)}return r}function Va(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var Hc=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function EL(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=nNe(i,n);if(s==null)return null;r[o]=s}return r}var nNe=(t,e)=>r$(t)||r$(e)?oNe(t,e):iNe(t.value,e.value)?t:null;function oNe(t,e){let r=n8(t.value),o=n8(e.value);if(r==null||o==null)return null;let n=r$(t),i=r$(e);if(!n&&!i)return null;if(n&&!i)return Py(o,t.prefix)===r?e:null;if(!n&&i)return Py(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Py(o,s)===r?e:null:Py(r,a)===o?t:null}var r$=t=>t.prefix!=null,n8=t=>typeof t=="string"?t:null;function iNe(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):o8(t)?o8(e)&&sNe(Object.entries(t),Object.entries(e)):t===e}var sNe=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),o8=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),aNe=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),$L=(t,e)=>e===""?[t]:t.split(e),cNe=["=",",","!","@","|"];function uNe(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new cDe(e,r));let n=t[0];if(fNe(n))return o(new uDe(e,r+1,n));if(!i8(n)&&wL(t,0)<1)return o(new lDe(e,r+1,n));let i=i8(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:lNe(t,e,r+1,s)}}function lNe(t,e,r,o){if(o>=t.length)throw new vL(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new Q5(e,r+i):new vL(e,r+i);let s=i,a=dNe(t,i);if(a===s)throw new vL(e,r+i);let c=t.slice(s,a);i=a;let u=pNe(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new fDe(e,r+i,t[i]):new dDe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new Q5(e,r+i-1)}return n}function dNe(t,e){let r=e,o=!0;for(;r<t.length;){let n=wL(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||wL(t,r+1)<1)break;r++,o=!0}return r}function pNe(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&mNe(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new pDe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function i8(t){return gDe.includes(t)&&t!==""}function fNe(t){return cNe.includes(t)}function mNe(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function hNe(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new oDe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new sDe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(uNe(f,t,i))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new iDe(t,i)),n(s),i++;continue}let a=vDe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Cy(t,i);r(new aDe(t,i,c)),n(c),i+=u}return o}var o$=class m8{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=_Ne(r),this.#e=gNe(hNe(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new m8(e,r)}get tokens(){return this.#e}expand=e=>d8(this.#e,e,this.#t);match=e=>DDe(this.#e,e,this.#t);toString=()=>this.uriTemplate},gNe=t=>Object.freeze(t.map(yNe)),yNe=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(vNe))}),vNe=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),wNe=()=>{},_Ne=({strict:t,report:e})=>(e??=wNe,t??=!0,e=t?SNe(e):e,{strict:t,report:e}),SNe=t=>e=>{throw t(e),e};function bNe(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.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[o.name]=n}return r}function xf(t,e){let r=bNe(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Ua.parse({...l,stdin:JSON.stringify(r)})}}let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(f=>f.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,f)=>{if(!t.parameters.some(p=>p.name===f))throw new Error("Declare every function parameter.");return Object.hasOwn(r,f)?n(r[f]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,f])=>[d,i(f,l)])):u},s=new o$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Ma.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.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}}function h8(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var Jl=class extends Error{constructor(r,o){super(o);this.code=r}code},RL=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},i$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||D(r)!==D(e))throw new Jl("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Rs);return await YU(r),{...r,fingerprint:await Vl(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new Jl("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},J5);if(await Kl(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},wo(H5));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await YU(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/resources/"+E.parse(e)+"/custody",{},yL);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await Oi(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=oL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&Di.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&D(o.policy)!==D(i.policy)||o.materialRevision===i.materialRevision&&await me(o)!==i.digest)throw new Jl("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!S5(i.policy,o))throw new Jl("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return KE((await this.read(e)).content,this.binding,this.keys.encryption)}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>D(c)===D(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)&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...qE(r)],origins:[],functionDigests:[],callerProgram:r!==ht.clientCredential,expiresAt:s});return Di.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&D(o)===D({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await HE(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},pn);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await HE(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},g.union([pn,pf]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},wo(K5))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},pn),a=await KE(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ht.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async prepareFunction(e,r,o=!1){let n=await this.environment(e.environmentId);if(n.manifest.functionVersion!==1)throw new Jl("function_runtime_required","Update this environment to Foundation CLI 5 or create a new environment.");if(!n.manifest.capabilities.includes(le.function)||!n.manifest.capabilities.includes(le[e.program.kind]))throw new Error("Choose an environment that can execute this function.");let i=await this.sourceContents(h8(e).map(u=>u.id)),s=new Set(i.map(u=>u.policy.id));if(o){let u=await this.api.json("/api/functions/"+r+"/authorizations",{},wo(yL));for(let l of u.items)s.has(l.content.policy.id)||(await this.observe(l.content),i.push(l.content))}let a={},c={id:r,digest:await me(e)};for(let u of i){let l=await this.read(u.policy.id);if(!l.content.policy.authorities.some(m=>D(m)===D(this.binding)))throw new Error("An authority of each input must approve its use by this function.");let d=tL(u.policy.contentType),f=Di.parse({...l.content.policy,revision:l.content.policy.revision+1,grants:[...l.content.policy.grants.filter(m=>!("function"in m)||m.function.id!==r),...s.has(u.policy.id)?[{function:c,executor:n.manifest.executor,operations:d,expiresAt:new Date(Date.now()+30*864e5).toISOString()}]:[]]}),p=await KE(l.content,this.binding,this.keys.encryption);a[u.policy.id]={version:l.version,content:await HE(p,f,l.content.materialRevision+1,this.binding,this.keys,l.content.metadata,l.content)}}return Z5.parse({functionId:r,contents:a})}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},wo(pn));s=d.items.find(f=>f.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ht.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await BE(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=Is.parse(o),s=i.kind==="function"?await this.api.json("/api/functions/"+i.functionId+"/invocation",{},W5):null;if(s&&(await me(s.definition)!==await me(i.kind==="function"?i.definition:null)||s.definition.environmentId!==r))throw new Error("Run the current function in its approved environment.");let a=s?await Kl(s.registration):await this.environment(r);await this.trusted(a.manifest.executor);let c=n.id??crypto.randomUUID(),u=n.expiresAt??new Date(Date.now()+36e5).toISOString(),l=i.kind==="function"?xf(i.definition,i.arguments):i,d=l.kind==="http"?l.request:null;if(i.kind==="http"||i.kind==="function"){let w=n.save??{},S=Object.fromEntries(await Promise.all(Object.entries(w).map(async([b,x])=>[b,await this.output(e,x,c,a,u)])));i.kind==="http"?i.save=S:i.outputs=S}let f=l.kind==="command"?l.inputs.map(w=>w.source.id):d?d.bindings.flatMap(w=>w.parts.flatMap(S=>typeof S=="string"?[]:[S.id])):[],p=s?s.sources:await this.sourceContents([...f,...n.sourceIds??[]]);if(s)for(let w of p)await this.observe(w);if(i.kind==="function"&&!n.expiresAt){let w=await me(i.definition),S=p.map(b=>Math.max(...b.policy.grants.filter(x=>"function"in x&&x.function.id===i.functionId&&x.function.digest===w&&D(x.executor)===D(a.manifest.executor)&&tL(b.policy.contentType).every(k=>x.operations.includes(k))).map(x=>Date.parse(x.expiresAt))));u=new Date(Math.min(Date.parse(u),...S)).toISOString()}let m={format:2,id:c,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:a.manifest.executor,environmentDigest:await me(a.manifest),operation:le[i.kind],operationDigest:await me(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:i.kind==="function"?await me(i.definition):null,...i.kind==="function"?{functionId:i.functionId}:{},sources:await Promise.all(p.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await me(w.policy),...w.policy.contentType===ht.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:[this.binding],createdAt:new Date().toISOString(),expiresAt:u};await JE(a,m);let y=w=>w.policy.contentType===ht.clientCredential;for(let w of p)await Bl(w,y(w)&&m.operation!==le.connect&&m.operation!==le.revoke?{...m,operation:le.refresh}:m,y(w)?{}:{destination:d?.url});return E5(m,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/executions",{method:"POST",body:e},zn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new RL(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(D(r.intent.actor)!==D(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");return this.submitPrepared(r)}async result(e){if(D(e.intent.actor)!==D(this.binding)||e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another requester.");let r=await XU(e.requestSignature,this.binding.signing,"run");if(D(r.intent)!==D(e.intent))throw new Error("The result belongs to a different signed request.");return await this.trusted(e.intent.executor),e.receipt?P5(e.receipt,e.intent,this.binding.id,this.keys):null}};import{lstat as xNe,mkdir as ENe,readFile as $Ne,readdir as RNe}from"node:fs/promises";import{join as g8}from"node:path";var y8=g.string().regex(/^(run|process|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Xl=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return D({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:y8.parse(e)})}async read(e){let r=this.context(e),o=g8(this.directory,e+".json");try{let n=await xNe(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=g.string().max(32e6).parse(JSON.parse(await $Ne(o,"utf8"))),s=await cy(i,await Bo(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(La(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await eo({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async write(e,r){let o=this.context(e),n={context:o,value:r},i=await fn(n,this.privateKeys.signing,"journal"),s=mt(D({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new uf(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Bo(this.binding.encryption,"ECDH-ES+A256KW"));await ENe(this.directory,{recursive:!0,mode:448}),await wf(g8(this.directory,e+".json"),D(a),!0)}async keys(e){let r;try{r=await RNe(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>y8.parse(o.name.slice(0,-5)))}};var s$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await jc(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await me(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&D(r)!==D(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var Ot=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function L(t,e,r,o){throw new Ot(t,e,r,o)}var a$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new Ot(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},X5)}renew(e,r){return this.api.json("/api/executions/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}dispatch(e,r){return this.api.json("/api/executions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/executions/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},zn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},g.object({id:E}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},t$),capture:(r,o,n)=>this.capture(r,o,n),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Ay),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Ay),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},So),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},Ay),state:r=>e.json("/api/connections/"+r+"/operation",{},Ay.nullable())}}};import{randomBytes as gde,randomUUID as E3e}from"node:crypto";var v8=g.object({operation:Is,save:g.record(g.string(),pe)}).strict();function c$(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t.kind==="function"?{kind:t.kind,functionId:t.functionId,definition:t.definition,arguments:t.arguments}:t}async function w8(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.connect"){let n=FE.parse(r.invocation.input),i=er.parse(e.kind==="connect"?e.input:null);if(e.kind!=="connect"||i.flowId!==r.continuationId||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Use the reviewed connection and execution environment.");if(i.action==="start"&&(i.methodId!==n.methodId||i.name!==n.name||i.appId!==(n.appId??null)||await me(i.method)!==n.methodDigest))throw new Error("Use the reviewed connection method and application.");if(!["start","exchange","commit"].includes(String(i.action)))throw new Error("Continue the reviewed connection.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=vy.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await me(c$(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="function"&&o.operation.kind==="function"){if(e.functionId!==o.operation.functionId||await me(e.definition)!==o.operation.definitionDigest||D(e.arguments)!==D(o.operation.arguments))throw new Error("Run the reviewed function and arguments.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(D(e.request)!==D(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(D(e)!==D(Is.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&D(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==D(o.save))throw new Error("Use the reviewed output destinations.");if(e.kind==="function"&&D(Object.fromEntries(Object.entries(e.outputs).map(([n,i])=>[n,i.name])))!==D(o.save))throw new Error("Use the reviewed function output destinations.")}function Oy(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function bo(t,e){for(let r of Oy(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function IL(t,e,r){let o=Oy(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function Ef(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function Kc(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}import{lookup as INe}from"node:dns/promises";import{isIP as b8}from"node:net";import{request as ANe}from"node:https";import{brotliDecompressSync as PNe,gunzipSync as kNe,inflateSync as TNe}from"node:zlib";var l$=jt(S8(),1),CNe=l$.default.IPv6.parseCIDR("2000::/3"),ONe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function x8(t){if(!b8(t)||t.includes("%"))return!1;let e=l$.default.parse(t);return ONe.has(e.range())&&(!(e instanceof l$.default.IPv6)||e.match(CNe))}function Yl(t,e){let r;try{r=new URL(t)}catch{L(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&L(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||b8(o)&&!x8(o))&&L(400,"private_destination","Choose a public HTTPS destination."),r}var d$=class{constructor(e){this.origin=e}origin;async send(e){let r=Yl(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&L(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&L(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await INe(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!x8(u.address)))&&L(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(p,m,y)=>{m.all?y(null,[a]):y(null,a.address,a.family)}},f=ANe(r,d,p=>{let m=[],y=0;p.on("data",w=>{y+=w.length,y>n?p.destroy(new Ot(413,"body_limit","The response body is too large.")):m.push(w)}),p.on("error",l),p.on("end",()=>{try{let w=Buffer.concat(m),S=p.headers["content-encoding"];if(S&&S!=="identity"){let x=S==="gzip"?kNe:S==="deflate"?TNe:S==="br"?PNe:null;if(!x)throw new Ot(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let b={};for(let[x,k]of Object.entries(p.headers))k!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(b[x]=Array.isArray(k)?k.join(", "):k);u({status:p.statusCode??502,headers:b,body:new Uint8Array(w)})}catch(w){l(w)}})});f.on("error",l),f.end(e.body)})}catch(s){if(s instanceof Ot)throw s;e.signal?.aborted&&L(409,"cancelled","The operation was cancelled."),L(502,"service_unavailable","The service could not be reached. Try again.")}}};function $f(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{L(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&L(502,"invalid_response","The service returned an invalid response."),e}function Ps(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function p$(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!c5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=mt(Ef(bo(JSON.parse(Ps(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Ps(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}function DNe(t,e){return t.policy.contentType===ht.value?e.output===void 0:t.policy.contentType===ht.tokenSet&&e.output!==void 0}var ks=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},f$=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await vf(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await vf(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await me(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let f=await vf(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:f,delivered:!1}),await this.broker.finish(r.lease,f),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(f=>{f.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let f=await $5(r.request,this.binding,this.keys);await JE(this.environment,f.intent);let p=Is.parse(f.operation);if(le[p.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await w8(o,p),await this.preflight(p,o,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.execute(p,o,r.sources,c);d=await vf(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(f){if(f instanceof ks)throw f;f instanceof by&&(f=new Ot(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let p=l&&(c.aborted||!(f instanceof Ot)||["service_unavailable","connection_uncertain","lease_lost"].includes(f.code));d=await vf(o,p?"uncertain":"failed",{ok:!1,result:null,error:f instanceof Ot?{code:f.code,message:f.message}:{code:p?"execution_uncertain":"invalid_execution",message:p?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?xf(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async preflight(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await Oi(c);let u=r.sources.find(f=>f.id===c.policy.id);if(!u||!await iL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await me(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(le[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(Yl(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=Oy(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");IL(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(Oy(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await yf(u.approval);if(D(l.policy.authorities.find(d=>d.id===l.authorityId))!==D(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==ht.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&D(d.executor)===D(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?xf(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!DNe(u,c))throw new Error("Use the input named in the signed request.");await Bl(u,r,{...n?{destination:n.url}:{}}),await qc(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async execute(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?xf(e.definition,e.arguments):e,a=[],c=new Map,u=async m=>{let y=o.find(S=>S.policy.id===m.id);if(y.policy.contentType===ht.value)return qc(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(m.id)||c.set(m.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(m.id);if(!m.output||!Object.hasOwn(w,m.output))throw new Error("Choose an available connection output.");return mt(w[m.output])};if(s.kind==="command"){let m=await p$(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:m.environment,files:m.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new Ot(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new Ot(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new Ot(422,"function_failed",Kc(y.stderr,m.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,Kc(y.stdout,m.sensitive))}return{...y,stdout:Kc(y.stdout,m.sensitive),stderr:Kc(y.stderr,m.sensitive)}}let l=structuredClone(i);for(let m of l.bindings){let y="";for(let w of m.parts)if(typeof w=="string")y+=w;else{let S=Ps(await u(w));a.push(S,Buffer.from(S).toString("base64"),Buffer.from(S).toString("base64url")),y+=S}IL(l,m.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let f=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(f.status>=400)throw new Ot(502,"service_response","The service returned an unsuccessful response.");return this.functionResult(e,r,Kc(Ps(f.body),a))}let p=e.kind==="http"?e.save:{};if(Object.keys(p).length){if(f.status>=400)throw new Ot(502,"service_response","The service returned an unsuccessful response.");let m={};for(let[y,w]of Object.entries(p)){let S=f.body;if(y!==""){let x=bo(JSON.parse(Ps(S)),y);if(x===void 0)throw new Ot(400,"invalid_pointer","The response value was not found.");S=mt(typeof x=="string"?x:JSON.stringify(x))}let b=await Sy(S,w.approval,r.id,this.binding,this.keys,{bytes:S.length});m[w.name]=(await this.broker.capture(w.name,b)).id}return{status:f.status,saved:m}}return{status:f.status,headers:Object.fromEntries(Object.entries(f.headers).map(([m,y])=>[m,Kc(y,a)])),body:Kc(Ps(f.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:ln.parse(JSON.parse(o))}catch{throw new Ot(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:bo(n,s);if(c===void 0)throw new Ot(400,"invalid_pointer","The function result value was not found.");let u=mt(typeof c=="string"?c:JSON.stringify(c)),l=await Sy(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};var oc=jt(Hq(),1);import{randomUUID as QVe}from"node:crypto";function ale(t){let e=RE.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&L(502,"invalid_response","The AWS account could not be verified."),e.data}function cle(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&lf(t.arn)===lf(e.arn)}function Bq(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&L(409,"reconnect_required","Reconnect with current AWS credentials.")}var DP=class{async obtain(e,r,o){let n=za.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};Bq(s?.expiration);let a=new oc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();Bq(d.expiration),c=new oc.STSClient({region:n.region,credentials:d});let f=ale(await c.send(new oc.GetCallerIdentityCommand({}),{abortSignal:u}));r&&!cle(f,r.sourceIdentity)&&L(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,m=f;if(n.role){l=!0;let S=(await c.send(new oc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+QVe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!S?.AccessKeyId||!S.SecretAccessKey||!S.SessionToken||!S.Expiration)&&L(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:S.AccessKeyId,secretAccessKey:S.SecretAccessKey,sessionToken:S.SessionToken,expiration:S.Expiration},Bq(p.expiration),c.destroy(),c=new oc.STSClient({region:n.region,credentials:p}),m=ale(await c.send(new oc.GetCallerIdentityCommand({}),{abortSignal:u}));let b=n.role.arn.split(":");(m.accountId!==b[4]||m.arn.split(":")[1]!==b[1]||m.arn.split(":")[5]?.split("/").slice(0,2).join("/")!=="assumed-role/"+n.role.arn.split("/").at(-1))&&L(502,"account_changed","The requested AWS role could not be verified.")}return r&&!cle(m,r.identity)&&L(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:IE.parse({...n,sourceIdentity:f,identity:m}),credentials:{AWS_ACCESS_KEY_ID:p.accessKeyId,AWS_SECRET_ACCESS_KEY:p.secretAccessKey,AWS_SESSION_TOKEN:p.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof Ot)throw d;o?.aborted&&L(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&L(409,"reconnect_required","Reconnect with current AWS credentials."),l&&L(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),L(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};import{randomUUID as eGe}from"node:crypto";var NP=class{constructor(e){this.aws=e}aws;facts=mL;validate(e){e.aws||L(400,"aws_authentication_required","Choose AWS authentication for this executor.")}async start({input:e,signal:r}){let o=(await this.aws.obtain(e.aws,void 0,r)).state;return{kind:"ready",material:zi.parse({format:2,methodId:e.methodId,method:e.method,generation:eGe(),appId:null,appGeneration:null,aws:o})}}needsRenewal(){return!1}async check(e,r){await this.outputs(e,null,r)}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};import{randomUUID as b3e}from"node:crypto";var Kq;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Kq="oauth4webapi/v3.8.8");function qw(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var ga="ERR_INVALID_ARG_VALUE",ya="ERR_INVALID_ARG_TYPE";function yr(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var rV=Symbol(),tGe=Symbol(),rGe=Symbol(),nV=Symbol();var Uw=Symbol();var nGe=new TextEncoder,oGe=new TextDecoder;function Zq(t){return typeof t=="string"?nGe.encode(t):oGe.decode(t)}var Wq;Uint8Array.prototype.toBase64?Wq=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):Wq=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var Jq;Uint8Array.fromBase64?Jq=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw yr("The input to be decoded is not correctly encoded.",ga,e)}}:Jq=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw yr("The input to be decoded is not correctly encoded.",ga,e)}};function Xq(t){return typeof t=="string"?Jq(t):Wq(t)}var Zm=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=CGe,Error.captureStackTrace?.(this,this.constructor)}},Lw=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function $e(t,e,r){return new Lw(t,{code:e,cause:r})}function iGe(t){return t.toLowerCase().replace(/^application\//,"")}function jw(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function oV(t){qw(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Kq&&!e.has("user-agent")&&e.set("user-agent",Kq),e.has("authorization"))throw yr('"options.headers" must not include the "authorization" header name',ga);return e}function sGe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw yr('"options.signal" must return or be an instance of AbortSignal',ya);return e}}function zP(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw yr(`${r} must be a number`,ya,n);if(t>0)return;if(e){if(t!==0)throw yr(`${r} must be a non-negative number`,ga,n);return}throw yr(`${r} must be a positive number`,ga,n)}catch(i){throw o?$e(i.message,o,n):i}}function tn(t,e,r,o){try{if(typeof t!="string")throw yr(`${e} must be a string`,ya,o);if(t.length===0)throw yr(`${e} must not be empty`,ga,o)}catch(n){throw r?$e(n.message,r,o):n}}function dle(t){cGe(t,"application/json")}function aGe(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return $e(r,DGe,t)}function cGe(t,e){if(yle(t)!==e)throw aGe(t,e)}async function ple(t){return tn(t,"codeVerifier"),Xq(await crypto.subtle.digest("SHA-256",Zq(t)))}function iV(t){let e=t?.[tGe];return typeof e=="number"&&Number.isFinite(e)?e:0}function sV(t){let e=t?.[rGe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function fle(){return Math.floor(Date.now()/1e3)}function ju(t){if(typeof t!="object"||t===null)throw yr('"as" must be an object',ya);tn(t.issuer,'"as.issuer"')}function Fu(t){if(typeof t!="object"||t===null)throw yr('"client" must be an object',ya);tn(t.client_id,'"client.client_id"')}function ule(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function mle(t){return tn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function hle(t){return tn(t,'"clientSecret"'),(e,r,o,n)=>{let i=ule(r.client_id),s=ule(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function gle(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var uGe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function lGe(t,e){if(e&&t.protocol!=="https:")throw $e("only requests to HTTPS are allowed",zGe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw $e("only HTTP and HTTPS requests are allowed",MGe,t)}function lle(t,e,r,o){let n;if(typeof t!="string"||!(n=uGe(t)))throw $e(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?UGe:LGe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return lGe(n,o),n}function aV(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?lle(t.mtls_endpoint_aliases[e],e,r,o):lle(t[e],e,r,o)}var Yq=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=TGe,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)}},Fw=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=OGe,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)}},Qq=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=kGe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},MP="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",dGe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",pGe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',fGe="("+MP+")\\s*=\\s*"+pGe,mGe="("+MP+")\\s*=\\s*("+MP+")",hGe=new RegExp("^[,\\s]*("+MP+")"),gGe=new RegExp("^[,\\s]*"+fGe+"[,\\s]*(.*)"),yGe=new RegExp("^[,\\s]*"+mGe+"[,\\s]*(.*)"),vGe=new RegExp("^("+dGe+")(?:$|[,\\s])(.*)");function wGe(t){if(!qw(t,Response))throw yr('"response" must be an instance of Response',ya);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(hGe),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let f,p;if(n=o.match(gGe)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(yGe)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(vGe)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function _Ge(t){if(t.status>399&&t.status<500){jP(t),dle(t);try{let e=await t.clone().json();if(jw(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function cV(t,e,r){if(t.status!==e){bGe(t);let o;throw(o=await _Ge(t))?(await t.body?.cancel(),new Yq("server responded with an error in the response body",{cause:o,response:t})):$e(`"response" is not a conform ${r} response (unexpected HTTP status code)`,NGe,t)}}function SGe(t){if(!dV.has(t))throw yr('"options.DPoP" is not a valid DPoPHandle',ga)}function yle(t){return t.headers.get("content-type")?.split(";")[0]}async function uV(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[nV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:sGe(o,s?.signal)})}async function lV(t,e,r,o,n,i){let s=aV(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[rV]!==!0);n.set("grant_type",o);let a=oV(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(SGe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await uV(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function vle(t,e,r,o,n){ju(t),Fu(e),tn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),lV(t,e,r,"refresh_token",i,n)}var wle=new WeakMap,_le=new WeakMap;function Sle(t){if(!t.id_token)return;let e=wle.get(t);if(!e)throw yr('"ref" was already garbage collected or did not resolve from the proper sources',ga);return e}async function FP(t,e,r,o,n,i){if(ju(t),Fu(e),!qw(r,Response))throw yr('"response" must be an instance of Response',ya);await cV(r,200,"Token Endpoint"),jP(r);let s=await Fle(r);if(tn(s.access_token,'"response" body "access_token" property',wt,{body:s}),tn(s.token_type,'"response" body "token_type" property',wt,{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;zP(a,!0,'"response" body "expires_in" property',wt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&tn(s.refresh_token,'"response" body "refresh_token" property',wt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw $e('"response" body "scope" property must be a string',wt,{body:s});if(s.id_token!==void 0){tn(s.id_token,'"response" body "id_token" property',wt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(zP(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await $Ge(t,e,s.id_token,a,n);IGe(e,c),RGe(c),_le.set(r,u),wle.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new Zm("unsupported `token_type` value",{cause:{body:s}});return s}function bGe(t){let e;if(e=wGe(t))throw new Qq("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function ble(t,e,r,o){return FP(t,e,r,void 0,o?.[Uw],o?.recognizedTokenTypes)}function xle(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw $e('unexpected JWT "aud" (audience) claim value',Wm,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw $e('unexpected JWT "aud" (audience) claim value',Wm,{expected:t,claims:e.claims,claim:"aud"});return e}function Ele(t,e){let r=t[VGe]?.(e)??t.issuer;if(e.claims.iss!==r)throw $e('unexpected JWT "iss" (issuer) claim value',Wm,{expected:r,claims:e.claims,claim:"iss"});return e}var dV=new WeakSet;function xGe(t){return dV.add(t),t}var pV=Symbol();async function $le(t,e,r,o,n,i,s){if(ju(t),Fu(e),!dV.has(o))throw yr('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',ga);tn(n,'"redirectUri"');let a=Od(o,"code");if(!a)throw $e('no authorization code in "callbackParameters"',wt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==pV&&(tn(i,'"codeVerifier"'),c.set("code_verifier",i)),lV(t,e,r,"authorization_code",c,s)}var Rle={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 Ile(t,e){for(let r of t)if(e.claims[r]===void 0)throw $e(`JWT "${r}" (${Rle[r]}) claim missing`,wt,{claims:e.claims});return e}function EGe(t,e){if(typeof e.claims[t]!="string")throw $e(`unexpected JWT "${t}" (${Rle[t]}) claim type`,wt,{claims:e.claims});return e}function $Ge(t,e,r,o,n){return Ule(r,Lle.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),iV(e),sV(e),n).then(Ile.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(Ele.bind(void 0,t)).then(xle.bind(void 0,e.client_id)).then(EGe.bind(void 0,"sub"))}function Ale(t,e){if(e===LP)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?LP:(zP(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function RGe(t){t.auth_time!==void 0&&zP(t.auth_time,!0,'ID Token "auth_time" (authentication time)',wt,{claims:t})}function Ple(t,e,r){if(r===LP)return;let o=fle()+iV(t),n=sV(t);if(e.auth_time+r<o-n)throw $e("too much time has elapsed since the last End-User authentication",tV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function kle(t,e){let r=e===UP?void 0:e;if(t.nonce!==r)throw $e('unexpected ID Token "nonce" claim value',Wm,{expected:r,claims:t,claim:"nonce"})}function IGe(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw $e('ID Token "aud" (audience) claim includes additional untrusted audiences',Wm,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw $e('unexpected ID Token "azp" (authorized party) claim value',Wm,{expected:t.client_id,claims:e,claim:"azp"})}}var UP=Symbol(),LP=Symbol();async function Tle(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?AGe(t,e,r,o.expectedNonce,o.maxAge,o[Uw],o.recognizedTokenTypes):PGe(t,e,r,o?.maxAge,o?.[Uw],o?.recognizedTokenTypes)}async function AGe(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=UP;break;case UP:break;default:tn(o,'"expectedNonce" argument'),a.push("nonce")}n=Ale(e,n),n!==LP&&a.push("auth_time");let c=await FP(t,e,r,a,i,s);tn(c.id_token,'"response" body "id_token" property',wt,{body:c});let u=Sle(c);return Ple(e,u,n),kle(u,o),c}async function PGe(t,e,r,o,n,i){let s=await FP(t,e,r,void 0,n,i),a=Sle(s);return a&&(Ple(e,a,Ale(e,o)),kle(a,UP)),s}var kGe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",TGe="OAUTH_RESPONSE_BODY_ERROR",CGe="OAUTH_UNSUPPORTED_OPERATION",OGe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var eV="OAUTH_PARSE_ERROR",wt="OAUTH_INVALID_RESPONSE";var DGe="OAUTH_RESPONSE_IS_NOT_JSON",NGe="OAUTH_RESPONSE_IS_NOT_CONFORM",zGe="OAUTH_HTTP_REQUEST_FORBIDDEN",MGe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",tV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Wm="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var UGe="OAUTH_MISSING_SERVER_METADATA",LGe="OAUTH_INVALID_SERVER_METADATA";function jGe(t,e){if(typeof e.header.typ!="string"||iGe(e.header.typ)!==t)throw $e('unexpected JWT "typ" header parameter value',wt,{header:e.header});return e}async function Cle(t,e,r,o,n){return ju(t),Fu(e),lV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Ole(t,e,r,o){return FP(t,e,r,void 0,o?.[Uw],o?.recognizedTokenTypes)}async function Dle(t,e,r,o,n){ju(t),Fu(e),tn(o,'"token"');let i=aV(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[rV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=oV(n?.headers);return a.delete("accept"),uV(t,e,r,i,s,a,n)}async function Nle(t){if(!qw(t,Response))throw yr('"response" must be an instance of Response',ya);await cV(t,200,"Revocation Endpoint")}function jP(t){if(t.bodyUsed)throw yr('"response" body has been used already',ga)}async function zle(t,e,r,o,n){ju(t),Fu(e),tn(o,'"token"');let i=aV(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[rV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=oV(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),uV(t,e,r,i,s,a,n)}async function Mle(t,e,r,o){if(ju(t),Fu(e),!qw(r,Response))throw yr('"response" must be an instance of Response',ya);await cV(r,200,"Introspection Endpoint");let n;if(yle(r)==="application/token-introspection+jwt"){jP(r);let{claims:i,jwt:s}=await Ule(await r.text(),Lle.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),iV(e),sV(e),o?.[Uw]).then(jGe.bind(void 0,"token-introspection+jwt")).then(Ile.bind(void 0,["aud","iat","iss"])).then(Ele.bind(void 0,t)).then(xle.bind(void 0,e.client_id));if(_le.set(r,s),!jw(i.token_introspection))throw $e('JWT "token_introspection" claim must be a JSON object',wt,{claims:i});n=i.token_introspection}else jP(r),n=await Fle(r);if(typeof n.active!="boolean")throw $e('"response" body "active" property must be a boolean',wt,{body:n});return n}async function Ule(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new Zm("JWE decryption is not configured",{cause:t});if(a!==3)throw $e("Invalid JWT",wt,t);let c;try{c=JSON.parse(Zq(Xq(i)))}catch(d){throw $e("failed to parse JWT Header body as base64url encoded JSON",eV,d)}if(!jw(c))throw $e("JWT Header must be a top level object",wt,t);if(e(c),c.crit!==void 0)throw new Zm('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Zq(Xq(s)))}catch(d){throw $e("failed to parse JWT Payload body as base64url encoded JSON",eV,d)}if(!jw(u))throw $e("JWT Payload must be a top level object",wt,t);let l=fle()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw $e('unexpected JWT "exp" (expiration time) claim type',wt,{claims:u});if(u.exp<=l-o)throw $e('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',tV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw $e('unexpected JWT "iat" (issued at) claim type',wt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw $e('unexpected JWT "iss" (issuer) claim type',wt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw $e('unexpected JWT "nbf" (not before) claim type',wt,{claims:u});if(u.nbf>l+o)throw $e('unexpected JWT "nbf" (not before) claim value',tV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw $e('unexpected JWT "aud" (audience) claim type',wt,{claims:u});return{header:c,claims:u,jwt:t}}function Lle(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw $e('unexpected JWT "alg" header parameter',wt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw $e('unexpected JWT "alg" header parameter',wt,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw $e('unexpected JWT "alg" header parameter',wt,{header:o,expected:r,reason:"default value"});return}throw $e('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Od(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw $e(`"${e}" parameter must be provided only once`,wt);return r}var FGe=Symbol(),qGe=Symbol();function jle(t,e,r,o){if(ju(t),Fu(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw yr('"parameters" must be an instance of URLSearchParams, or URL',ya);if(Od(r,"response"))throw $e('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',wt,{parameters:r});let n=Od(r,"iss"),i=Od(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw $e('response parameter "iss" (issuer) missing',wt,{parameters:r});if(n&&n!==t.issuer)throw $e('unexpected "iss" (issuer) response parameter value',wt,{expected:t.issuer,parameters:r});switch(o){case void 0:case qGe:if(i!==void 0)throw $e('unexpected "state" response parameter encountered',wt,{expected:void 0,parameters:r});break;case FGe:break;default:if(tn(o,'"expectedState" argument'),i!==o)throw $e(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',wt,{expected:o,parameters:r})}if(Od(r,"error"))throw new Fw("authorization response from the server is an error",{cause:r});let a=Od(r,"id_token"),c=Od(r,"token");if(a!==void 0||c!==void 0)throw new Zm("implicit and hybrid flows are not supported");return xGe(new URLSearchParams(r))}async function Fle(t,e=dle){let r;try{r=await t.json()}catch(o){throw e(t),$e('failed to parse "response" body as JSON',eV,o)}if(!jw(r))throw $e('"response" body must be a top level object',wt,{body:r});return r}var VGe=Symbol();import{createHash as GGe}from"node:crypto";function qu(t,e){try{return Yl(new o$(t).expand(e)).href}catch{L(400,"invalid_service_url","Check the service URL and its required fields.")}}var qP=t=>GGe("sha256").update(t).digest("hex"),Vw=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],VP=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&L(502,"invalid_response","The service returned an invalid expiry."),e};var Vle=Object.assign(Object.create(null),{dpop:()=>L(502,"invalid_response","The service returned an unsupported token.")}),HGe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Vle,{"user access token":()=>{}}),refreshInspection:!0,async inspect(t){let{app:e,current:r}=t,{server:o,client:n}=t.configuration(),i=await zle({...o,introspection_endpoint:o.token_endpoint+"/introspect"},n,t.authentication("basic"),r.accessToken,{...t.options(),additionalParameters:{token_type_hint:"access_token"}}),s;try{s=await Mle(o,n,Response.json(await t.json(i),{status:i.status}))}catch{L(409,"reconnect_required","Reconnect this service to renew access.")}return(s.active!==!0||s.client_id!==e.clientId||typeof s.sub!="string"||!s.sub||typeof s.exp!="number"||s.exp*1e3<=Date.now())&&L(409,"reconnect_required","Reconnect this service to renew access."),{...r,account:s.sub,accountName:typeof s.username=="string"?s.username:s.sub,scopes:Vw(s.scope),scopesStatus:"reported",accountVerified:!0,expiresAt:Math.min(r.expiresAt??1/0,s.exp*1e3)}}},BGe={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&L(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key",allowAccountChange:!0,refreshInspection:!0,async inspect({transport:t,current:e}){let r=await t.send({url:"https://openrouter.ai/api/v1/key",headers:{authorization:"Bearer "+e.accessToken}}),o=$f(r);(r.status!==200||!o.data||typeof o.data!="object")&&L(409,"reconnect_required","Reconnect this service to renew access.");let n=o.data;return{...e,account:qP(e.accessToken),accountName:typeof n.label=="string"?n.label:"OpenRouter",facts:n}}},KGe={verifyIdentity({current:t,response:e}){e.headers["x-oauth-scopes"]!==void 0&&(t.scopes=Vw(e.headers["x-oauth-scopes"].replaceAll(","," ")),t.scopesStatus="reported")}},ZGe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+Buffer.from(t.clientId+":"+(t.clientSecret??"")).toString("base64"),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},WGe={verifyIdentity({data:t}){t.email_verified!==!0&&L(502,"invalid_response","The service account could not be verified.")}},JGe=Object.assign(Object.create(null),{ebay:HGe,openrouter:BGe,github:KGe,google:WGe}),XGe=[{matches:t=>t.hostname.endsWith(".myshopify.com"),service(t,e){return{...e.pathname==="/admin/oauth/access_token"?{normalizeToken(r){r.token_type===void 0&&(r.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...t.grantType==="client_credentials"&&/^\/admin\/api\/[^/]+\/graphql\.json$/.test(e.pathname)?{identityRequest({spec:r,url:o,current:n}){return{url:o,method:r.identity.method,headers:{...r.identity.headers,"content-type":"application/json","X-Shopify-Access-Token":n.accessToken},body:JSON.stringify({query:"{ shop { id name myshopifyDomain } }"})}},verifyIdentity({app:r,data:o}){((Array.isArray(o.errors)?o.errors.length:o.errors)||bo(o,"/data/shop/myshopifyDomain")!==r.fields.shop+".myshopify.com")&&L(502,"invalid_response","The Shopify store could not be verified.")}}:{}}}},{matches:t=>t.hostname==="api.notion.com"&&t.pathname==="/v1/oauth/token",service:()=>({normalizeToken(t){t.refresh_token===null&&delete t.refresh_token}})}];function so(t,e){let r=e?new URL(e):void 0,o=r?XGe.find(i=>i.matches(r))?.service(t,r):void 0,n=t.adapter?JGe[t.adapter]:void 0;return t.adapter&&!n&&L(400,"invalid_input","Choose a supported service authentication adapter."),{recognizedTokenTypes:Vle,...o,...n,...t.revoke?.style==="github"?ZGe:{},...o?.verifyIdentity||n?.verifyIdentity?{verifyIdentity(i){o?.verifyIdentity?.(i),n?.verifyIdentity?.(i)}}:{}}}var GP=class{constructor(e){this.transport=e}transport;appValues(e,r){return{...e.defaults,...r.fields,clientId:r.clientId}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&L(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(qu(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:so(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await ple(n),c.code_challenge_method="S256"),so(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(qu(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:qu(e.tokenUrl,this.appValues(e,r))};return e.issuer&&Yl(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?gle():(e.clientSecret||L(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?hle(e.clientSecret):mle(e.clientSecret))}options(e="form"){return{[nV]:async(r,{body:o,headers:n,method:i,signal:s})=>{let a=await this.transport.send({url:r,method:i,headers:e==="json"?{...n,"content-type":"application/json"}:n,body:e==="json"?JSON.stringify(Object.fromEntries(o)):o.toString(),signal:s});return new Response([204,205,304].includes(a.status)?null:new Uint8Array(a.body),{status:a.status,headers:a.headers})}}}async json(e){return $f({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&bo(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&L(409,"reconnect_required","Reconnect this service to renew access."),r===429&&L(503,"service_rate_limit","The service is busy. Try again later."),L(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&L(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,so(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=VP(u.expires_in));try{let d=await(n?ble:e.grantType==="client_credentials"?Ole:Tle)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:so(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof Ot)throw l;L(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[so(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&L(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+VP(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&L(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?Vw(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+VP(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&L(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=so(e);if(l.exchange){let p=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>qu(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,p.status,$f(p))}else{let{server:p,client:m}=this.configuration(e,r),y;try{let w=jle(p,m,o.parameters,o.state);y=await $le(p,m,this.authentication(r,e.clientAuth),w,l.redirectUri?.(r,i)??i,e.pkce?n:pV,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(w){throw(w instanceof Lw||w instanceof Fw)&&L(400,"invalid_state","Start the connection again."),w}u=await this.tokenResponse(e,r,y)}let d=this.token(e,u,s,a);await c?.(d,u);let f=await this.inspect(e,r,d,u);return a&&f.account!==a.account&&!l.allowAccountChange&&L(409,"account_changed","Reconnect using the same service account."),f}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&L(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=so(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Cle(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e.tokenFormat)),d=await this.tokenResponse(e,r,l),f={...this.token(e,d,o,n,!!n),requestedScopes:o};await i?.(f,d);let p=await this.inspect(e,r,f,d);return n&&p.account!==n.account&&L(409,"account_changed","Reconnect using the same service account."),p}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||L(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&L(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await vle(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return(e.identity?.url||so(e).refreshInspection)&&(i=await this.inspect(e,r,i)),i.account!==o.account&&L(409,"account_changed","Reconnect using the same service account."),i}async inspect(e,r,o,n){let i=n??{},s=so(e);if(s.inspect)return s.inspect({spec:e,app:r,transport:this.transport,current:o,configuration:()=>this.configuration(e,r),authentication:l=>this.authentication(r,l),options:()=>this.options(),json:l=>this.json(l)});if(e.identity?.url){let l=qu(e.identity.url,{...this.appValues(e,r),...o.extra,accessToken:o.accessToken,refreshToken:o.refreshToken??""}),d=so(e,l),f=await this.transport.send(d.identityRequest?.({spec:e,app:r,transport:this.transport,url:l,current:o})??{url:l,method:e.identity.method,headers:{...e.identity.headers,authorization:"Bearer "+o.accessToken}});i=$f(f),(f.status===401||f.status===403)&&L(409,"reconnect_required","Reconnect this service to renew access."),f.status>=400&&L(502,"invalid_response","The service account could not be verified."),d.verifyIdentity?.({spec:e,app:r,transport:this.transport,current:o,response:f,data:i})}else e.identity?.from==="app"&&(i=this.appValues(e,r));let a=l=>{for(let d of Array.isArray(l)?l:[l]){let f=bo(i,d);if(typeof f=="string"&&f||typeof f=="number")return String(f)}return""},c=e.identity?.id,u=c?Array.isArray(c)?c.map(l=>a(l)).filter(Boolean).join(":"):a(c):o.account||r.fields.domain||r.fields.shop||qP(o.accessToken);return(!u||u.length>1e3)&&L(502,"invalid_response","The service account could not be verified."),{...o,account:u,accountName:e.identity&&a(e.identity.name)||u,accountVerified:!!(e.identity?.url||e.identity?.from==="token"&&n)}}async revoke(e,r,o){e.revoke||L(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=qu(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await Dle({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Nle(d)}catch{L(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+Buffer.from(r.clientId+":"+(r.clientSecret??"")).toString("base64")),(await this.transport.send(so(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&L(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,Ef(bo(n,s))]))}};var pde=jt(dde(),1);function Hw(t,e,r={}){let o={...r,...e};for(let n of t)n.required!==!1&&!o[n.name]&&L(400,"missing_field","Complete the required service fields."),o[n.name]?.includes("\0")&&L(400,"invalid_field","Check the service fields."),n.pattern&&(n.pattern.length>200||!(0,pde.default)(n.pattern))&&L(400,"invalid_pattern","Use a simple field validation pattern."),n.pattern&&o[n.name]&&!new RegExp(n.pattern,"u").test(o[n.name].slice(0,1e3))&&L(400,"invalid_field","Check the service fields.");return Object.keys(e).some(n=>!t.some(i=>i.name===n))&&L(400,"invalid_field","Remove unrecognized service fields."),o}function Gu(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function Nd(t){return t||L(409,"app_required","Choose an OAuth application."),t}function SV(t){let e=Gu(t).scopes;return QE(e,t.scopes)}function fde(t,e,r){return zi.parse({format:2,methodId:t.methodId,method:t.method,generation:b3e(),appId:t.appId,appGeneration:t.appId?e.generation:null,oauth:r})}function mde(t){return{token:gL.parse(t.token),response:er.parse(t.response)}}var ek=class{constructor(e){this.transport=e}transport;facts=pL;oauth(e){return new GP({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}validate(e,r){let o=Gu(e),n=Nd(r);so(o),Hw(o.fields,n.fields,o.defaults),Zo(e.method).requiresApp&&o.clientAuth!=="none"&&!n.clientSecret&&L(409,"app_required","Add a client secret to this OAuth application.")}async start(e){let{input:r,signal:o}=e,n=Gu(r),i=Nd(e.app);if(n.grantType!=="client_credentials")return{kind:"authorize",url:await this.oauth(o).authorize(n,i,e.state,e.verifier,r.redirectUri,SV(r))};await e.dispatch();let s=await this.oauth(o).clientCredentials(n,i,SV(r),void 0,(a,c)=>e.receive({token:a,response:c}));return{kind:"ready",material:fde(r,i,s)}}async exchange(e,r,o){let{input:n,signal:i}=e,s=Gu(n),a=Nd(e.app),c=new URLSearchParams(r);(c.getAll("state").length!==1||c.get("state")!==e.state)&&L(400,"invalid_state","Start the connection again.");let u;if(o){let l=mde(o);u=await this.oauth(i).inspect(s,a,l.token,l.response)}else await e.dispatch(),u=await this.oauth(i).exchange(s,a,{parameters:c,state:e.state},e.verifier,n.redirectUri,SV(n),void 0,(l,d)=>e.receive({token:l,response:d}));return fde(n,a,u)}needsRenewal(e){return e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=await this.oauth(e.signal).refresh(Gu(e.material),Nd(e.app),e.material.oauth,(o,n)=>e.receive({token:o,response:n}));return zi.parse({...e.material,oauth:r})}async recover(e,r,o){let n=mde(o),i=await this.oauth().inspect(Gu(e),Nd(r),n.token,n.response);return zi.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(Gu(e),Nd(r),e.oauth)}async revoke(e,r,o){await this.oauth(o).revoke(Gu(e),Nd(r),e.oauth)}};import{randomUUID as x3e}from"node:crypto";function bV(t){if(t.method.kind!=="token")throw new Error("Use a token connection provider.");return t.method.config}var tk=class{facts=fL;validate(e){Hw(bV(e).fields,e.fields)}async start({input:e}){return{kind:"ready",material:zi.parse({format:2,methodId:e.methodId,method:e.method,generation:x3e(),appId:null,appGeneration:null,fields:Hw(bV(e).fields,e.fields)})}}needsRenewal(){return!1}async outputs(e){return Object.fromEntries(Object.entries(bV(e).outputs).map(([r,o])=>[r,Ef(bo(e.fields,o))]))}};function hde(t,e){return{oauth:new ek(t),token:new tk,aws:new NP(e)}}var Ym=class{constructor(e,r,o,n,i,s=new DP){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=hde(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers[Zo(e).family]}metadata(e){return q5(e,this.provider(e.method).facts(e))}labels(e){return G5(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||L(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=zi.safeParse(JSON.parse(Ps(await qc(e,r,this.keys,{destination:o}))));n.success||L(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&L(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==le.revoke&&L(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,ht.clientCredential,n),s=Zl.parse(JSON.parse(Ps(await qc(i,o,this.keys))));return s.methodId!==r&&L(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(Zo(e.method).application==="none")return null;if(!As(e.method))return Zl.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===le.revoke?le.revoke:le.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&L(409,"app_changed","Reconnect this service with the current application."),i}async flow(e,r){let o=await this.readFlow(e);return(!o||o.expiresAt<=Date.now()||D(o.actor)!==D(r.actor)||o.ownerId!==r.ownerId)&&L(409,"connection_expired","Start the connection again."),o}async readFlow(e){let r=await this.journal.read("connect_"+e);return r&&(!Iy.safeParse(r.input).success||r.material&&!zi.safeParse(r.material).success)&&L(409,"connection_expired","Start the connection again."),r}writeFlow(e,r){return this.journal.write("connect_"+e,r)}async startApp(e,r,o){return Zo(e.method).application==="none"?null:e.appId?this.app(e.appId,e.methodId,r,o):Zl.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}})}authorization(e,r,o){return{input:r.input,app:r.app,state:r.state,verifier:r.verifier,signal:o,dispatch:async()=>{r.phase="exchanging",await this.writeFlow(e,r)},receive:async n=>{r.checkpoint=n,r.phase="received",await this.writeFlow(e,r)}}}async validate(e,r,o){let n=Iy.parse(e),i=le[n.action==="refresh"||n.action==="revoke"?n.action:"connect"];if(r.operation!==i&&L(400,"wrong_operation","Use the approved connection operation."),n.action==="start"){if(As(n.method)&&!n.appId&&L(400,"app_required","Choose an OAuth application."),Zo(n.method).browserAuthorization){n.redirectUri||L(400,"invalid_redirect","Choose a callback URL.");let s=new URL(n.redirectUri);(s.username||s.password||s.hash||s.search||!(n.redirectUri===r.origin+"/oauth/callback"||s.protocol==="http:"&&["127.0.0.1","[::1]"].includes(s.hostname)))&&L(400,"invalid_redirect","Use the Foundation callback or a callback on this computer.")}this.provider(n.method).validate(n,await this.startApp(n,r,o))}else if(n.action==="commit"){let s=await this.flow(n.flowId,r),a=await yf(n.approval);(!s.material||n.authorizationDigest!==(await this.metadata(s.material)).authorizationDigest||a.policy.contentType!==ht.tokenSet||a.policy.ownerId!==r.ownerId||a.policy.origin!==r.origin||D(a.policy.authorities.find(c=>c.id===a.authorityId))!==D(r.actor)||!a.policy.producers.some(c=>c.runId===r.id&&D(c.executor)===D(this.binding)&&Date.parse(c.expiresAt)>Date.now()))&&L(403,"approval_required","Review the connection and approve its recipients before saving.")}else if(n.action==="exchange"){let s=await this.flow(n.flowId,r);if(s.app&&s.input.appId){let a=await this.app(s.input.appId,s.input.methodId,r,o);D(a)!==D(s.app)&&L(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,ht.tokenSet,o),a=await this.material(s,r);await this.connectionApp(a,r,o)}}async execute(e,r,o,n){let i=Iy.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&L(409,"connection_busy","Another operation is updating this connection."),this.active.add(s);try{if(n.throwIfAborted(),i.action==="start")return await this.start(i,r,o,n);if(i.action==="exchange")return await this.exchange(i,r,n);if(i.action==="commit")return await this.commit(i,r);let a=this.source(i.id,ht.tokenSet,o),c=await this.material(a,r);if(i.action==="refresh"){await this.provider(c.method).check?.(c,n);let l=await this.refresh(a,c,r,o,n);return{kind:"refreshed",id:a.policy.id,...await this.metadata(l)}}let u=this.provider(c.method);return u.revoke||L(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await u.revoke(c,await this.connectionApp(c,r,o),n),{kind:"revoked",id:a.policy.id}}finally{this.active.delete(s)}}async review(e,r){return{kind:"review",flowId:e,name:r.input.name,metadata:{...await this.metadata(r.material),...this.labels(r.material)}}}async start(e,r,o,n){await this.readFlow(e.flowId)&&L(409,"flow_exists","Use a new connection request.");let i={actor:r.actor,ownerId:r.ownerId,input:e,app:await this.startApp(e,r,o),state:gde(32).toString("base64url"),verifier:gde(32).toString("base64url"),expiresAt:Math.min(Date.now()+6e5,Date.parse(r.expiresAt)),phase:"authorize"};await this.writeFlow(e.flowId,i);let s=await this.provider(e.method).start(this.authorization(e.flowId,i,n));return s.kind==="ready"?(i.material=s.material,i.phase="review",await this.writeFlow(e.flowId,i),this.review(e.flowId,i)):(e.redirectUri===r.origin+"/oauth/callback"&&await this.broker.relay?.({id:e.flowId,runId:r.id,stateDigest:await me(i.state),expiresAt:new Date(i.expiresAt).toISOString()}),{kind:"authorize",flowId:e.flowId,url:s.url})}async exchange(e,r,o){let n=await this.flow(e.flowId,r);if(n.phase==="review")return this.review(e.flowId,n);let i=this.provider(n.input.method);return(!i.exchange||!["authorize","received"].includes(n.phase))&&L(409,"connection_uncertain","Check the connection before authorizing it again."),n.material=await i.exchange(this.authorization(e.flowId,n,o),e.parameters,n.phase==="received"?n.checkpoint:void 0),n.phase="review",await this.writeFlow(e.flowId,n),this.review(e.flowId,n)}async commit(e,r){let o=await this.flow(e.flowId,r);if(o.phase==="committed")return{kind:"connected",id:o.content.policy.id};["review","committing"].includes(o.phase)||L(409,"approval_required","Review this connection before saving."),o.content?(D(o.content.policy)!==D(e.approval.policy)||o.content.creationRunId!==r.id)&&L(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await Sy(mt(D(o.material)),e.approval,r.id,this.binding,this.keys,await this.metadata(o.material)),o.phase="committing",await this.writeFlow(e.flowId,o));let n;try{n=await this.broker.capture(o.input.name,o.content,this.labels(o.material))}catch(i){throw i instanceof Ot&&i.status<500?i:new ks}return o.phase="committed",await this.writeFlow(e.flowId,o),{kind:"connected",id:n.id}}async recover(e,r){let o=Iy.parse(e);if(o.action!=="commit")return null;let n=await this.readFlow(o.flowId);if(!n?.content||n.ownerId!==r.ownerId||D(n.actor)!==D(r.actor)||n.content.creationRunId!==r.id||D(n.content.policy)!==D(o.approval.policy)||!["committing","committed"].includes(n.phase))return null;try{await this.broker.capture(n.input.name,n.content,this.labels(n.material))}catch(i){if(i instanceof Ot&&i.status<500)return null;throw new ks}return n.phase="committed",await this.writeFlow(o.flowId,n),{kind:"connected",id:n.content.policy.id}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&L(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&L(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await x5(e.previous,mt(D(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||L(409,"reconnect_required","Reconnect this service to renew access.");try{await Bl(e,{...o,operation:le.refresh},{destination:s})}catch{L(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=E3e(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let f=await a.renew({material:r,app:c,signal:i,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,f)}catch(f){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),f instanceof Ot&&["connection_review","reconnect_required","account_changed"].includes(f.code))throw f;L(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};function zo(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=xV($3e(qa()),"custody",r.id),i=new Xl(xV(n,"client"),o,r,e),s=new i$(t,o,r,e,new s$(i)),a=new a$(t),c=new d$(o),u=new Ym(r,e,a.connections(),new Xl(xV(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function yde(t,e){let{custody:r,keys:o,binding:n,connections:i}=zo(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await me(n),operation:le.command,functionDigest:null,operationDigest:await me(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await me(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===ht.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return p$(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ht.value)return qc(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return mt(d[u.output])})}import{mkdir as dnt}from"node:fs/promises";import{join as L_}from"node:path";import{setTimeout as pnt}from"node:timers/promises";import{spawn as R3e}from"node:child_process";import{constants as EV}from"node:fs";import{open as vde,rm as I3e}from"node:fs/promises";async function wde(t){if(process.platform!=="linux"){let r=await vde(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await I3e(t,{force:!0})}}let e=await vde(t,EV.O_CREAT|EV.O_WRONLY|EV.O_NOFOLLOW,384);try{let r=R3e("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var WO=jt(Hq(),1),JO=jt(Qxe(),1);function e0e(t){return sL.safeParse(t).success?t:null}async function t0e(t=3e3){let e=new WO.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new WO.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=e0e(n.Arn);if(i)return i;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 JO.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new JO.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=e0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var vG=g.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),wG=vG.max(4096).startsWith("/"),r0e=g.object({command:g.array(vG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:wG.optional(),environment:g.record(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),vG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:g.string().max(1e6).default(""),timeoutSeconds:g.number().int().min(1).max(3600).default(60)}).strict(),TBt=r0e.extend({id:E.optional()}),n0e=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),o0e=g.object({exitCode:g.number().int().nullable(),signal:g.string().max(32).nullable(),stdout:g.string().max(1e6),stderr:g.string().max(1e6),timedOut:g.boolean(),truncated:g.boolean()}).strict(),CBt=g.object({state:n0e.exclude(["queued","running"]),result:o0e.nullable(),error:g.string().max(100).nullable()}).strict(),XO=r0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:wG,state:n0e,result:o0e.nullable(),error:g.string().nullable(),createdAt:nt,startedAt:nt.nullable(),finishedAt:nt.nullable()}).strict(),OBt=XO.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),DBt=g.object({workingDirectory:wG}).strict(),i0e=g.object({lease:E,process:XO}).strict().nullable();var YO=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},i0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},XO)}},QO=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new ks}return!0}};import{spawn as tnt,execFile as rnt}from"node:child_process";import{chmod as nnt,lstat as s0e,mkdir as _G,readFile as a0e,readdir as ont,realpath as c0e,rename as int,rm as snt,symlink as ant,writeFile as u0e}from"node:fs/promises";import{join as Qu}from"node:path";import{promisify as cnt}from"node:util";import{createConnection as unt}from"node:net";import{setTimeout as lnt}from"node:timers/promises";var SG=cnt(rnt),U_=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',eD=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1024||e.port>65535)throw new Error("Use an allocated SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=Qu(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await _G(this.options.directory,{recursive:!0,mode:448}),await _G(this.sessions,{recursive:!0,mode:448}),await _G(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await s0e(this.options.workspaceLink),await c0e(this.options.workspaceLink)!==await c0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await ant(this.options.workspace,this.options.workspaceLink)}let e=Qu(this.options.directory,"host_ed25519");try{await s0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await SG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:Ni(),timeout:1e4})}await nnt(e,384),this.hostKey=ny.parse((await SG("ssh-keygen",["-y","-f",e],{env:Ni(),timeout:1e4})).stdout);let r=Qu(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+U_(e),"PidFile "+U_(Qu(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+U_(Qu(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+U_("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+U_("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
|
|
130
|
+
`),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await D5(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",p,...f.flatMap(([m,y])=>["--env",m+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(f=>{let p=O5(d[0],d.slice(1),{env:Ni(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),m={stdout:new z5("utf8"),stderr:new z5("utf8")},y=0,w=!1,S=(T,U)=>{let X=Math.max(0,1e6-y);U.length>X&&(c.truncated=!0);let ue=U.subarray(0,X);y+=ue.length,c[T]+=m[T].write(ue)};p.stdout.on("data",T=>S("stdout",T)),p.stderr.on("data",T=>S("stderr",T)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let b=()=>{u=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,b()},e.timeoutSeconds*1e3);x.unref();let k=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",b),c.stdout+=m.stdout.end(),c.stderr+=m.stderr.end(),f())};r.addEventListener("abort",b,{once:!0}),r.aborted&&b(),p.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",k()}),p.once("close",(T,U)=>{c.exitCode=T,c.signal=U,k()})}),c}finally{s&&u&&await new Promise(l=>{let d=O5("docker",["rm","-f",i],{env:Ni(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await FOe(o,{recursive:!0,force:!0})}}};function JOe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var YE=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new WOe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function U5(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await HOe(M5(ZOe(),"foundation-"));await GOe(r,448);try{let o=Ni(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=M5(r,i);await KOe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=VOe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=JOe(n),u=new YE(c,m=>process.stdout.write(m)),l=new YE(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},f=()=>d("SIGINT"),p=()=>d("SIGTERM");process.on("SIGINT",f),process.on("SIGTERM",p),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,y)=>{process.off("SIGINT",f),process.off("SIGTERM",p),u.end(),l.end(),i(m??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await BOe(r,{recursive:!0,force:!0})}}import{dirname as $3e,join as xV}from"node:path";function Zo(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function QE(t,e){return[...new Set([...t.required??[],...e??t.default])]}function As(t){return Zo(t).requiresApp}var XOe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),L5=er.refine(t=>Object.keys(t).every(e=>!XOe.has(e)),"Keep method-specific facts separate from common facts."),dL=g.object({accountId:g.string().max(2e3).nullable(),accountName:g.string().max(2e3),accountVerified:g.boolean(),scopes:g.array(g.string().max(1e3)).max(200),scopesStatus:g.enum(["unknown","requested","reported"]),authorization:L5,details:L5}).strict();function pL(t){if(t.method.kind!=="oauth"||!t.oauth)throw new Error("Use OAuth connection material.");return dL.parse({accountId:t.oauth.account,accountName:t.oauth.accountName,accountVerified:t.oauth.accountVerified??!1,scopes:t.oauth.scopes,scopesStatus:t.oauth.scopesStatus??"unknown",authorization:{},details:{}})}function fL(t){if(t.method.kind!=="token"||!t.fields)throw new Error("Use token connection material.");return dL.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function mL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return dL.parse({accountId:lf(t.aws.identity.arn),accountName:t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1),accountVerified:!0,scopes:[],scopesStatus:"unknown",authorization:{aws:JW(t.aws)},details:{aws:XW(t.aws)}})}var YOe={oauth:pL,token:fL,aws:mL};function _f(t){return YOe[t.method.kind](t)}function j5(t,e=_f(t)){return e.accountVerified?e.accountId:null}function F5(t,e=_f(t)){return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...e.authorization,...t.state?{state:t.state}:{}}}var e$=g.record(g.string().max(100),g.string().max(16384)),Zl=g.object({format:g.literal(1),methodId:g.string().min(1),generation:E,clientId:g.string().max(1e3),clientSecret:g.string().max(16384).optional(),fields:e$}).strict(),gL=g.object({accessToken:g.string().min(1).max(16384),refreshToken:g.string().min(1).max(16384).optional(),expiresAt:g.number().nullable(),refreshExpiresAt:g.number().optional(),scopes:g.array(g.string()),requestedScopes:g.array(g.string()).optional(),account:g.string(),accountName:g.string(),accountVerified:g.boolean().optional(),scopesStatus:g.enum(["unknown","requested","reported"]).optional(),extra:e$,facts:er}).strict(),hL={format:g.literal(2),methodId:g.string().min(1),method:Fl,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:g.literal("reconnect").optional()},Sf=g.never().optional(),zi=g.union([g.object({...hL,method:CE,oauth:gL,fields:Sf,aws:Sf}).strict(),g.object({...hL,method:OE,fields:e$,oauth:Sf,aws:Sf}).strict(),g.object({...hL,method:DE,aws:IE,oauth:Sf,fields:Sf}).strict()]).superRefine((t,e)=>{t.method.kind==="oauth"&&As(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the OAuth application required by this connection."}),t.method.kind!=="oauth"&&t.appId!==null&&e.addIssue({code:"custom",message:"Only OAuth connections use an application."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),f_t=g.object({methodId:g.string().min(1).max(200),clientId:g.string().max(1e3),generation:E}).strict(),QOe=g.object({methodId:g.string().min(1).max(200),methodKind:VU,generation:E,authorizationDigest:Ar,appId:E.nullable(),accountId:g.string().max(2e3).nullable(),accountVerified:g.boolean(),scopes:g.array(g.string().max(1e3)).max(200),scopesStatus:g.enum(["unknown","requested","reported"]),outputs:g.array(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:g.enum(["ready","reconnect"]),aws:AE.optional()}).strict();async function q5(t,e=_f(t)){let r=Zo(t.method).outputs,o=await me(F5(t,e));return QOe.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:o,appId:t.appId,accountId:j5(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...e.details})}var V5=g.object({methodName:pe,account:g.string().max(2e3)}).strict();function G5(t,e=_f(t)){return{methodName:t.method.name,account:e.accountName}}var eDe=g.object({action:g.literal("start"),flowId:E,name:pe,methodId:g.string().min(1),method:Fl,appId:E.nullable(),fields:e$.default({}),scopes:g.array(g.string().max(1e3)).max(200).default([]),redirectUri:g.url().optional(),aws:za.optional()}).strict().superRefine((t,e)=>{t.aws&&t.method.kind!=="aws"&&e.addIssue({code:"custom",message:"Choose one authentication configuration for this connection method."})}),Iy=g.discriminatedUnion("action",[eDe,g.object({action:g.literal("exchange"),flowId:E,parameters:g.string().max(16384)}).strict(),g.object({action:g.literal("commit"),flowId:E,authorizationDigest:Ar,approval:_y}).strict(),g.object({action:g.literal("refresh"),id:E}).strict(),g.object({action:g.literal("revoke"),id:E}).strict()]);var H5=Rs.extend({name:pe}),b_t=g.object({bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Rs,token:g.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),B5=g.object({id:E,executorId:E,ownerId:E,name:pe,origin:g.url(),bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:g.object({port:g.number().int().min(1).max(65535)}).strict().optional(),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),x_t=Rs.extend({previousSignature:Nn.optional()}).strict(),E_t=g.object({name:pe,content:So,labels:V5.optional(),version:g.number().int().positive().optional()}).strict(),yL=g.object({content:So,version:g.number().int().positive()}).strict(),K5=g.object({id:E,reason:g.enum(["grantExpired"])}).strict(),tDe=g.record(E,g.object({version:g.number().int().positive(),content:So}).strict()),Z5=g.object({functionId:E,contents:tDe}).strict(),W5=g.object({definition:ql,registration:WE,sources:g.array(So).max(100)}).strict(),$_t=g.object({id:E,name:pe,version:g.number().int().positive(),content:So,policy:Di}).strict(),J5=g.object({registration:WE,stoppedAt:g.iso.datetime().nullable(),heartbeatAt:g.iso.datetime().nullable()}).strict(),X5=g.object({lease:E,request:Fc,sources:g.array(So).max(100)}).strict().nullable(),rDe=g.object({lease:E}).strict(),R_t=rDe.extend({receipt:xy}).strict(),Ay=g.object({id:E,resource_id:E,executor_id:E,expected_revision:g.number().int().positive(),state:g.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:g.string().regex(/^\d+$/),result:So.nullable()}),I_t=g.object({id:E,resourceId:E,expectedRevision:g.number().int().positive()}).strict(),nDe=g.object({fence:g.string().regex(/^\d+$/)}).strict(),A_t=nDe.extend({content:So}).strict(),P_t=g.object({id:E,runId:E,stateDigest:Ar,expiresAt:nt}).strict(),t$=g.object({id:E,runId:E,context:g.string(),sealed:vo.nullable(),expiresAt:nt,receivedAt:nt.nullable()}).strict(),Y5=(t,e)=>"oauth-callback:"+t+":"+e;var Ga=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},oDe=class extends Ga{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},iDe=class extends Ga{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},sDe=class extends Ga{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},aDe=class extends Ga{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},cDe=class extends Ga{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},uDe=class extends Ga{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},lDe=class extends Ga{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},n$=class extends Ga{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},vL=class extends n${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},dDe=class extends n${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},pDe=class extends n${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},Q5=class extends n${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},fDe=class extends Ga{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},mDe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},hDe=class extends mDe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},gDe=["","+",".","/",";","?","&","#"],s8={"":{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}},yDe=new TextEncoder,e8="0123456789ABCDEF",t8=t=>Bc(mn(48,57),mn(65,70),mn(97,102))(t.charCodeAt(0)),Ty=(t,e)=>t[e]==="%"&&e+2<t.length&&t8(t[e+1])&&t8(t[e+2]);function wL(t,e){let r=t[e];return r==null?0:Bc(a8,c8,Wl("_"))(r)?1:Ty(t,e)?3:0}function vDe(t,e){if(Ty(t,e))return 3;let{char:r,size:o}=Cy(t,e);return _De(r)?o:0}function Cy(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var xL=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Ty(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Cy(e,o);r+=Bc(u8,s=>t&&wDe(s))(n)?n:l8(n),o+=i}return r};function bf(t){let e="";for(let r=0;r<t.length;){if(Ty(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Cy(t,r);e+=u8(o)?o:l8(o),r+=n}return e}function Py(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Ty(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Cy(t,n);r+=i,n+=s}return r}var a8=t=>Bc(mn(65,90),mn(97,122))(t.charCodeAt(0)),c8=t=>mn(48,57)(t.charCodeAt(0)),u8=t=>Bc(a8,c8,e=>"-._~".includes(e))(t),wDe=t=>":/?#[]@!$&'()*+,;=".includes(t),_De=t=>SDe(t.codePointAt(0)),SDe=t=>t!=null&&Bc(Wl(33),mn(35,36),Wl(38),mn(40,59),Wl(61),mn(63,91),Wl(93),Wl(95),mn(97,122),Wl(126),bDe,xDe)(t);function bDe(t){if(t<65536)return Bc(mn(160,55295),mn(63744,64975),mn(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var xDe=t=>Bc(mn(57344,63743),mn(983040,1048573),mn(1048576,1114109))(t),l8=t=>Array.from(yDe.encode(t)).map(e=>`%${e8[e>>4]}${e8[e&15]}`).join(""),mn=(t,e)=>r=>t<=r&&r<=e,Wl=t=>e=>t===e,Bc=(...t)=>e=>t.some(r=>r(e));function d8(t,e,r){return t.map(o=>o.kind==="literal"?o.text:EDe(o.vars,o.operator,e,r)).join("")}function EDe(t,e,r,o){let n=s8[e],i=t.flatMap(s=>$De(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function $De(t,e,r,o){if(e==null)return[];if(ODe(e)){let n=PDe(e,r.allowReserved);return n.length<1?[]:r8(t,"list",o)?IDe(t,n,r):[]}if(CDe(e)){let n=kDe(e,r.allowReserved);return n.length<1?[]:r8(t,"associative",o)?ADe(t,n,r):[]}return RDe(t,e,r)}function RDe(t,e,r){let o=String(e),n=t.prefix==null?o:Py(o,t.prefix),i=xL(r.allowReserved)(n);return r.named?[ky(bf(t.name),i,r)]:[i]}function IDe(t,e,r){let o=bf(t.name);if(t.explode)return r.named?e.map(i=>ky(o,i,r)):[...e];let n=e.join(",");return r.named?[ky(o,n,r)]:[n]}function ADe(t,e,r){if(t.explode)return e.map(([n,i])=>ky(n,i,r));let o=e.flat(1).join(",");return r.named?[ky(bf(t.name),o,r)]:[o]}var ky=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,PDe=(t,e)=>t.filter(r=>r!=null).map(String).map(xL(e)),kDe=(t,e)=>Object.entries(t).map(([r,o])=>[r,TDe(o)]).filter(([,r])=>r!=null).map(r=>r.map(xL(e)));function TDe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var CDe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ODe=t=>Array.isArray(t);function r8(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new hDe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function DDe(t,e,r){return _L(t,e,r,0,0,{})}function _L(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=aNe(i);return d8(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?_L(t,e,r,o+1,n+s.text.length,i):null;for(let a of NDe(t,e,o,n)){let c=e.slice(n,a);for(let u of MDe(s.vars,s.operator,c)){let l=EL(i,u);if(l==null)continue;let d=_L(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*NDe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*zDe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*zDe(t,e){for(let r=t;r>=e;r--)yield r}function*MDe(t,e,r){if(r===""){yield*UDe(t,e);return}let o=s8[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?KDe(t,o,n):LDe(t,o,n)}var UDe=(t,e)=>(e===""||e==="+")&&t.length===1?[Hc(t[0],"")]:[{}],LDe=(t,e,r)=>SL(t,e,$L(r,e.sep),0,0);function*SL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of jDe(i,e,r,n))for(let a of SL(t,e,r,o+1,s.index)){let c=EL(s.bindings,a);c!=null&&(yield c)}yield*SL(t,e,r,o+1,n)}function*jDe(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of FDe(t,e,s))yield{bindings:a,index:o+i}}}function*FDe(t,e,r){let o=p8(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*qDe(t,e,r)),yield*o}function*qDe(t,e,r){let o=f8(r,e.allowReserved);if(o==null)return;let n=VDe(r,e);n!=null&&(yield Hc(t,n)),yield Hc(t,o)}var VDe=(t,e)=>GDe(t.join(e.sep),e);function GDe(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=HDe(t,i,e.sep),a=Va(t.slice(o,n),e.allowReserved),c=Va(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function HDe(t,e,r){for(let o=e;o<t.length;o++)if(BDe(t,o,r))return o;return t.length}var BDe=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*p8(t,e,r){let o=Va(r,e.allowReserved);if(o==null)return;let n=Hc(t,o);if(t.prefix!=null){yield n;return}let i=$L(r,",");if(i.length<2){yield n;return}let s=f8(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?rNe(i,e.allowReserved):null;a!=null&&(yield Hc(t,a)),yield Hc(t,s),yield n}var KDe=(t,e,r)=>bL(t,e,$L(r,e.sep).map(tNe),0,0);function*bL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of ZDe(i,e,r,n,t))for(let a of bL(t,e,r,o+1,s.index)){let c=EL(s.bindings,a);c!=null&&(yield c)}yield*bL(t,e,r,o+1,n)}function*ZDe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*JDe(t,e,r,o,n);return}yield*WDe(t,e,r,o)}}function*WDe(t,e,r,o){let n=r[o];if(n.name===bf(t.name))for(let i of p8(t,e,n.value))yield{bindings:i,index:o+1}}function*JDe(t,e,r,o,n){yield*XDe(t,e,r,o),yield*QDe(t,e,r,o,n)}function*XDe(t,e,r,o){let n=[...YDe(bf(t.name),e,r,o)];n.length>0&&(yield{bindings:Hc(t,n),index:o+n.length})}function*YDe(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Va(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*QDe(t,e,r,o,n){let i=[...eNe(e,r,o,new Set(n.map(s=>bf(s.name))))];i.length>0&&(yield{bindings:Hc(t,Object.fromEntries(i)),index:o+i.length})}function*eNe(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=Va(i.name,t.allowReserved),a=Va(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function tNe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function rNe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Va(t[o],e),i=Va(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function f8(t,e){let r=[];for(let o of t){let n=Va(o,e);if(n==null)return null;r.push(n)}return r}function Va(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var Hc=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function EL(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=nNe(i,n);if(s==null)return null;r[o]=s}return r}var nNe=(t,e)=>r$(t)||r$(e)?oNe(t,e):iNe(t.value,e.value)?t:null;function oNe(t,e){let r=n8(t.value),o=n8(e.value);if(r==null||o==null)return null;let n=r$(t),i=r$(e);if(!n&&!i)return null;if(n&&!i)return Py(o,t.prefix)===r?e:null;if(!n&&i)return Py(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Py(o,s)===r?e:null:Py(r,a)===o?t:null}var r$=t=>t.prefix!=null,n8=t=>typeof t=="string"?t:null;function iNe(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):o8(t)?o8(e)&&sNe(Object.entries(t),Object.entries(e)):t===e}var sNe=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),o8=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),aNe=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),$L=(t,e)=>e===""?[t]:t.split(e),cNe=["=",",","!","@","|"];function uNe(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new cDe(e,r));let n=t[0];if(fNe(n))return o(new uDe(e,r+1,n));if(!i8(n)&&wL(t,0)<1)return o(new lDe(e,r+1,n));let i=i8(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:lNe(t,e,r+1,s)}}function lNe(t,e,r,o){if(o>=t.length)throw new vL(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new Q5(e,r+i):new vL(e,r+i);let s=i,a=dNe(t,i);if(a===s)throw new vL(e,r+i);let c=t.slice(s,a);i=a;let u=pNe(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new fDe(e,r+i,t[i]):new dDe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new Q5(e,r+i-1)}return n}function dNe(t,e){let r=e,o=!0;for(;r<t.length;){let n=wL(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||wL(t,r+1)<1)break;r++,o=!0}return r}function pNe(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&mNe(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new pDe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function i8(t){return gDe.includes(t)&&t!==""}function fNe(t){return cNe.includes(t)}function mNe(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function hNe(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new oDe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new sDe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(uNe(f,t,i))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new iDe(t,i)),n(s),i++;continue}let a=vDe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Cy(t,i);r(new aDe(t,i,c)),n(c),i+=u}return o}var o$=class m8{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=_Ne(r),this.#e=gNe(hNe(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new m8(e,r)}get tokens(){return this.#e}expand=e=>d8(this.#e,e,this.#t);match=e=>DDe(this.#e,e,this.#t);toString=()=>this.uriTemplate},gNe=t=>Object.freeze(t.map(yNe)),yNe=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(vNe))}),vNe=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),wNe=()=>{},_Ne=({strict:t,report:e})=>(e??=wNe,t??=!0,e=t?SNe(e):e,{strict:t,report:e}),SNe=t=>e=>{throw t(e),e};function bNe(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.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[o.name]=n}return r}function xf(t,e){let r=bNe(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Ua.parse({...l,stdin:JSON.stringify(r)})}}let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(f=>f.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,f)=>{if(!t.parameters.some(p=>p.name===f))throw new Error("Declare every function parameter.");return Object.hasOwn(r,f)?n(r[f]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,f])=>[d,i(f,l)])):u},s=new o$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Ma.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.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}}function h8(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var Jl=class extends Error{constructor(r,o){super(o);this.code=r}code},RL=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},i$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||D(r)!==D(e))throw new Jl("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Rs);return await YU(r),{...r,fingerprint:await Vl(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new Jl("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},J5);if(await Kl(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},wo(H5));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await YU(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/resources/"+E.parse(e)+"/custody",{},yL);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await Oi(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=oL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&Di.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&D(o.policy)!==D(i.policy)||o.materialRevision===i.materialRevision&&await me(o)!==i.digest)throw new Jl("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!S5(i.policy,o))throw new Jl("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return KE((await this.read(e)).content,this.binding,this.keys.encryption)}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>D(c)===D(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)&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...qE(r)],origins:[],functionDigests:[],callerProgram:r!==ht.clientCredential,expiresAt:s});return Di.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&D(o)===D({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await HE(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},pn);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await HE(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},g.union([pn,pf]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},wo(K5))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},pn),a=await KE(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ht.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async prepareFunction(e,r,o=!1){let n=await this.environment(e.environmentId);if(n.manifest.functionVersion!==1)throw new Jl("function_runtime_required","Update this environment to Foundation CLI 5 or create a new environment.");if(!n.manifest.capabilities.includes(le.function)||!n.manifest.capabilities.includes(le[e.program.kind]))throw new Error("Choose an environment that can execute this function.");let i=await this.sourceContents(h8(e).map(u=>u.id)),s=new Set(i.map(u=>u.policy.id));if(o){let u=await this.api.json("/api/functions/"+r+"/authorizations",{},wo(yL));for(let l of u.items)s.has(l.content.policy.id)||(await this.observe(l.content),i.push(l.content))}let a={},c={id:r,digest:await me(e)};for(let u of i){let l=await this.read(u.policy.id);if(!l.content.policy.authorities.some(m=>D(m)===D(this.binding)))throw new Error("An authority of each input must approve its use by this function.");let d=tL(u.policy.contentType),f=Di.parse({...l.content.policy,revision:l.content.policy.revision+1,grants:[...l.content.policy.grants.filter(m=>!("function"in m)||m.function.id!==r),...s.has(u.policy.id)?[{function:c,executor:n.manifest.executor,operations:d,expiresAt:new Date(Date.now()+30*864e5).toISOString()}]:[]]}),p=await KE(l.content,this.binding,this.keys.encryption);a[u.policy.id]={version:l.version,content:await HE(p,f,l.content.materialRevision+1,this.binding,this.keys,l.content.metadata,l.content)}}return Z5.parse({functionId:r,contents:a})}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},wo(pn));s=d.items.find(f=>f.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ht.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await BE(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=Is.parse(o),s=i.kind==="function"?await this.api.json("/api/functions/"+i.functionId+"/invocation",{},W5):null;if(s&&(await me(s.definition)!==await me(i.kind==="function"?i.definition:null)||s.definition.environmentId!==r))throw new Error("Run the current function in its approved environment.");let a=s?await Kl(s.registration):await this.environment(r);await this.trusted(a.manifest.executor);let c=n.id??crypto.randomUUID(),u=n.expiresAt??new Date(Date.now()+36e5).toISOString(),l=i.kind==="function"?xf(i.definition,i.arguments):i,d=l.kind==="http"?l.request:null;if(i.kind==="http"||i.kind==="function"){let w=n.save??{},S=Object.fromEntries(await Promise.all(Object.entries(w).map(async([b,x])=>[b,await this.output(e,x,c,a,u)])));i.kind==="http"?i.save=S:i.outputs=S}let f=l.kind==="command"?l.inputs.map(w=>w.source.id):d?d.bindings.flatMap(w=>w.parts.flatMap(S=>typeof S=="string"?[]:[S.id])):[],p=s?s.sources:await this.sourceContents([...f,...n.sourceIds??[]]);if(s)for(let w of p)await this.observe(w);if(i.kind==="function"&&!n.expiresAt){let w=await me(i.definition),S=p.map(b=>Math.max(...b.policy.grants.filter(x=>"function"in x&&x.function.id===i.functionId&&x.function.digest===w&&D(x.executor)===D(a.manifest.executor)&&tL(b.policy.contentType).every(k=>x.operations.includes(k))).map(x=>Date.parse(x.expiresAt))));u=new Date(Math.min(Date.parse(u),...S)).toISOString()}let m={format:2,id:c,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:a.manifest.executor,environmentDigest:await me(a.manifest),operation:le[i.kind],operationDigest:await me(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:i.kind==="function"?await me(i.definition):null,...i.kind==="function"?{functionId:i.functionId}:{},sources:await Promise.all(p.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await me(w.policy),...w.policy.contentType===ht.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:[this.binding],createdAt:new Date().toISOString(),expiresAt:u};await JE(a,m);let y=w=>w.policy.contentType===ht.clientCredential;for(let w of p)await Bl(w,y(w)&&m.operation!==le.connect&&m.operation!==le.revoke?{...m,operation:le.refresh}:m,y(w)?{}:{destination:d?.url});return E5(m,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/executions",{method:"POST",body:e},zn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new RL(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(D(r.intent.actor)!==D(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");return this.submitPrepared(r)}async result(e){if(D(e.intent.actor)!==D(this.binding)||e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another requester.");let r=await XU(e.requestSignature,this.binding.signing,"run");if(D(r.intent)!==D(e.intent))throw new Error("The result belongs to a different signed request.");return await this.trusted(e.intent.executor),e.receipt?P5(e.receipt,e.intent,this.binding.id,this.keys):null}};import{lstat as xNe,mkdir as ENe,readFile as $Ne,readdir as RNe}from"node:fs/promises";import{join as g8}from"node:path";var y8=g.string().regex(/^(run|process|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Xl=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return D({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:y8.parse(e)})}async read(e){let r=this.context(e),o=g8(this.directory,e+".json");try{let n=await xNe(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=g.string().max(32e6).parse(JSON.parse(await $Ne(o,"utf8"))),s=await cy(i,await Bo(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(La(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await eo({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async write(e,r){let o=this.context(e),n={context:o,value:r},i=await fn(n,this.privateKeys.signing,"journal"),s=mt(D({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new uf(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Bo(this.binding.encryption,"ECDH-ES+A256KW"));await ENe(this.directory,{recursive:!0,mode:448}),await wf(g8(this.directory,e+".json"),D(a),!0)}async keys(e){let r;try{r=await RNe(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>y8.parse(o.name.slice(0,-5)))}};var s$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await jc(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await me(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&D(r)!==D(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var Ot=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function L(t,e,r,o){throw new Ot(t,e,r,o)}var a$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new Ot(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},X5)}renew(e,r){return this.api.json("/api/executions/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}dispatch(e,r){return this.api.json("/api/executions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/executions/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},zn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},g.object({id:E}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},t$),capture:(r,o,n)=>this.capture(r,o,n),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Ay),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Ay),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},So),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},Ay),state:r=>e.json("/api/connections/"+r+"/operation",{},Ay.nullable())}}};import{randomBytes as gde,randomUUID as E3e}from"node:crypto";var v8=g.object({operation:Is,save:g.record(g.string(),pe)}).strict();function c$(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t.kind==="function"?{kind:t.kind,functionId:t.functionId,definition:t.definition,arguments:t.arguments}:t}async function w8(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.connect"){let n=FE.parse(r.invocation.input),i=er.parse(e.kind==="connect"?e.input:null);if(e.kind!=="connect"||i.flowId!==r.continuationId||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Use the reviewed connection and execution environment.");if(i.action==="start"&&(i.methodId!==n.methodId||i.name!==n.name||i.appId!==(n.appId??null)||await me(i.method)!==n.methodDigest))throw new Error("Use the reviewed connection method and application.");if(!["start","exchange","commit"].includes(String(i.action)))throw new Error("Continue the reviewed connection.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=vy.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await me(c$(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="function"&&o.operation.kind==="function"){if(e.functionId!==o.operation.functionId||await me(e.definition)!==o.operation.definitionDigest||D(e.arguments)!==D(o.operation.arguments))throw new Error("Run the reviewed function and arguments.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(D(e.request)!==D(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(D(e)!==D(Is.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&D(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==D(o.save))throw new Error("Use the reviewed output destinations.");if(e.kind==="function"&&D(Object.fromEntries(Object.entries(e.outputs).map(([n,i])=>[n,i.name])))!==D(o.save))throw new Error("Use the reviewed function output destinations.")}function Oy(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function bo(t,e){for(let r of Oy(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function IL(t,e,r){let o=Oy(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function Ef(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function Kc(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}import{lookup as INe}from"node:dns/promises";import{isIP as b8}from"node:net";import{request as ANe}from"node:https";import{brotliDecompressSync as PNe,gunzipSync as kNe,inflateSync as TNe}from"node:zlib";var l$=jt(S8(),1),CNe=l$.default.IPv6.parseCIDR("2000::/3"),ONe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function x8(t){if(!b8(t)||t.includes("%"))return!1;let e=l$.default.parse(t);return ONe.has(e.range())&&(!(e instanceof l$.default.IPv6)||e.match(CNe))}function Yl(t,e){let r;try{r=new URL(t)}catch{L(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&L(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||b8(o)&&!x8(o))&&L(400,"private_destination","Choose a public HTTPS destination."),r}var d$=class{constructor(e){this.origin=e}origin;async send(e){let r=Yl(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&L(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&L(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await INe(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!x8(u.address)))&&L(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(p,m,y)=>{m.all?y(null,[a]):y(null,a.address,a.family)}},f=ANe(r,d,p=>{let m=[],y=0;p.on("data",w=>{y+=w.length,y>n?p.destroy(new Ot(413,"body_limit","The response body is too large.")):m.push(w)}),p.on("error",l),p.on("end",()=>{try{let w=Buffer.concat(m),S=p.headers["content-encoding"];if(S&&S!=="identity"){let x=S==="gzip"?kNe:S==="deflate"?TNe:S==="br"?PNe:null;if(!x)throw new Ot(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let b={};for(let[x,k]of Object.entries(p.headers))k!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(b[x]=Array.isArray(k)?k.join(", "):k);u({status:p.statusCode??502,headers:b,body:new Uint8Array(w)})}catch(w){l(w)}})});f.on("error",l),f.end(e.body)})}catch(s){if(s instanceof Ot)throw s;e.signal?.aborted&&L(409,"cancelled","The operation was cancelled."),L(502,"service_unavailable","The service could not be reached. Try again.")}}};function $f(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{L(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&L(502,"invalid_response","The service returned an invalid response."),e}function Ps(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function p$(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!c5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=mt(Ef(bo(JSON.parse(Ps(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Ps(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}function DNe(t,e){return t.policy.contentType===ht.value?e.output===void 0:t.policy.contentType===ht.tokenSet&&e.output!==void 0}var ks=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},f$=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await vf(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await vf(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await me(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let f=await vf(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:f,delivered:!1}),await this.broker.finish(r.lease,f),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(f=>{f.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let f=await $5(r.request,this.binding,this.keys);await JE(this.environment,f.intent);let p=Is.parse(f.operation);if(le[p.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await w8(o,p),await this.preflight(p,o,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.execute(p,o,r.sources,c);d=await vf(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(f){if(f instanceof ks)throw f;f instanceof by&&(f=new Ot(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let p=l&&(c.aborted||!(f instanceof Ot)||["service_unavailable","connection_uncertain","lease_lost"].includes(f.code));d=await vf(o,p?"uncertain":"failed",{ok:!1,result:null,error:f instanceof Ot?{code:f.code,message:f.message}:{code:p?"execution_uncertain":"invalid_execution",message:p?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?xf(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async preflight(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await Oi(c);let u=r.sources.find(f=>f.id===c.policy.id);if(!u||!await iL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await me(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(le[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(Yl(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=Oy(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");IL(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(Oy(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await yf(u.approval);if(D(l.policy.authorities.find(d=>d.id===l.authorityId))!==D(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==ht.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&D(d.executor)===D(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?xf(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!DNe(u,c))throw new Error("Use the input named in the signed request.");await Bl(u,r,{...n?{destination:n.url}:{}}),await qc(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async execute(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?xf(e.definition,e.arguments):e,a=[],c=new Map,u=async m=>{let y=o.find(S=>S.policy.id===m.id);if(y.policy.contentType===ht.value)return qc(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(m.id)||c.set(m.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(m.id);if(!m.output||!Object.hasOwn(w,m.output))throw new Error("Choose an available connection output.");return mt(w[m.output])};if(s.kind==="command"){let m=await p$(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:m.environment,files:m.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new Ot(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new Ot(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new Ot(422,"function_failed",Kc(y.stderr,m.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,Kc(y.stdout,m.sensitive))}return{...y,stdout:Kc(y.stdout,m.sensitive),stderr:Kc(y.stderr,m.sensitive)}}let l=structuredClone(i);for(let m of l.bindings){let y="";for(let w of m.parts)if(typeof w=="string")y+=w;else{let S=Ps(await u(w));a.push(S,Buffer.from(S).toString("base64"),Buffer.from(S).toString("base64url")),y+=S}IL(l,m.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let f=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(f.status>=400)throw new Ot(502,"service_response","The service returned an unsuccessful response.");return this.functionResult(e,r,Kc(Ps(f.body),a))}let p=e.kind==="http"?e.save:{};if(Object.keys(p).length){if(f.status>=400)throw new Ot(502,"service_response","The service returned an unsuccessful response.");let m={};for(let[y,w]of Object.entries(p)){let S=f.body;if(y!==""){let x=bo(JSON.parse(Ps(S)),y);if(x===void 0)throw new Ot(400,"invalid_pointer","The response value was not found.");S=mt(typeof x=="string"?x:JSON.stringify(x))}let b=await Sy(S,w.approval,r.id,this.binding,this.keys,{bytes:S.length});m[w.name]=(await this.broker.capture(w.name,b)).id}return{status:f.status,saved:m}}return{status:f.status,headers:Object.fromEntries(Object.entries(f.headers).map(([m,y])=>[m,Kc(y,a)])),body:Kc(Ps(f.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:ln.parse(JSON.parse(o))}catch{throw new Ot(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:bo(n,s);if(c===void 0)throw new Ot(400,"invalid_pointer","The function result value was not found.");let u=mt(typeof c=="string"?c:JSON.stringify(c)),l=await Sy(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};var oc=jt(Hq(),1);import{randomUUID as QVe}from"node:crypto";function ale(t){let e=RE.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&L(502,"invalid_response","The AWS account could not be verified."),e.data}function cle(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&lf(t.arn)===lf(e.arn)}function Bq(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&L(409,"reconnect_required","Reconnect with current AWS credentials.")}var DP=class{async obtain(e,r,o){let n=za.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};Bq(s?.expiration);let a=new oc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();Bq(d.expiration),c=new oc.STSClient({region:n.region,credentials:d});let f=ale(await c.send(new oc.GetCallerIdentityCommand({}),{abortSignal:u}));r&&!cle(f,r.sourceIdentity)&&L(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,m=f;if(n.role){l=!0;let S=(await c.send(new oc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+QVe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!S?.AccessKeyId||!S.SecretAccessKey||!S.SessionToken||!S.Expiration)&&L(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:S.AccessKeyId,secretAccessKey:S.SecretAccessKey,sessionToken:S.SessionToken,expiration:S.Expiration},Bq(p.expiration),c.destroy(),c=new oc.STSClient({region:n.region,credentials:p}),m=ale(await c.send(new oc.GetCallerIdentityCommand({}),{abortSignal:u}));let b=n.role.arn.split(":");(m.accountId!==b[4]||m.arn.split(":")[1]!==b[1]||m.arn.split(":")[5]?.split("/").slice(0,2).join("/")!=="assumed-role/"+n.role.arn.split("/").at(-1))&&L(502,"account_changed","The requested AWS role could not be verified.")}return r&&!cle(m,r.identity)&&L(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:IE.parse({...n,sourceIdentity:f,identity:m}),credentials:{AWS_ACCESS_KEY_ID:p.accessKeyId,AWS_SECRET_ACCESS_KEY:p.secretAccessKey,AWS_SESSION_TOKEN:p.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof Ot)throw d;o?.aborted&&L(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&L(409,"reconnect_required","Reconnect with current AWS credentials."),l&&L(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),L(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};import{randomUUID as eGe}from"node:crypto";var NP=class{constructor(e){this.aws=e}aws;facts=mL;validate(e){e.aws||L(400,"aws_authentication_required","Choose AWS authentication for this executor.")}async start({input:e,signal:r}){let o=(await this.aws.obtain(e.aws,void 0,r)).state;return{kind:"ready",material:zi.parse({format:2,methodId:e.methodId,method:e.method,generation:eGe(),appId:null,appGeneration:null,aws:o})}}needsRenewal(){return!1}async check(e,r){await this.outputs(e,null,r)}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};import{randomUUID as b3e}from"node:crypto";var Kq;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Kq="oauth4webapi/v3.8.8");function qw(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var ga="ERR_INVALID_ARG_VALUE",ya="ERR_INVALID_ARG_TYPE";function yr(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var rV=Symbol(),tGe=Symbol(),rGe=Symbol(),nV=Symbol();var Uw=Symbol();var nGe=new TextEncoder,oGe=new TextDecoder;function Zq(t){return typeof t=="string"?nGe.encode(t):oGe.decode(t)}var Wq;Uint8Array.prototype.toBase64?Wq=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):Wq=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var Jq;Uint8Array.fromBase64?Jq=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw yr("The input to be decoded is not correctly encoded.",ga,e)}}:Jq=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw yr("The input to be decoded is not correctly encoded.",ga,e)}};function Xq(t){return typeof t=="string"?Jq(t):Wq(t)}var Zm=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=CGe,Error.captureStackTrace?.(this,this.constructor)}},Lw=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function $e(t,e,r){return new Lw(t,{code:e,cause:r})}function iGe(t){return t.toLowerCase().replace(/^application\//,"")}function jw(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function oV(t){qw(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Kq&&!e.has("user-agent")&&e.set("user-agent",Kq),e.has("authorization"))throw yr('"options.headers" must not include the "authorization" header name',ga);return e}function sGe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw yr('"options.signal" must return or be an instance of AbortSignal',ya);return e}}function zP(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw yr(`${r} must be a number`,ya,n);if(t>0)return;if(e){if(t!==0)throw yr(`${r} must be a non-negative number`,ga,n);return}throw yr(`${r} must be a positive number`,ga,n)}catch(i){throw o?$e(i.message,o,n):i}}function tn(t,e,r,o){try{if(typeof t!="string")throw yr(`${e} must be a string`,ya,o);if(t.length===0)throw yr(`${e} must not be empty`,ga,o)}catch(n){throw r?$e(n.message,r,o):n}}function dle(t){cGe(t,"application/json")}function aGe(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return $e(r,DGe,t)}function cGe(t,e){if(yle(t)!==e)throw aGe(t,e)}async function ple(t){return tn(t,"codeVerifier"),Xq(await crypto.subtle.digest("SHA-256",Zq(t)))}function iV(t){let e=t?.[tGe];return typeof e=="number"&&Number.isFinite(e)?e:0}function sV(t){let e=t?.[rGe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function fle(){return Math.floor(Date.now()/1e3)}function ju(t){if(typeof t!="object"||t===null)throw yr('"as" must be an object',ya);tn(t.issuer,'"as.issuer"')}function Fu(t){if(typeof t!="object"||t===null)throw yr('"client" must be an object',ya);tn(t.client_id,'"client.client_id"')}function ule(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function mle(t){return tn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function hle(t){return tn(t,'"clientSecret"'),(e,r,o,n)=>{let i=ule(r.client_id),s=ule(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function gle(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var uGe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function lGe(t,e){if(e&&t.protocol!=="https:")throw $e("only requests to HTTPS are allowed",zGe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw $e("only HTTP and HTTPS requests are allowed",MGe,t)}function lle(t,e,r,o){let n;if(typeof t!="string"||!(n=uGe(t)))throw $e(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?UGe:LGe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return lGe(n,o),n}function aV(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?lle(t.mtls_endpoint_aliases[e],e,r,o):lle(t[e],e,r,o)}var Yq=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=TGe,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)}},Fw=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=OGe,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)}},Qq=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=kGe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},MP="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",dGe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",pGe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',fGe="("+MP+")\\s*=\\s*"+pGe,mGe="("+MP+")\\s*=\\s*("+MP+")",hGe=new RegExp("^[,\\s]*("+MP+")"),gGe=new RegExp("^[,\\s]*"+fGe+"[,\\s]*(.*)"),yGe=new RegExp("^[,\\s]*"+mGe+"[,\\s]*(.*)"),vGe=new RegExp("^("+dGe+")(?:$|[,\\s])(.*)");function wGe(t){if(!qw(t,Response))throw yr('"response" must be an instance of Response',ya);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(hGe),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let f,p;if(n=o.match(gGe)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(yGe)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(vGe)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function _Ge(t){if(t.status>399&&t.status<500){jP(t),dle(t);try{let e=await t.clone().json();if(jw(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function cV(t,e,r){if(t.status!==e){bGe(t);let o;throw(o=await _Ge(t))?(await t.body?.cancel(),new Yq("server responded with an error in the response body",{cause:o,response:t})):$e(`"response" is not a conform ${r} response (unexpected HTTP status code)`,NGe,t)}}function SGe(t){if(!dV.has(t))throw yr('"options.DPoP" is not a valid DPoPHandle',ga)}function yle(t){return t.headers.get("content-type")?.split(";")[0]}async function uV(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[nV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:sGe(o,s?.signal)})}async function lV(t,e,r,o,n,i){let s=aV(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[rV]!==!0);n.set("grant_type",o);let a=oV(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(SGe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await uV(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function vle(t,e,r,o,n){ju(t),Fu(e),tn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),lV(t,e,r,"refresh_token",i,n)}var wle=new WeakMap,_le=new WeakMap;function Sle(t){if(!t.id_token)return;let e=wle.get(t);if(!e)throw yr('"ref" was already garbage collected or did not resolve from the proper sources',ga);return e}async function FP(t,e,r,o,n,i){if(ju(t),Fu(e),!qw(r,Response))throw yr('"response" must be an instance of Response',ya);await cV(r,200,"Token Endpoint"),jP(r);let s=await Fle(r);if(tn(s.access_token,'"response" body "access_token" property',wt,{body:s}),tn(s.token_type,'"response" body "token_type" property',wt,{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;zP(a,!0,'"response" body "expires_in" property',wt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&tn(s.refresh_token,'"response" body "refresh_token" property',wt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw $e('"response" body "scope" property must be a string',wt,{body:s});if(s.id_token!==void 0){tn(s.id_token,'"response" body "id_token" property',wt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(zP(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await $Ge(t,e,s.id_token,a,n);IGe(e,c),RGe(c),_le.set(r,u),wle.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new Zm("unsupported `token_type` value",{cause:{body:s}});return s}function bGe(t){let e;if(e=wGe(t))throw new Qq("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function ble(t,e,r,o){return FP(t,e,r,void 0,o?.[Uw],o?.recognizedTokenTypes)}function xle(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw $e('unexpected JWT "aud" (audience) claim value',Wm,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw $e('unexpected JWT "aud" (audience) claim value',Wm,{expected:t,claims:e.claims,claim:"aud"});return e}function Ele(t,e){let r=t[VGe]?.(e)??t.issuer;if(e.claims.iss!==r)throw $e('unexpected JWT "iss" (issuer) claim value',Wm,{expected:r,claims:e.claims,claim:"iss"});return e}var dV=new WeakSet;function xGe(t){return dV.add(t),t}var pV=Symbol();async function $le(t,e,r,o,n,i,s){if(ju(t),Fu(e),!dV.has(o))throw yr('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',ga);tn(n,'"redirectUri"');let a=Od(o,"code");if(!a)throw $e('no authorization code in "callbackParameters"',wt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==pV&&(tn(i,'"codeVerifier"'),c.set("code_verifier",i)),lV(t,e,r,"authorization_code",c,s)}var Rle={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 Ile(t,e){for(let r of t)if(e.claims[r]===void 0)throw $e(`JWT "${r}" (${Rle[r]}) claim missing`,wt,{claims:e.claims});return e}function EGe(t,e){if(typeof e.claims[t]!="string")throw $e(`unexpected JWT "${t}" (${Rle[t]}) claim type`,wt,{claims:e.claims});return e}function $Ge(t,e,r,o,n){return Ule(r,Lle.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),iV(e),sV(e),n).then(Ile.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(Ele.bind(void 0,t)).then(xle.bind(void 0,e.client_id)).then(EGe.bind(void 0,"sub"))}function Ale(t,e){if(e===LP)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?LP:(zP(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function RGe(t){t.auth_time!==void 0&&zP(t.auth_time,!0,'ID Token "auth_time" (authentication time)',wt,{claims:t})}function Ple(t,e,r){if(r===LP)return;let o=fle()+iV(t),n=sV(t);if(e.auth_time+r<o-n)throw $e("too much time has elapsed since the last End-User authentication",tV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function kle(t,e){let r=e===UP?void 0:e;if(t.nonce!==r)throw $e('unexpected ID Token "nonce" claim value',Wm,{expected:r,claims:t,claim:"nonce"})}function IGe(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw $e('ID Token "aud" (audience) claim includes additional untrusted audiences',Wm,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw $e('unexpected ID Token "azp" (authorized party) claim value',Wm,{expected:t.client_id,claims:e,claim:"azp"})}}var UP=Symbol(),LP=Symbol();async function Tle(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?AGe(t,e,r,o.expectedNonce,o.maxAge,o[Uw],o.recognizedTokenTypes):PGe(t,e,r,o?.maxAge,o?.[Uw],o?.recognizedTokenTypes)}async function AGe(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=UP;break;case UP:break;default:tn(o,'"expectedNonce" argument'),a.push("nonce")}n=Ale(e,n),n!==LP&&a.push("auth_time");let c=await FP(t,e,r,a,i,s);tn(c.id_token,'"response" body "id_token" property',wt,{body:c});let u=Sle(c);return Ple(e,u,n),kle(u,o),c}async function PGe(t,e,r,o,n,i){let s=await FP(t,e,r,void 0,n,i),a=Sle(s);return a&&(Ple(e,a,Ale(e,o)),kle(a,UP)),s}var kGe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",TGe="OAUTH_RESPONSE_BODY_ERROR",CGe="OAUTH_UNSUPPORTED_OPERATION",OGe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var eV="OAUTH_PARSE_ERROR",wt="OAUTH_INVALID_RESPONSE";var DGe="OAUTH_RESPONSE_IS_NOT_JSON",NGe="OAUTH_RESPONSE_IS_NOT_CONFORM",zGe="OAUTH_HTTP_REQUEST_FORBIDDEN",MGe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",tV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Wm="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var UGe="OAUTH_MISSING_SERVER_METADATA",LGe="OAUTH_INVALID_SERVER_METADATA";function jGe(t,e){if(typeof e.header.typ!="string"||iGe(e.header.typ)!==t)throw $e('unexpected JWT "typ" header parameter value',wt,{header:e.header});return e}async function Cle(t,e,r,o,n){return ju(t),Fu(e),lV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Ole(t,e,r,o){return FP(t,e,r,void 0,o?.[Uw],o?.recognizedTokenTypes)}async function Dle(t,e,r,o,n){ju(t),Fu(e),tn(o,'"token"');let i=aV(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[rV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=oV(n?.headers);return a.delete("accept"),uV(t,e,r,i,s,a,n)}async function Nle(t){if(!qw(t,Response))throw yr('"response" must be an instance of Response',ya);await cV(t,200,"Revocation Endpoint")}function jP(t){if(t.bodyUsed)throw yr('"response" body has been used already',ga)}async function zle(t,e,r,o,n){ju(t),Fu(e),tn(o,'"token"');let i=aV(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[rV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=oV(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),uV(t,e,r,i,s,a,n)}async function Mle(t,e,r,o){if(ju(t),Fu(e),!qw(r,Response))throw yr('"response" must be an instance of Response',ya);await cV(r,200,"Introspection Endpoint");let n;if(yle(r)==="application/token-introspection+jwt"){jP(r);let{claims:i,jwt:s}=await Ule(await r.text(),Lle.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),iV(e),sV(e),o?.[Uw]).then(jGe.bind(void 0,"token-introspection+jwt")).then(Ile.bind(void 0,["aud","iat","iss"])).then(Ele.bind(void 0,t)).then(xle.bind(void 0,e.client_id));if(_le.set(r,s),!jw(i.token_introspection))throw $e('JWT "token_introspection" claim must be a JSON object',wt,{claims:i});n=i.token_introspection}else jP(r),n=await Fle(r);if(typeof n.active!="boolean")throw $e('"response" body "active" property must be a boolean',wt,{body:n});return n}async function Ule(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new Zm("JWE decryption is not configured",{cause:t});if(a!==3)throw $e("Invalid JWT",wt,t);let c;try{c=JSON.parse(Zq(Xq(i)))}catch(d){throw $e("failed to parse JWT Header body as base64url encoded JSON",eV,d)}if(!jw(c))throw $e("JWT Header must be a top level object",wt,t);if(e(c),c.crit!==void 0)throw new Zm('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Zq(Xq(s)))}catch(d){throw $e("failed to parse JWT Payload body as base64url encoded JSON",eV,d)}if(!jw(u))throw $e("JWT Payload must be a top level object",wt,t);let l=fle()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw $e('unexpected JWT "exp" (expiration time) claim type',wt,{claims:u});if(u.exp<=l-o)throw $e('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',tV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw $e('unexpected JWT "iat" (issued at) claim type',wt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw $e('unexpected JWT "iss" (issuer) claim type',wt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw $e('unexpected JWT "nbf" (not before) claim type',wt,{claims:u});if(u.nbf>l+o)throw $e('unexpected JWT "nbf" (not before) claim value',tV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw $e('unexpected JWT "aud" (audience) claim type',wt,{claims:u});return{header:c,claims:u,jwt:t}}function Lle(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw $e('unexpected JWT "alg" header parameter',wt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw $e('unexpected JWT "alg" header parameter',wt,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw $e('unexpected JWT "alg" header parameter',wt,{header:o,expected:r,reason:"default value"});return}throw $e('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Od(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw $e(`"${e}" parameter must be provided only once`,wt);return r}var FGe=Symbol(),qGe=Symbol();function jle(t,e,r,o){if(ju(t),Fu(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw yr('"parameters" must be an instance of URLSearchParams, or URL',ya);if(Od(r,"response"))throw $e('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',wt,{parameters:r});let n=Od(r,"iss"),i=Od(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw $e('response parameter "iss" (issuer) missing',wt,{parameters:r});if(n&&n!==t.issuer)throw $e('unexpected "iss" (issuer) response parameter value',wt,{expected:t.issuer,parameters:r});switch(o){case void 0:case qGe:if(i!==void 0)throw $e('unexpected "state" response parameter encountered',wt,{expected:void 0,parameters:r});break;case FGe:break;default:if(tn(o,'"expectedState" argument'),i!==o)throw $e(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',wt,{expected:o,parameters:r})}if(Od(r,"error"))throw new Fw("authorization response from the server is an error",{cause:r});let a=Od(r,"id_token"),c=Od(r,"token");if(a!==void 0||c!==void 0)throw new Zm("implicit and hybrid flows are not supported");return xGe(new URLSearchParams(r))}async function Fle(t,e=dle){let r;try{r=await t.json()}catch(o){throw e(t),$e('failed to parse "response" body as JSON',eV,o)}if(!jw(r))throw $e('"response" body must be a top level object',wt,{body:r});return r}var VGe=Symbol();import{createHash as GGe}from"node:crypto";function qu(t,e){try{return Yl(new o$(t).expand(e)).href}catch{L(400,"invalid_service_url","Check the service URL and its required fields.")}}var qP=t=>GGe("sha256").update(t).digest("hex"),Vw=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],VP=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&L(502,"invalid_response","The service returned an invalid expiry."),e};var Vle=Object.assign(Object.create(null),{dpop:()=>L(502,"invalid_response","The service returned an unsupported token.")}),HGe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Vle,{"user access token":()=>{}}),refreshInspection:!0,async inspect(t){let{app:e,current:r}=t,{server:o,client:n}=t.configuration(),i=await zle({...o,introspection_endpoint:o.token_endpoint+"/introspect"},n,t.authentication("basic"),r.accessToken,{...t.options(),additionalParameters:{token_type_hint:"access_token"}}),s;try{s=await Mle(o,n,Response.json(await t.json(i),{status:i.status}))}catch{L(409,"reconnect_required","Reconnect this service to renew access.")}return(s.active!==!0||s.client_id!==e.clientId||typeof s.sub!="string"||!s.sub||typeof s.exp!="number"||s.exp*1e3<=Date.now())&&L(409,"reconnect_required","Reconnect this service to renew access."),{...r,account:s.sub,accountName:typeof s.username=="string"?s.username:s.sub,scopes:Vw(s.scope),scopesStatus:"reported",accountVerified:!0,expiresAt:Math.min(r.expiresAt??1/0,s.exp*1e3)}}},BGe={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&L(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key",allowAccountChange:!0,refreshInspection:!0,async inspect({transport:t,current:e}){let r=await t.send({url:"https://openrouter.ai/api/v1/key",headers:{authorization:"Bearer "+e.accessToken}}),o=$f(r);(r.status!==200||!o.data||typeof o.data!="object")&&L(409,"reconnect_required","Reconnect this service to renew access.");let n=o.data;return{...e,account:qP(e.accessToken),accountName:typeof n.label=="string"?n.label:"OpenRouter",facts:n}}},KGe={verifyIdentity({current:t,response:e}){e.headers["x-oauth-scopes"]!==void 0&&(t.scopes=Vw(e.headers["x-oauth-scopes"].replaceAll(","," ")),t.scopesStatus="reported")}},ZGe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+Buffer.from(t.clientId+":"+(t.clientSecret??"")).toString("base64"),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},WGe={verifyIdentity({data:t}){t.email_verified!==!0&&L(502,"invalid_response","The service account could not be verified.")}},JGe=Object.assign(Object.create(null),{ebay:HGe,openrouter:BGe,github:KGe,google:WGe}),XGe=[{matches:t=>t.hostname.endsWith(".myshopify.com"),service(t,e){return{...e.pathname==="/admin/oauth/access_token"?{normalizeToken(r){r.token_type===void 0&&(r.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...t.grantType==="client_credentials"&&/^\/admin\/api\/[^/]+\/graphql\.json$/.test(e.pathname)?{identityRequest({spec:r,url:o,current:n}){return{url:o,method:r.identity.method,headers:{...r.identity.headers,"content-type":"application/json","X-Shopify-Access-Token":n.accessToken},body:JSON.stringify({query:"{ shop { id name myshopifyDomain } }"})}},verifyIdentity({app:r,data:o}){((Array.isArray(o.errors)?o.errors.length:o.errors)||bo(o,"/data/shop/myshopifyDomain")!==r.fields.shop+".myshopify.com")&&L(502,"invalid_response","The Shopify store could not be verified.")}}:{}}}},{matches:t=>t.hostname==="api.notion.com"&&t.pathname==="/v1/oauth/token",service:()=>({normalizeToken(t){t.refresh_token===null&&delete t.refresh_token}})}];function so(t,e){let r=e?new URL(e):void 0,o=r?XGe.find(i=>i.matches(r))?.service(t,r):void 0,n=t.adapter?JGe[t.adapter]:void 0;return t.adapter&&!n&&L(400,"invalid_input","Choose a supported service authentication adapter."),{recognizedTokenTypes:Vle,...o,...n,...t.revoke?.style==="github"?ZGe:{},...o?.verifyIdentity||n?.verifyIdentity?{verifyIdentity(i){o?.verifyIdentity?.(i),n?.verifyIdentity?.(i)}}:{}}}var GP=class{constructor(e){this.transport=e}transport;appValues(e,r){return{...e.defaults,...r.fields,clientId:r.clientId}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&L(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(qu(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:so(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await ple(n),c.code_challenge_method="S256"),so(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(qu(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:qu(e.tokenUrl,this.appValues(e,r))};return e.issuer&&Yl(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?gle():(e.clientSecret||L(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?hle(e.clientSecret):mle(e.clientSecret))}options(e="form"){return{[nV]:async(r,{body:o,headers:n,method:i,signal:s})=>{let a=await this.transport.send({url:r,method:i,headers:e==="json"?{...n,"content-type":"application/json"}:n,body:e==="json"?JSON.stringify(Object.fromEntries(o)):o.toString(),signal:s});return new Response([204,205,304].includes(a.status)?null:new Uint8Array(a.body),{status:a.status,headers:a.headers})}}}async json(e){return $f({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&bo(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&L(409,"reconnect_required","Reconnect this service to renew access."),r===429&&L(503,"service_rate_limit","The service is busy. Try again later."),L(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&L(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,so(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=VP(u.expires_in));try{let d=await(n?ble:e.grantType==="client_credentials"?Ole:Tle)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:so(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof Ot)throw l;L(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[so(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&L(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+VP(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&L(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?Vw(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+VP(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&L(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=so(e);if(l.exchange){let p=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>qu(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,p.status,$f(p))}else{let{server:p,client:m}=this.configuration(e,r),y;try{let w=jle(p,m,o.parameters,o.state);y=await $le(p,m,this.authentication(r,e.clientAuth),w,l.redirectUri?.(r,i)??i,e.pkce?n:pV,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(w){throw(w instanceof Lw||w instanceof Fw)&&L(400,"invalid_state","Start the connection again."),w}u=await this.tokenResponse(e,r,y)}let d=this.token(e,u,s,a);await c?.(d,u);let f=await this.inspect(e,r,d,u);return a&&f.account!==a.account&&!l.allowAccountChange&&L(409,"account_changed","Reconnect using the same service account."),f}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&L(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=so(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Cle(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e.tokenFormat)),d=await this.tokenResponse(e,r,l),f={...this.token(e,d,o,n,!!n),requestedScopes:o};await i?.(f,d);let p=await this.inspect(e,r,f,d);return n&&p.account!==n.account&&L(409,"account_changed","Reconnect using the same service account."),p}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||L(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&L(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await vle(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return(e.identity?.url||so(e).refreshInspection)&&(i=await this.inspect(e,r,i)),i.account!==o.account&&L(409,"account_changed","Reconnect using the same service account."),i}async inspect(e,r,o,n){let i=n??{},s=so(e);if(s.inspect)return s.inspect({spec:e,app:r,transport:this.transport,current:o,configuration:()=>this.configuration(e,r),authentication:l=>this.authentication(r,l),options:()=>this.options(),json:l=>this.json(l)});if(e.identity?.url){let l=qu(e.identity.url,{...this.appValues(e,r),...o.extra,accessToken:o.accessToken,refreshToken:o.refreshToken??""}),d=so(e,l),f=await this.transport.send(d.identityRequest?.({spec:e,app:r,transport:this.transport,url:l,current:o})??{url:l,method:e.identity.method,headers:{...e.identity.headers,authorization:"Bearer "+o.accessToken}});i=$f(f),(f.status===401||f.status===403)&&L(409,"reconnect_required","Reconnect this service to renew access."),f.status>=400&&L(502,"invalid_response","The service account could not be verified."),d.verifyIdentity?.({spec:e,app:r,transport:this.transport,current:o,response:f,data:i})}else e.identity?.from==="app"&&(i=this.appValues(e,r));let a=l=>{for(let d of Array.isArray(l)?l:[l]){let f=bo(i,d);if(typeof f=="string"&&f||typeof f=="number")return String(f)}return""},c=e.identity?.id,u=c?Array.isArray(c)?c.map(l=>a(l)).filter(Boolean).join(":"):a(c):o.account||r.fields.domain||r.fields.shop||qP(o.accessToken);return(!u||u.length>1e3)&&L(502,"invalid_response","The service account could not be verified."),{...o,account:u,accountName:e.identity&&a(e.identity.name)||u,accountVerified:!!(e.identity?.url||e.identity?.from==="token"&&n)}}async revoke(e,r,o){e.revoke||L(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=qu(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await Dle({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Nle(d)}catch{L(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+Buffer.from(r.clientId+":"+(r.clientSecret??"")).toString("base64")),(await this.transport.send(so(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&L(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,Ef(bo(n,s))]))}};var pde=jt(dde(),1);function Hw(t,e,r={}){let o={...r,...e};for(let n of t)n.required!==!1&&!o[n.name]&&L(400,"missing_field","Complete the required service fields."),o[n.name]?.includes("\0")&&L(400,"invalid_field","Check the service fields."),n.pattern&&(n.pattern.length>200||!(0,pde.default)(n.pattern))&&L(400,"invalid_pattern","Use a simple field validation pattern."),n.pattern&&o[n.name]&&!new RegExp(n.pattern,"u").test(o[n.name].slice(0,1e3))&&L(400,"invalid_field","Check the service fields.");return Object.keys(e).some(n=>!t.some(i=>i.name===n))&&L(400,"invalid_field","Remove unrecognized service fields."),o}function Gu(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function Nd(t){return t||L(409,"app_required","Choose an OAuth application."),t}function SV(t){let e=Gu(t).scopes;return QE(e,t.scopes)}function fde(t,e,r){return zi.parse({format:2,methodId:t.methodId,method:t.method,generation:b3e(),appId:t.appId,appGeneration:t.appId?e.generation:null,oauth:r})}function mde(t){return{token:gL.parse(t.token),response:er.parse(t.response)}}var ek=class{constructor(e){this.transport=e}transport;facts=pL;oauth(e){return new GP({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}validate(e,r){let o=Gu(e),n=Nd(r);so(o),Hw(o.fields,n.fields,o.defaults),Zo(e.method).requiresApp&&o.clientAuth!=="none"&&!n.clientSecret&&L(409,"app_required","Add a client secret to this OAuth application.")}async start(e){let{input:r,signal:o}=e,n=Gu(r),i=Nd(e.app);if(n.grantType!=="client_credentials")return{kind:"authorize",url:await this.oauth(o).authorize(n,i,e.state,e.verifier,r.redirectUri,SV(r))};await e.dispatch();let s=await this.oauth(o).clientCredentials(n,i,SV(r),void 0,(a,c)=>e.receive({token:a,response:c}));return{kind:"ready",material:fde(r,i,s)}}async exchange(e,r,o){let{input:n,signal:i}=e,s=Gu(n),a=Nd(e.app),c=new URLSearchParams(r);(c.getAll("state").length!==1||c.get("state")!==e.state)&&L(400,"invalid_state","Start the connection again.");let u;if(o){let l=mde(o);u=await this.oauth(i).inspect(s,a,l.token,l.response)}else await e.dispatch(),u=await this.oauth(i).exchange(s,a,{parameters:c,state:e.state},e.verifier,n.redirectUri,SV(n),void 0,(l,d)=>e.receive({token:l,response:d}));return fde(n,a,u)}needsRenewal(e){return e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=await this.oauth(e.signal).refresh(Gu(e.material),Nd(e.app),e.material.oauth,(o,n)=>e.receive({token:o,response:n}));return zi.parse({...e.material,oauth:r})}async recover(e,r,o){let n=mde(o),i=await this.oauth().inspect(Gu(e),Nd(r),n.token,n.response);return zi.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(Gu(e),Nd(r),e.oauth)}async revoke(e,r,o){await this.oauth(o).revoke(Gu(e),Nd(r),e.oauth)}};import{randomUUID as x3e}from"node:crypto";function bV(t){if(t.method.kind!=="token")throw new Error("Use a token connection provider.");return t.method.config}var tk=class{facts=fL;validate(e){Hw(bV(e).fields,e.fields)}async start({input:e}){return{kind:"ready",material:zi.parse({format:2,methodId:e.methodId,method:e.method,generation:x3e(),appId:null,appGeneration:null,fields:Hw(bV(e).fields,e.fields)})}}needsRenewal(){return!1}async outputs(e){return Object.fromEntries(Object.entries(bV(e).outputs).map(([r,o])=>[r,Ef(bo(e.fields,o))]))}};function hde(t,e){return{oauth:new ek(t),token:new tk,aws:new NP(e)}}var Ym=class{constructor(e,r,o,n,i,s=new DP){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=hde(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers[Zo(e).family]}metadata(e){return q5(e,this.provider(e.method).facts(e))}labels(e){return G5(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||L(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=zi.safeParse(JSON.parse(Ps(await qc(e,r,this.keys,{destination:o}))));n.success||L(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&L(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==le.revoke&&L(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,ht.clientCredential,n),s=Zl.parse(JSON.parse(Ps(await qc(i,o,this.keys))));return s.methodId!==r&&L(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(Zo(e.method).application==="none")return null;if(!As(e.method))return Zl.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===le.revoke?le.revoke:le.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&L(409,"app_changed","Reconnect this service with the current application."),i}async flow(e,r){let o=await this.readFlow(e);return(!o||o.expiresAt<=Date.now()||D(o.actor)!==D(r.actor)||o.ownerId!==r.ownerId)&&L(409,"connection_expired","Start the connection again."),o}async readFlow(e){let r=await this.journal.read("connect_"+e);return r&&(!Iy.safeParse(r.input).success||r.material&&!zi.safeParse(r.material).success)&&L(409,"connection_expired","Start the connection again."),r}writeFlow(e,r){return this.journal.write("connect_"+e,r)}async startApp(e,r,o){return Zo(e.method).application==="none"?null:e.appId?this.app(e.appId,e.methodId,r,o):Zl.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}})}authorization(e,r,o){return{input:r.input,app:r.app,state:r.state,verifier:r.verifier,signal:o,dispatch:async()=>{r.phase="exchanging",await this.writeFlow(e,r)},receive:async n=>{r.checkpoint=n,r.phase="received",await this.writeFlow(e,r)}}}async validate(e,r,o){let n=Iy.parse(e),i=le[n.action==="refresh"||n.action==="revoke"?n.action:"connect"];if(r.operation!==i&&L(400,"wrong_operation","Use the approved connection operation."),n.action==="start"){if(As(n.method)&&!n.appId&&L(400,"app_required","Choose an OAuth application."),Zo(n.method).browserAuthorization){n.redirectUri||L(400,"invalid_redirect","Choose a callback URL.");let s=new URL(n.redirectUri);(s.username||s.password||s.hash||s.search||!(n.redirectUri===r.origin+"/oauth/callback"||s.protocol==="http:"&&["127.0.0.1","[::1]"].includes(s.hostname)))&&L(400,"invalid_redirect","Use the Foundation callback or a callback on this computer.")}this.provider(n.method).validate(n,await this.startApp(n,r,o))}else if(n.action==="commit"){let s=await this.flow(n.flowId,r),a=await yf(n.approval);(!s.material||n.authorizationDigest!==(await this.metadata(s.material)).authorizationDigest||a.policy.contentType!==ht.tokenSet||a.policy.ownerId!==r.ownerId||a.policy.origin!==r.origin||D(a.policy.authorities.find(c=>c.id===a.authorityId))!==D(r.actor)||!a.policy.producers.some(c=>c.runId===r.id&&D(c.executor)===D(this.binding)&&Date.parse(c.expiresAt)>Date.now()))&&L(403,"approval_required","Review the connection and approve its recipients before saving.")}else if(n.action==="exchange"){let s=await this.flow(n.flowId,r);if(s.app&&s.input.appId){let a=await this.app(s.input.appId,s.input.methodId,r,o);D(a)!==D(s.app)&&L(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,ht.tokenSet,o),a=await this.material(s,r);await this.connectionApp(a,r,o)}}async execute(e,r,o,n){let i=Iy.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&L(409,"connection_busy","Another operation is updating this connection."),this.active.add(s);try{if(n.throwIfAborted(),i.action==="start")return await this.start(i,r,o,n);if(i.action==="exchange")return await this.exchange(i,r,n);if(i.action==="commit")return await this.commit(i,r);let a=this.source(i.id,ht.tokenSet,o),c=await this.material(a,r);if(i.action==="refresh"){await this.provider(c.method).check?.(c,n);let l=await this.refresh(a,c,r,o,n);return{kind:"refreshed",id:a.policy.id,...await this.metadata(l)}}let u=this.provider(c.method);return u.revoke||L(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await u.revoke(c,await this.connectionApp(c,r,o),n),{kind:"revoked",id:a.policy.id}}finally{this.active.delete(s)}}async review(e,r){return{kind:"review",flowId:e,name:r.input.name,metadata:{...await this.metadata(r.material),...this.labels(r.material)}}}async start(e,r,o,n){await this.readFlow(e.flowId)&&L(409,"flow_exists","Use a new connection request.");let i={actor:r.actor,ownerId:r.ownerId,input:e,app:await this.startApp(e,r,o),state:gde(32).toString("base64url"),verifier:gde(32).toString("base64url"),expiresAt:Math.min(Date.now()+6e5,Date.parse(r.expiresAt)),phase:"authorize"};await this.writeFlow(e.flowId,i);let s=await this.provider(e.method).start(this.authorization(e.flowId,i,n));return s.kind==="ready"?(i.material=s.material,i.phase="review",await this.writeFlow(e.flowId,i),this.review(e.flowId,i)):(e.redirectUri===r.origin+"/oauth/callback"&&await this.broker.relay?.({id:e.flowId,runId:r.id,stateDigest:await me(i.state),expiresAt:new Date(i.expiresAt).toISOString()}),{kind:"authorize",flowId:e.flowId,url:s.url})}async exchange(e,r,o){let n=await this.flow(e.flowId,r);if(n.phase==="review")return this.review(e.flowId,n);let i=this.provider(n.input.method);return(!i.exchange||!["authorize","received"].includes(n.phase))&&L(409,"connection_uncertain","Check the connection before authorizing it again."),n.material=await i.exchange(this.authorization(e.flowId,n,o),e.parameters,n.phase==="received"?n.checkpoint:void 0),n.phase="review",await this.writeFlow(e.flowId,n),this.review(e.flowId,n)}async commit(e,r){let o=await this.flow(e.flowId,r);if(o.phase==="committed")return{kind:"connected",id:o.content.policy.id};["review","committing"].includes(o.phase)||L(409,"approval_required","Review this connection before saving."),o.content?(D(o.content.policy)!==D(e.approval.policy)||o.content.creationRunId!==r.id)&&L(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await Sy(mt(D(o.material)),e.approval,r.id,this.binding,this.keys,await this.metadata(o.material)),o.phase="committing",await this.writeFlow(e.flowId,o));let n;try{n=await this.broker.capture(o.input.name,o.content,this.labels(o.material))}catch(i){throw i instanceof Ot&&i.status<500?i:new ks}return o.phase="committed",await this.writeFlow(e.flowId,o),{kind:"connected",id:n.id}}async recover(e,r){let o=Iy.parse(e);if(o.action!=="commit")return null;let n=await this.readFlow(o.flowId);if(!n?.content||n.ownerId!==r.ownerId||D(n.actor)!==D(r.actor)||n.content.creationRunId!==r.id||D(n.content.policy)!==D(o.approval.policy)||!["committing","committed"].includes(n.phase))return null;try{await this.broker.capture(n.input.name,n.content,this.labels(n.material))}catch(i){if(i instanceof Ot&&i.status<500)return null;throw new ks}return n.phase="committed",await this.writeFlow(o.flowId,n),{kind:"connected",id:n.content.policy.id}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&L(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&L(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await x5(e.previous,mt(D(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||L(409,"reconnect_required","Reconnect this service to renew access.");try{await Bl(e,{...o,operation:le.refresh},{destination:s})}catch{L(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=E3e(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let f=await a.renew({material:r,app:c,signal:i,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,f)}catch(f){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),f instanceof Ot&&["connection_review","reconnect_required","account_changed"].includes(f.code))throw f;L(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};function zo(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=xV($3e(qa()),"custody",r.id),i=new Xl(xV(n,"client"),o,r,e),s=new i$(t,o,r,e,new s$(i)),a=new a$(t),c=new d$(o),u=new Ym(r,e,a.connections(),new Xl(xV(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function yde(t,e){let{custody:r,keys:o,binding:n,connections:i}=zo(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await me(n),operation:le.command,functionDigest:null,operationDigest:await me(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await me(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===ht.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return p$(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ht.value)return qc(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return mt(d[u.output])})}import{mkdir as dnt}from"node:fs/promises";import{join as L_}from"node:path";import{setTimeout as pnt}from"node:timers/promises";import{spawn as R3e}from"node:child_process";import{constants as EV}from"node:fs";import{open as vde,rm as I3e}from"node:fs/promises";async function wde(t){if(process.platform!=="linux"){let r=await vde(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await I3e(t,{force:!0})}}let e=await vde(t,EV.O_CREAT|EV.O_WRONLY|EV.O_NOFOLLOW,384);try{let r=R3e("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var WO=jt(Hq(),1),JO=jt(Qxe(),1);function e0e(t){return sL.safeParse(t).success?t:null}async function t0e(t=3e3){let e=new WO.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new WO.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=e0e(n.Arn);if(i)return i;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 JO.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new JO.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=e0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var vG=g.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),wG=vG.max(4096).startsWith("/"),r0e=g.object({command:g.array(vG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:wG.optional(),environment:g.record(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),vG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:g.string().max(1e6).default(""),timeoutSeconds:g.number().int().min(1).max(3600).default(60)}).strict(),TBt=r0e.extend({id:E.optional()}),n0e=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),o0e=g.object({exitCode:g.number().int().nullable(),signal:g.string().max(32).nullable(),stdout:g.string().max(1e6),stderr:g.string().max(1e6),timedOut:g.boolean(),truncated:g.boolean()}).strict(),CBt=g.object({state:n0e.exclude(["queued","running"]),result:o0e.nullable(),error:g.string().max(100).nullable()}).strict(),XO=r0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:wG,state:n0e,result:o0e.nullable(),error:g.string().nullable(),createdAt:nt,startedAt:nt.nullable(),finishedAt:nt.nullable()}).strict(),OBt=XO.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),DBt=g.object({workingDirectory:wG}).strict(),i0e=g.object({lease:E,process:XO}).strict().nullable();var YO=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},i0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},g.object({active:g.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},XO)}},QO=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new ks}return!0}};import{spawn as tnt,execFile as rnt}from"node:child_process";import{chmod as nnt,lstat as s0e,mkdir as _G,readFile as a0e,readdir as ont,realpath as c0e,rename as int,rm as snt,symlink as ant,writeFile as u0e}from"node:fs/promises";import{join as Qu}from"node:path";import{promisify as cnt}from"node:util";import{createConnection as unt}from"node:net";import{setTimeout as lnt}from"node:timers/promises";var SG=cnt(rnt),U_=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',eD=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1||e.port>65535)throw new Error("Use a valid SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=Qu(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await _G(this.options.directory,{recursive:!0,mode:448}),await _G(this.sessions,{recursive:!0,mode:448}),await _G(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await s0e(this.options.workspaceLink),await c0e(this.options.workspaceLink)!==await c0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await ant(this.options.workspace,this.options.workspaceLink)}let e=Qu(this.options.directory,"host_ed25519");try{await s0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await SG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:Ni(),timeout:1e4})}await nnt(e,384),this.hostKey=ny.parse((await SG("ssh-keygen",["-y","-f",e],{env:Ni(),timeout:1e4})).stdout);let r=Qu(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+U_(e),"PidFile "+U_(Qu(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+U_(Qu(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+U_("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+U_("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
|
|
131
131
|
`)+`
|
|
132
132
|
`;await u0e(r,o,{mode:384}),await this.sync(),await SG("/usr/sbin/sshd",["-t","-f",r],{env:Ni(),timeout:1e4});let n=tnt("/usr/sbin/sshd",["-D","-e","-f",r],{env:Ni(),detached:!0,stdio:"ignore"});this.child=n;let i=null;n.once("error",s=>{i=s});try{for(let s=0;;s++){if(i||n.exitCode!==null||n.signalCode!==null||s>=100)throw i??new Error("The SSH server could not start.");if(await this.listening())break;await lnt(50)}await this.sync(),this.timer=setInterval(()=>{!this.pending&&!this.closing&&(this.pending=this.sync().catch(()=>{process.stderr.write(JSON.stringify({event:"ssh_settings_pending"})+`
|
|
133
133
|
`)}).finally(()=>{this.pending=null}))},1e4),this.timer.unref()}catch(s){throw await this.stop(),s}}ensureRunning(){if(!this.child?.pid||this.child.exitCode!==null||this.child.signalCode!==null)throw new Error("The SSH server has stopped.")}listening(){return new Promise(e=>{let r=unt({host:this.options.listenAddress==="::1"?"::1":"127.0.0.1",port:this.options.port});r.setTimeout(500),r.once("connect",()=>{r.destroy(),e(!0)}),r.once("error",()=>{r.destroy(),e(!1)}),r.once("timeout",()=>{r.destroy(),e(!1)})})}async activeSessions(){let e=0;for(let r of await ont(this.sessions)){if(!/^[1-9][0-9]*$/.test(r))continue;let o=Qu(this.sessions,r);try{let[n,i]=await Promise.all([a0e(o,"utf8"),a0e("/proc/"+r+"/stat","utf8")]),s=a=>a.slice(a.lastIndexOf(")")+2).trim().split(/\s+/)[19];if(!s(n)||s(n)!==s(i))throw new Error("The SSH session has ended.");e++}catch{await snt(o,{force:!0})}}return Math.min(e,1024)}async sync(){let{configuration:e}=eE.parse(await this.heartbeat({hostKey:this.hostKey,appliedRevision:this.child?.pid&&this.child.exitCode===null&&this.child.signalCode===null?this.appliedRevision:0,activeSessions:await this.activeSessions()}));if(!e||e.port!==this.options.port)throw new Error("The SSH settings belong to another listener.");if(this.appliedRevision!==e.revision){let r=Qu(this.options.directory,"authorized_keys."+crypto.randomUUID());await u0e(r,e.authorizedKeys.join(`
|