@zuplo/graphql 5.1797.0 → 5.1800.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/index.d.ts +5 -1
- package/index.minified.js +1 -1
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -644,6 +644,10 @@ declare interface RouteConfiguration extends Omit<BuildRouteConfiguration, "raw"
|
|
|
644
644
|
|
|
645
645
|
declare type UserDataDefault = any;
|
|
646
646
|
|
|
647
|
+
declare interface WaitUntilFunc {
|
|
648
|
+
(promise: Promise<any>): void;
|
|
649
|
+
}
|
|
650
|
+
|
|
647
651
|
/**
|
|
648
652
|
* @beta
|
|
649
653
|
*/
|
|
@@ -663,7 +667,7 @@ declare interface ZuploContext extends EventTarget {
|
|
|
663
667
|
readonly custom: Record<string, any>;
|
|
664
668
|
readonly incomingRequestProperties: IncomingRequestProperties;
|
|
665
669
|
readonly invokeInboundPolicy: (policyName: string, request: ZuploRequest) => Promise<Response | ZuploRequest>;
|
|
666
|
-
readonly waitUntil:
|
|
670
|
+
readonly waitUntil: WaitUntilFunc;
|
|
667
671
|
/**
|
|
668
672
|
* Fires just before the response is sent. Response can be modified.
|
|
669
673
|
*/
|
package/index.minified.js
CHANGED
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
`)}s(lI,"messagesToMultilineText");qe.messagesToMultilineText=lI;function wm(t){return typeof t=="string"?t:JSON.stringify(t)}s(wm,"stringifyNonString");qe.stringifyNonString=wm;function Em(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?(0,_m.toString)(t):"unknown"}s(Em,"stringifyNonStringToText");qe.stringifyNonStringToText=Em});var D,ae,Se=I(()=>{D=crypto,ae=s(t=>t instanceof CryptoKey,"isCryptoKey")});var dI,ns,Nl=I(()=>{Se();dI=s(async(t,e)=>{let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await D.subtle.digest(r,e))},"digest"),ns=dI});function Te(...t){let e=t.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(e),n=0;return t.forEach(i=>{r.set(i,n),n+=i.length}),r}function vm(t,e){return Te(Z.encode(t),new Uint8Array([0]),e)}function Cl(t,e,r){if(e<0||e>=is)throw new RangeError(`value must be >= 0 and <= ${is-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function os(t){let e=Math.floor(t/is),r=t%is,n=new Uint8Array(8);return Cl(n,e,0),Cl(n,r,4),n}function ss(t){let e=new Uint8Array(4);return Cl(e,t),e}function as(t){return Te(ss(t.length),t)}async function Sm(t,e,r){let n=Math.ceil((e>>3)/32),i=new Uint8Array(n*32);for(let o=0;o<n;o++){let a=new Uint8Array(4+t.length+r.length);a.set(ss(o+1)),a.set(t,4),a.set(r,4+t.length),i.set(await ns("sha256",a),o*32)}return i.slice(0,e>>3)}var Z,ue,is,ge=I(()=>{Nl();Z=new TextEncoder,ue=new TextDecoder,is=2**32;s(Te,"concat");s(vm,"p2s");s(Cl,"writeUInt32BE");s(os,"uint64be");s(ss,"uint32be");s(as,"lengthAndInput");s(Sm,"concatKdf")});var cs,X,xl,re,Ie=I(()=>{ge();cs=s(t=>{let e=t;typeof e=="string"&&(e=Z.encode(e));let r=32768,n=[];for(let i=0;i<e.length;i+=r)n.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));return btoa(n.join(""))},"encodeBase64"),X=s(t=>cs(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),"encode"),xl=s(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},"decodeBase64"),re=s(t=>{let e=t;e instanceof Uint8Array&&(e=ue.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return xl(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}},"decode")});var Ll={};co(Ll,{JOSEAlgNotAllowed:()=>nr,JOSEError:()=>he,JOSENotSupported:()=>k,JWEDecryptionFailed:()=>Ht,JWEInvalid:()=>R,JWKInvalid:()=>di,JWKSInvalid:()=>ir,JWKSMultipleMatchingKeys:()=>pi,JWKSNoMatchingKey:()=>Mr,JWKSTimeout:()=>hi,JWSInvalid:()=>z,JWSSignatureVerificationFailed:()=>Hr,JWTClaimValidationFailed:()=>be,JWTExpired:()=>sn,JWTInvalid:()=>le});var he,be,sn,nr,k,Ht,R,z,le,di,ir,Mr,pi,hi,Hr,V=I(()=>{he=class extends Error{static{s(this,"JOSEError")}static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var r;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},be=class extends he{static{s(this,"JWTClaimValidationFailed")}static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,r="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},sn=class extends he{static{s(this,"JWTExpired")}static get code(){return"ERR_JWT_EXPIRED"}constructor(e,r="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},nr=class extends he{static{s(this,"JOSEAlgNotAllowed")}constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},k=class extends he{static{s(this,"JOSENotSupported")}constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},Ht=class extends he{static{s(this,"JWEDecryptionFailed")}constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},R=class extends he{static{s(this,"JWEInvalid")}constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},z=class extends he{static{s(this,"JWSInvalid")}constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},le=class extends he{static{s(this,"JWTInvalid")}constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},di=class extends he{static{s(this,"JWKInvalid")}constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},ir=class extends he{static{s(this,"JWKSInvalid")}constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Mr=class extends he{static{s(this,"JWKSNoMatchingKey")}constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}},pi=class extends he{static{s(this,"JWKSMultipleMatchingKeys")}constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},hi=class extends he{static{s(this,"JWKSTimeout")}constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},Hr=class extends he{static{s(this,"JWSSignatureVerificationFailed")}constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}});var or,fi=I(()=>{Se();or=D.getRandomValues.bind(D)});function Dl(t){switch(t){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new k(`Unsupported JWE Algorithm: ${t}`)}}var us,ls=I(()=>{V();fi();s(Dl,"bitLength");us=s(t=>or(new Uint8Array(Dl(t)>>3)),"default")});var pI,ds,Ul=I(()=>{V();ls();pI=s((t,e)=>{if(e.length<<3!==Dl(t))throw new R("Invalid Initialization Vector length")},"checkIvLength"),ds=pI});var hI,an,kl=I(()=>{V();hI=s((t,e)=>{let r=t.byteLength<<3;if(r!==e)throw new R(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)},"checkCekLength"),an=hI});var fI,Im,Pm=I(()=>{fI=s((t,e)=>{if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(t.length!==e.length)throw new TypeError("Input buffers must have the same length");let r=t.length,n=0,i=-1;for(;++i<r;)n|=t[i]^e[i];return n===0},"timingSafeEqual"),Im=fI});function Pe(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function sr(t,e){return t.name===e}function ps(t){return parseInt(t.name.slice(4),10)}function mI(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Am(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){let n=e.pop();r+=`one of ${e.join(", ")}, or ${n}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function Rm(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!sr(t.algorithm,"HMAC"))throw Pe("HMAC");let n=parseInt(e.slice(2),10);if(ps(t.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!sr(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Pe("RSASSA-PKCS1-v1_5");let n=parseInt(e.slice(2),10);if(ps(t.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!sr(t.algorithm,"RSA-PSS"))throw Pe("RSA-PSS");let n=parseInt(e.slice(2),10);if(ps(t.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw Pe("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!sr(t.algorithm,"ECDSA"))throw Pe("ECDSA");let n=mI(e);if(t.algorithm.namedCurve!==n)throw Pe(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Am(t,r)}function $e(t,e,...r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!sr(t.algorithm,"AES-GCM"))throw Pe("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Pe(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!sr(t.algorithm,"AES-KW"))throw Pe("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Pe(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw Pe("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!sr(t.algorithm,"PBKDF2"))throw Pe("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!sr(t.algorithm,"RSA-OAEP"))throw Pe("RSA-OAEP");let n=parseInt(e.slice(9),10)||1;if(ps(t.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Am(t,r)}var ar=I(()=>{s(Pe,"unusable");s(sr,"isAlgorithm");s(ps,"getHashLength");s(mI,"getNamedCurve");s(Am,"checkUsage");s(Rm,"checkSigCryptoKey");s($e,"checkEncCryptoKey")});function Om(t,e,...r){if(r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}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&&e.constructor.name&&(t+=` Received an instance of ${e.constructor.name}`),t}function Ml(t,e,...r){return Om(`Key for the ${t} algorithm must be `,e,...r)}var oe,ut=I(()=>{s(Om,"message");oe=s((t,...e)=>Om("Key must be ",t,...e),"default");s(Ml,"withAlg")});var Hl,Q,lt=I(()=>{Se();Hl=s(t=>ae(t),"default"),Q=["CryptoKey"]});async function yI(t,e,r,n,i,o){if(!(e instanceof Uint8Array))throw new TypeError(oe(e,"Uint8Array"));let a=parseInt(t.slice(1,4),10),c=await D.subtle.importKey("raw",e.subarray(a>>3),"AES-CBC",!1,["decrypt"]),u=await D.subtle.importKey("raw",e.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),l=Te(o,n,r,os(o.length<<3)),d=new Uint8Array((await D.subtle.sign("HMAC",u,l)).slice(0,a>>3)),p;try{p=Im(i,d)}catch{}if(!p)throw new Ht;let m;try{m=new Uint8Array(await D.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!m)throw new Ht;return m}async function gI(t,e,r,n,i,o){let a;e instanceof Uint8Array?a=await D.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):($e(e,t,"decrypt"),a=e);try{return new Uint8Array(await D.subtle.decrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,Te(r,i)))}catch{throw new Ht}}var bI,hs,Fl=I(()=>{ge();Ul();kl();Pm();V();Se();ar();ut();lt();s(yI,"cbcDecrypt");s(gI,"gcmDecrypt");bI=s(async(t,e,r,n,i,o)=>{if(!ae(e)&&!(e instanceof Uint8Array))throw new TypeError(oe(e,...Q,"Uint8Array"));switch(ds(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&an(e,parseInt(t.slice(-3),10)),yI(t,e,r,n,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&an(e,parseInt(t.slice(1,4),10)),gI(t,e,r,n,i,o);default:throw new k("Unsupported JWE Content Encryption Algorithm")}},"decrypt"),hs=bI});var Nm,Cm,ql=I(()=>{V();Nm=s(async()=>{throw new k('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},"inflate"),Cm=s(async()=>{throw new k('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')},"deflate")});var _I,vt,cn=I(()=>{_I=s((...t)=>{let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let o of i){if(r.has(o))return!1;r.add(o)}}return!0},"isDisjoint"),vt=_I});function wI(t){return typeof t=="object"&&t!==null}function Y(t){if(!wI(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}var je=I(()=>{s(wI,"isObjectLike");s(Y,"isObject")});var EI,un,$l=I(()=>{EI=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],un=EI});function xm(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function Lm(t,e,r){if(ae(t))return $e(t,e,r),t;if(t instanceof Uint8Array)return D.subtle.importKey("raw",t,"AES-KW",!0,[r]);throw new TypeError(oe(t,...Q,"Uint8Array"))}var mi,yi,fs=I(()=>{$l();Se();ar();ut();lt();s(xm,"checkKeySize");s(Lm,"getCryptoKey");mi=s(async(t,e,r)=>{let n=await Lm(e,t,"wrapKey");xm(n,t);let i=await D.subtle.importKey("raw",r,...un);return new Uint8Array(await D.subtle.wrapKey("raw",i,n,"AES-KW"))},"wrap"),yi=s(async(t,e,r)=>{let n=await Lm(e,t,"unwrapKey");xm(n,t);let i=await D.subtle.unwrapKey("raw",r,n,"AES-KW",...un);return new Uint8Array(await D.subtle.exportKey("raw",i))},"unwrap")});async function ms(t,e,r,n,i=new Uint8Array(0),o=new Uint8Array(0)){if(!ae(t))throw new TypeError(oe(t,...Q));if($e(t,"ECDH"),!ae(e))throw new TypeError(oe(e,...Q));$e(e,"ECDH","deriveBits");let a=Te(as(Z.encode(r)),as(i),as(o),ss(n)),c;t.algorithm.name==="X25519"?c=256:t.algorithm.name==="X448"?c=448:c=Math.ceil(parseInt(t.algorithm.namedCurve.substr(-3),10)/8)<<3;let u=new Uint8Array(await D.subtle.deriveBits({name:t.algorithm.name,public:t},e,c));return Sm(u,n,a)}async function Dm(t){if(!ae(t))throw new TypeError(oe(t,...Q));return D.subtle.generateKey(t.algorithm,!0,["deriveBits"])}function ys(t){if(!ae(t))throw new TypeError(oe(t,...Q));return["P-256","P-384","P-521"].includes(t.algorithm.namedCurve)||t.algorithm.name==="X25519"||t.algorithm.name==="X448"}var jl=I(()=>{ge();Se();ar();ut();lt();s(ms,"deriveKey");s(Dm,"generateEpk");s(ys,"ecdhAllowed")});function Vl(t){if(!(t instanceof Uint8Array)||t.length<8)throw new R("PBES2 Salt Input must be 8 or more octets")}var km=I(()=>{V();s(Vl,"checkP2s")});function vI(t,e){if(t instanceof Uint8Array)return D.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]);if(ae(t))return $e(t,e,"deriveBits","deriveKey"),t;throw new TypeError(oe(t,...Q,"Uint8Array"))}async function Mm(t,e,r,n){Vl(t);let i=vm(e,t),o=parseInt(e.slice(13,16),10),a={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},c={length:o,name:"AES-KW"},u=await vI(n,e);if(u.usages.includes("deriveBits"))return new Uint8Array(await D.subtle.deriveBits(a,u,o));if(u.usages.includes("deriveKey"))return D.subtle.deriveKey(a,u,c,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var Hm,Fm,Gl=I(()=>{fi();ge();Ie();fs();km();Se();ar();ut();lt();s(vI,"getCryptoKey");s(Mm,"deriveKey");Hm=s(async(t,e,r,n=2048,i=or(new Uint8Array(16)))=>{let o=await Mm(i,t,n,e);return{encryptedKey:await mi(t.slice(-6),o,r),p2c:n,p2s:X(i)}},"encrypt"),Fm=s(async(t,e,r,n,i)=>{let o=await Mm(i,t,n,e);return yi(t.slice(-6),o,r)},"decrypt")});function ln(t){switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new k(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var qm=I(()=>{V();s(ln,"subtleRsaEs")});var Fr,gs=I(()=>{Fr=s((t,e)=>{if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}},"default")});var $m,jm,Bl=I(()=>{qm();$l();Se();ar();gs();ut();lt();$m=s(async(t,e,r)=>{if(!ae(e))throw new TypeError(oe(e,...Q));if($e(e,t,"encrypt","wrapKey"),Fr(t,e),e.usages.includes("encrypt"))return new Uint8Array(await D.subtle.encrypt(ln(t),e,r));if(e.usages.includes("wrapKey")){let n=await D.subtle.importKey("raw",r,...un);return new Uint8Array(await D.subtle.wrapKey("raw",n,e,ln(t)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},"encrypt"),jm=s(async(t,e,r)=>{if(!ae(e))throw new TypeError(oe(e,...Q));if($e(e,t,"decrypt","unwrapKey"),Fr(t,e),e.usages.includes("decrypt"))return new Uint8Array(await D.subtle.decrypt(ln(t),e,r));if(e.usages.includes("unwrapKey")){let n=await D.subtle.unwrapKey("raw",r,e,ln(t),...un);return new Uint8Array(await D.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')},"decrypt")});function gi(t){switch(t){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new k(`Unsupported JWE Algorithm: ${t}`)}}var St,bi=I(()=>{V();fi();s(gi,"bitLength");St=s(t=>or(new Uint8Array(gi(t)>>3)),"default")});var Kl,Vm=I(()=>{Kl=s((t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
|
|
57
57
|
`);return`-----BEGIN ${e}-----
|
|
58
58
|
${r}
|
|
59
|
-
-----END ${e}-----`},"default")});function Bm(t){let e=[],r=0;for(;r<t.length;){let n=Ym(t.subarray(r));e.push(n),r+=n.byteLength}return e}function Ym(t){let e=0,r=t[0]&31;if(e++,r===31){for(r=0;t[e]>=128;)r=r*128+t[e]-128,e++;r=r*128+t[e]-128,e++}let n=0;if(t[e]<128)n=t[e],e++;else if(n===128){for(n=0;t[e+n]!==0||t[e+n+1]!==0;){if(n>t.byteLength)throw new TypeError("invalid indefinite form length");n++}let o=e+n+2;return{byteLength:o,contents:t.subarray(e,e+n),raw:t.subarray(0,o)}}else{let o=t[e]&127;e++,n=0;for(let a=0;a<o;a++)n=n*256+t[e],e++}let i=e+n;return{byteLength:i,contents:t.subarray(e,i),raw:t.subarray(0,i)}}function SI(t){let e=Bm(Bm(Ym(t).contents)[0].contents);return cs(e[e[0].raw[0]===160?6:5].raw)}function TI(t){let e=t.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=xl(e);return Kl(SI(r),"PUBLIC KEY")}var Km,Jm,zm,cr,Gm,Wm,Qm,Jl,Zm,bs=I(()=>{Se();ut();Ie();Vm();V();lt();Km=s(async(t,e,r)=>{if(!ae(r))throw new TypeError(oe(r,...Q));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return Kl(cs(new Uint8Array(await D.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},"genericExport"),Jm=s(t=>Km("public","spki",t),"toSPKI"),zm=s(t=>Km("private","pkcs8",t),"toPKCS8"),cr=s((t,e,r=0)=>{r===0&&(e.unshift(e.length),e.unshift(6));let n=t.indexOf(e[0],r);if(n===-1)return!1;let i=t.subarray(n,n+e.length);return i.length!==e.length?!1:i.every((o,a)=>o===e[a])||cr(t,e,n+1)},"findOid"),Gm=s(t=>{switch(!0){case cr(t,[42,134,72,206,61,3,1,7]):return"P-256";case cr(t,[43,129,4,0,34]):return"P-384";case cr(t,[43,129,4,0,35]):return"P-521";case cr(t,[43,101,110]):return"X25519";case cr(t,[43,101,111]):return"X448";case cr(t,[43,101,112]):return"Ed25519";case cr(t,[43,101,113]):return"Ed448";default:throw new k("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),Wm=s(async(t,e,r,n,i)=>{var o;let a,c,u=new Uint8Array(atob(r.replace(t,"")).split("").map(d=>d.charCodeAt(0))),l=e==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},c=l?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},c=l?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},c=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=Gm(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:Gm(u)},c=l?["verify"]:["sign"];break;default:throw new k('Invalid or unsupported "alg" (Algorithm) value')}return D.subtle.importKey(e,u,a,(o=i?.extractable)!==null&&o!==void 0?o:!1,c)},"genericImport"),Qm=s((t,e,r)=>Wm(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,e,r),"fromPKCS8"),Jl=s((t,e,r)=>Wm(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",t,e,r),"fromSPKI");s(Bm,"getElement");s(Ym,"parseElement");s(SI,"spkiFromX509");s(TI,"getSPKI");Zm=s((t,e,r)=>{let n;try{n=TI(t)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return Jl(n,e,r)},"fromX509")});function II(t){let e,r;switch(t.kty){case"oct":{switch(t.alg){case"HS256":case"HS384":case"HS512":e={name:"HMAC",hash:`SHA-${t.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new k(`${t.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":e={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":e={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":e={name:"PBKDF2"},r=["deriveBits"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new k('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var PI,zl,Xm=I(()=>{Se();V();Ie();s(II,"subtleMapping");PI=s(async t=>{var e,r;if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=II(t),o=[n,(e=t.ext)!==null&&e!==void 0?e:!1,(r=t.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return D.subtle.importKey("raw",re(t.k),...o);let a={...t};return delete a.alg,delete a.use,D.subtle.importKey("jwk",a,...o)},"parse"),zl=PI});async function ey(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Jl(t,e,r)}async function ty(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Zm(t,e,r)}async function ry(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Qm(t,e,r)}async function ur(t,e,r){var n;if(!Y(t))throw new TypeError("JWK must be an object");switch(e||(e=t.alg),t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=t.ext!==!0),r?zl({...t,alg:e,ext:(n=t.ext)!==null&&n!==void 0?n:!1}):re(t.k);case"RSA":if(t.oth!==void 0)throw new k('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return zl({...t,alg:e});default:throw new k('Unsupported "kty" (Key Type) Parameter value')}}var _i=I(()=>{Ie();bs();Xm();V();je();s(ey,"importSPKI");s(ty,"importX509");s(ry,"importPKCS8");s(ur,"importJWK")});var AI,RI,OI,lr,wi=I(()=>{ut();lt();AI=s((t,e)=>{if(!(e instanceof Uint8Array)){if(!Hl(e))throw new TypeError(Ml(t,e,...Q,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Q.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),RI=s((t,e,r)=>{if(!Hl(e))throw new TypeError(Ml(t,e,...Q));if(e.type==="secret")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),OI=s((t,e,r)=>{t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?AI(t,e):RI(t,e,r)},"checkKeyType"),lr=OI});async function NI(t,e,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(oe(r,"Uint8Array"));let o=parseInt(t.slice(1,4),10),a=await D.subtle.importKey("raw",r.subarray(o>>3),"AES-CBC",!1,["encrypt"]),c=await D.subtle.importKey("raw",r.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await D.subtle.encrypt({iv:n,name:"AES-CBC"},a,e)),l=Te(i,n,u,os(i.length<<3)),d=new Uint8Array((await D.subtle.sign("HMAC",c,l)).slice(0,o>>3));return{ciphertext:u,tag:d}}async function CI(t,e,r,n,i){let o;r instanceof Uint8Array?o=await D.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($e(r,t,"encrypt"),o=r);let a=new Uint8Array(await D.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},o,e)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var xI,Ei,Wl=I(()=>{ge();Ul();kl();Se();ar();ut();V();lt();s(NI,"cbcEncrypt");s(CI,"gcmEncrypt");xI=s(async(t,e,r,n,i)=>{if(!ae(r)&&!(r instanceof Uint8Array))throw new TypeError(oe(r,...Q,"Uint8Array"));switch(ds(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&an(r,parseInt(t.slice(-3),10)),NI(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&an(r,parseInt(t.slice(1,4),10)),CI(t,e,r,n,i);default:throw new k("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),Ei=xI});async function ny(t,e,r,n){let i=t.slice(0,7);n||(n=us(i));let{ciphertext:o,tag:a}=await Ei(i,r,e,n,new Uint8Array(0));return{encryptedKey:o,iv:X(n),tag:X(a)}}async function iy(t,e,r,n,i){let o=t.slice(0,7);return hs(o,e,r,n,i,new Uint8Array(0))}var Ql=I(()=>{Wl();Fl();ls();Ie();s(ny,"wrap");s(iy,"unwrap")});async function LI(t,e,r,n,i){switch(lr(t,e,"decrypt"),t){case"dir":{if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Y(n.epk))throw new R('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!ys(e))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await ur(n.epk,t),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new R('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=re(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new R('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=re(n.apv)}let u=await ms(o,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?gi(n.enc):parseInt(t.slice(-5,-2),10),a,c);if(t==="ECDH-ES")return u;if(r===void 0)throw new R("JWE Encrypted Key missing");return yi(t.slice(-6),u,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new R("JWE Encrypted Key missing");return jm(t,e,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new R('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new R('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new R('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return Fm(t,e,r,n.p2c,re(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");return yi(t,e,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new R('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new R('JOSE Header "tag" (Authentication Tag) missing or invalid');let o=re(n.iv),a=re(n.tag);return iy(t,e,r,o,a)}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var oy,sy=I(()=>{fs();jl();Gl();Bl();Ie();V();bi();_i();wi();je();Ql();s(LI,"decryptKeyManagement");oy=LI});function DI(t,e,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...e.entries()]):o=e;for(let a of n.crit){if(!o.has(a))throw new k(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new t(`Extension Header Parameter "${a}" is missing`);if(o.get(a)&&n[a]===void 0)throw new t(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var Tt,dn=I(()=>{V();s(DI,"validateCrit");Tt=DI});var UI,vi,Yl=I(()=>{UI=s((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`);if(e)return new Set(e)},"validateAlgorithms"),vi=UI});async function pn(t,e,r){var n;if(!Y(t))throw new R("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new R("JOSE Header missing");if(typeof t.iv!="string")throw new R("JWE Initialization Vector missing or incorrect type");if(typeof t.ciphertext!="string")throw new R("JWE Ciphertext missing or incorrect type");if(typeof t.tag!="string")throw new R("JWE Authentication Tag missing or incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new R("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new R("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new R("JWE AAD incorrect type");if(t.header!==void 0&&!Y(t.header))throw new R("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!Y(t.unprotected))throw new R("JWE Per-Recipient Unprotected Header incorrect type");let i;if(t.protected)try{let j=re(t.protected);i=JSON.parse(ue.decode(j))}catch{throw new R("JWE Protected Header is invalid")}if(!vt(i,t.header,t.unprotected))throw new R("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...i,...t.header,...t.unprotected};if(Tt(R,new Map,r?.crit,i,o),o.zip!==void 0){if(!i||!i.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(o.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=o;if(typeof a!="string"||!a)throw new R("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new R("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&vi("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&vi("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new nr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new nr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;t.encrypted_key!==void 0&&(d=re(t.encrypted_key));let p=!1;typeof e=="function"&&(e=await e(i,t),p=!0);let m;try{m=await oy(a,e,d,o,r)}catch(j){if(j instanceof TypeError||j instanceof R||j instanceof k)throw j;m=St(c)}let h=re(t.iv),g=re(t.tag),_=Z.encode((n=t.protected)!==null&&n!==void 0?n:""),S;t.aad!==void 0?S=Te(_,Z.encode("."),Z.encode(t.aad)):S=_;let T=await hs(c,m,re(t.ciphertext),h,g,S);o.zip==="DEF"&&(T=await(r?.inflateRaw||Nm)(T));let M={plaintext:T};return t.protected!==void 0&&(M.protectedHeader=i),t.aad!==void 0&&(M.additionalAuthenticatedData=re(t.aad)),t.unprotected!==void 0&&(M.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(M.unprotectedHeader=t.header),p?{...M,key:e}:M}var _s=I(()=>{Ie();Fl();ql();V();cn();je();sy();ge();bi();dn();Yl();s(pn,"flattenedDecrypt")});async function ws(t,e,r){if(t instanceof Uint8Array&&(t=ue.decode(t)),typeof t!="string")throw new R("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:o,3:a,4:c,length:u}=t.split(".");if(u!==5)throw new R("Invalid Compact JWE");let l=await pn({ciphertext:a,iv:o||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},e,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...d,key:l.key}:d}var Zl=I(()=>{_s();V();ge();s(ws,"compactDecrypt")});async function ay(t,e,r){if(!Y(t))throw new R("General JWE must be an object");if(!Array.isArray(t.recipients)||!t.recipients.every(Y))throw new R("JWE Recipients missing or incorrect type");if(!t.recipients.length)throw new R("JWE Recipients has no members");for(let n of t.recipients)try{return await pn({aad:t.aad,ciphertext:t.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:t.iv,protected:t.protected,tag:t.tag,unprotected:t.unprotected},e,r)}catch{}throw new Ht}var cy=I(()=>{_s();V();je();s(ay,"generalDecrypt")});var kI,uy,ly=I(()=>{Se();ut();Ie();lt();kI=s(async t=>{if(t instanceof Uint8Array)return{kty:"oct",k:X(t)};if(!ae(t))throw new TypeError(oe(t,...Q,"Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...o}=await D.subtle.exportKey("jwk",t);return o},"keyToJWK"),uy=kI});async function dy(t){return Jm(t)}async function py(t){return zm(t)}async function Es(t){return uy(t)}var Xl=I(()=>{bs();bs();ly();s(dy,"exportSPKI");s(py,"exportPKCS8");s(Es,"exportJWK")});async function MI(t,e,r,n,i={}){let o,a,c;switch(lr(t,r,"encrypt"),t){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!ys(r))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:u,apv:l}=i,{epk:d}=i;d||(d=(await Dm(r)).privateKey);let{x:p,y:m,crv:h,kty:g}=await Es(d),_=await ms(r,d,t==="ECDH-ES"?e:t,t==="ECDH-ES"?gi(e):parseInt(t.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:g}},g==="EC"&&(a.epk.y=m),u&&(a.apu=X(u)),l&&(a.apv=X(l)),t==="ECDH-ES"){c=_;break}c=n||St(e);let S=t.slice(-6);o=await mi(S,_,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||St(e),o=await $m(t,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||St(e);let{p2c:u,p2s:l}=i;({encryptedKey:o,...a}=await Hm(t,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||St(e),o=await mi(t,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||St(e);let{iv:u}=i;({encryptedKey:o,...a}=await ny(t,r,c,u));break}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:o,parameters:a}}var vs,ed=I(()=>{fs();jl();Gl();Bl();Ie();bi();V();Xl();wi();Ql();s(MI,"encryptKeyManagement");vs=MI});var td,Ft,Ss=I(()=>{Ie();Wl();ql();ls();ed();V();cn();ge();dn();td=Symbol(),Ft=class{static{s(this,"FlattenedEncrypt")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new R("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!vt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(Tt(R,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:o}=n;if(typeof i!="string"||!i)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(i==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(i==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let c;{let g;({cek:c,encryptedKey:a,parameters:g}=await vs(i,o,e,this._cek,this._keyManagementParameters)),g&&(r&&td in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...g}:this.setUnprotectedHeader(g):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...g}:this.setProtectedHeader(g))}this._iv||(this._iv=us(o));let u,l,d;this._protectedHeader?l=Z.encode(X(JSON.stringify(this._protectedHeader))):l=Z.encode(""),this._aad?(d=X(this._aad),u=Te(l,Z.encode("."),Z.encode(d))):u=l;let p,m;if(n.zip==="DEF"){let g=await(r?.deflateRaw||Cm)(this._plaintext);({ciphertext:p,tag:m}=await Ei(o,g,c,this._iv,u))}else({ciphertext:p,tag:m}=await Ei(o,this._plaintext,c,this._iv,u));let h={ciphertext:X(p),iv:X(this._iv),tag:X(m)};return a&&(h.encrypted_key=X(a)),d&&(h.aad=d),this._protectedHeader&&(h.protected=ue.decode(l)),this._sharedUnprotectedHeader&&(h.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(h.header=this._unprotectedHeader),h}}});var rd,Ts,hy=I(()=>{Ss();V();bi();cn();ed();Ie();dn();rd=class{static{s(this,"IndividualRecipient")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}},Ts=class{static{s(this,"GeneralEncrypt")}constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,r){let n=new rd(this,e,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var r,n,i;if(!this._recipients.length)throw new R("at least one recipient must be added");if(e={deflateRaw:e?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Ft(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...e}),d={ciphertext:l.ciphertext,iv:l.iv,recipients:[{}],tag:l.tag};return l.aad&&(d.aad=l.aad),l.protected&&(d.protected=l.protected),l.unprotected&&(d.unprotected=l.unprotected),l.encrypted_key&&(d.recipients[0].encrypted_key=l.encrypted_key),l.header&&(d.recipients[0].header=l.header),d}let o;for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u];if(!vt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let d={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader},{alg:p}=d;if(typeof p!="string"||!p)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new R('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!o)o=d.enc;else if(o!==d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(Tt(R,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=St(o),c={ciphertext:"",iv:"",recipients:[],tag:""};for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u],d={};c.recipients.push(d);let m={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let _=await new Ft(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:m}).encrypt(l.key,{...l.options,...e,[td]:!0});c.ciphertext=_.ciphertext,c.iv=_.iv,c.tag=_.tag,_.aad&&(c.aad=_.aad),_.protected&&(c.protected=_.protected),_.unprotected&&(c.unprotected=_.unprotected),d.encrypted_key=_.encrypted_key,_.header&&(d.header=_.header);continue}let{encryptedKey:h,parameters:g}=await vs(((r=l.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((i=this._unprotectedHeader)===null||i===void 0?void 0:i.alg),o,l.key,a,{p2c:m});d.encrypted_key=X(h),(l.unprotectedHeader||g)&&(d.header={...l.unprotectedHeader,...g})}return c}}});function Si(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"EdDSA":return{name:e.name};default:throw new k(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var nd=I(()=>{V();s(Si,"subtleDsa")});function Ti(t,e,r){if(ae(e))return Rm(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(oe(e,...Q));return D.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(oe(e,...Q,"Uint8Array"))}var id=I(()=>{Se();ar();ut();lt();s(Ti,"getCryptoKey")});var HI,fy,my=I(()=>{nd();Se();gs();id();HI=s(async(t,e,r,n)=>{let i=await Ti(t,e,"verify");Fr(t,i);let o=Si(t,i.algorithm);try{return await D.subtle.verify(o,i,r,n)}catch{return!1}},"verify"),fy=HI});async function hn(t,e,r){var n;if(!Y(t))throw new z("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new z("JWS Protected Header incorrect type");if(t.payload===void 0)throw new z("JWS Payload missing");if(typeof t.signature!="string")throw new z("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Y(t.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(t.protected)try{let S=re(t.protected);i=JSON.parse(ue.decode(S))}catch{throw new z("JWS Protected Header is invalid")}if(!vt(i,t.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...i,...t.header},a=Tt(z,new Map([["b64",!0]]),r?.crit,i,o),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=o;if(typeof u!="string"||!u)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&vi("algorithms",r.algorithms);if(l&&!l.has(u))throw new nr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof t.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof e=="function"&&(e=await e(i,t),d=!0),lr(u,e,"verify");let p=Te(Z.encode((n=t.protected)!==null&&n!==void 0?n:""),Z.encode("."),typeof t.payload=="string"?Z.encode(t.payload):t.payload),m=re(t.signature);if(!await fy(u,e,m,p))throw new Hr;let g;c?g=re(t.payload):typeof t.payload=="string"?g=Z.encode(t.payload):g=t.payload;let _={payload:g};return t.protected!==void 0&&(_.protectedHeader=i),t.header!==void 0&&(_.unprotectedHeader=t.header),d?{..._,key:e}:_}var Is=I(()=>{Ie();my();V();ge();cn();je();wi();dn();Yl();s(hn,"flattenedVerify")});async function Ps(t,e,r){if(t instanceof Uint8Array&&(t=ue.decode(t)),typeof t!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:o,length:a}=t.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await hn({payload:i,protected:n,signature:o},e,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof e=="function"?{...u,key:c.key}:u}var od=I(()=>{Is();V();ge();s(Ps,"compactVerify")});async function yy(t,e,r){if(!Y(t))throw new z("General JWS must be an object");if(!Array.isArray(t.signatures)||!t.signatures.every(Y))throw new z("JWS Signatures missing or incorrect type");for(let n of t.signatures)try{return await hn({header:n.header,payload:t.payload,protected:n.protected,signature:n.signature},e,r)}catch{}throw new Hr}var gy=I(()=>{Is();V();je();s(yy,"generalVerify")});var fn,sd=I(()=>{fn=s(t=>Math.floor(t.getTime()/1e3),"default")});var FI,mn,ad=I(()=>{FI=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,mn=s(t=>{let e=FI.exec(t);if(!e)throw new TypeError("Invalid time period format");let r=parseFloat(e[1]);switch(e[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}},"default")});var by,qI,yn,As=I(()=>{V();ge();sd();ad();je();by=s(t=>t.toLowerCase().replace(/^application\//,""),"normalizeTyp"),qI=s((t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1,"checkAudiencePresence"),yn=s((t,e,r={})=>{let{typ:n}=r;if(n&&(typeof t.typ!="string"||by(t.typ)!==by(n)))throw new be('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ue.decode(e))}catch{}if(!Y(i))throw new le("JWT Claims Set must be a top-level JSON object");let{requiredClaims:o=[],issuer:a,subject:c,audience:u,maxTokenAge:l}=r;l!==void 0&&o.push("iat"),u!==void 0&&o.push("aud"),c!==void 0&&o.push("sub"),a!==void 0&&o.push("iss");for(let h of new Set(o.reverse()))if(!(h in i))throw new be(`missing required "${h}" claim`,h,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new be('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new be('unexpected "sub" claim value',"sub","check_failed");if(u&&!qI(i.aud,typeof u=="string"?[u]:u))throw new be('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=mn(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,m=fn(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new be('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new be('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>m+d)throw new be('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new be('"exp" claim must be a number',"exp","invalid");if(i.exp<=m-d)throw new sn('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=m-i.iat,g=typeof l=="number"?l:mn(l);if(h-d>g)throw new sn('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(h<0-d)throw new be('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function _y(t,e,r){var n;let i=await Ps(t,e,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new le("JWTs MUST NOT use unencoded payload");let a={payload:yn(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof e=="function"?{...a,key:i.key}:a}var wy=I(()=>{od();As();V();s(_y,"jwtVerify")});async function Ey(t,e,r){let n=await ws(t,e,r),i=yn(n.protectedHeader,n.plaintext,r),{protectedHeader:o}=n;if(o.iss!==void 0&&o.iss!==i.iss)throw new be('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(o.sub!==void 0&&o.sub!==i.sub)throw new be('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(o.aud!==void 0&&JSON.stringify(o.aud)!==JSON.stringify(i.aud))throw new be('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:o};return typeof e=="function"?{...a,key:n.key}:a}var vy=I(()=>{Zl();As();V();s(Ey,"jwtDecrypt")});var gn,cd=I(()=>{Ss();gn=class{static{s(this,"CompactEncrypt")}constructor(e){this._flattened=new Ft(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this._flattened.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var $I,Sy,Ty=I(()=>{nd();Se();gs();id();$I=s(async(t,e,r)=>{let n=await Ti(t,e,"sign");Fr(t,n);let i=await D.subtle.sign(Si(t,n.algorithm),n,r);return new Uint8Array(i)},"sign"),Sy=$I});var dr,Rs=I(()=>{Ie();Ty();cn();V();ge();wi();dn();dr=class{static{s(this,"FlattenedSign")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!vt(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=Tt(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(i.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');lr(a,e,"sign");let c=this._payload;o&&(c=Z.encode(X(c)));let u;this._protectedHeader?u=Z.encode(X(JSON.stringify(this._protectedHeader))):u=Z.encode("");let l=Te(u,Z.encode("."),c),d=await Sy(a,e,l),p={signature:X(d),payload:""};return o&&(p.payload=ue.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ue.decode(u)),p}}});var bn,ud=I(()=>{Rs();bn=class{static{s(this,"CompactSign")}constructor(e){this._flattened=new dr(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var ld,Os,Iy=I(()=>{Rs();V();ld=class{static{s(this,"IndividualSignature")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setProtectedHeader(e){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=e,this}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addSignature(...e){return this.parent.addSignature(...e)}sign(...e){return this.parent.sign(...e)}done(){return this.parent}},Os=class{static{s(this,"GeneralSign")}constructor(e){this._signatures=[],this._payload=e}addSignature(e,r){let n=new ld(this,e,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("at least one signature must be added");let e={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new dr(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:o,...a}=await i.sign(n.key,n.options);if(r===0)e.payload=o;else if(e.payload!==o)throw new z("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(a)}return e}}});var pr,Ns=I(()=>{sd();je();ad();pr=class{static{s(this,"ProduceJWT")}constructor(e){if(!Y(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:e}:this._payload={...this._payload,nbf:fn(new Date)+mn(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:fn(new Date)+mn(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:fn(new Date)}:this._payload={...this._payload,iat:e},this}}});var Cs,Py=I(()=>{ud();V();ge();Ns();Cs=class extends pr{static{s(this,"SignJWT")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var n;let i=new bn(Z.encode(JSON.stringify(this._payload)));if(i.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new le("JWTs MUST NOT use unencoded payload");return i.sign(e,r)}}});var xs,Ay=I(()=>{cd();ge();Ns();xs=class extends pr{static{s(this,"EncryptJWT")}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(e,r){let n=new gn(Z.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(e,r)}}});async function dd(t,e){if(!Y(t))throw new TypeError("JWK must be an object");if(e??(e="sha256"),e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(t.kty){case"EC":hr(t.crv,'"crv" (Curve) Parameter'),hr(t.x,'"x" (X Coordinate) Parameter'),hr(t.y,'"y" (Y Coordinate) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":hr(t.crv,'"crv" (Subtype of Key Pair) Parameter'),hr(t.x,'"x" (Public Key) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":hr(t.e,'"e" (Exponent) Parameter'),hr(t.n,'"n" (Modulus) Parameter'),r={e:t.e,kty:t.kty,n:t.n};break;case"oct":hr(t.k,'"k" (Key Value) Parameter'),r={k:t.k,kty:t.kty};break;default:throw new k('"kty" (Key Type) Parameter missing or unsupported')}let n=Z.encode(JSON.stringify(r));return X(await ns(e,n))}async function Ry(t,e){e??(e="sha256");let r=await dd(t,e);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${e.slice(-3)}:${r}`}var hr,Oy=I(()=>{Nl();Ie();V();ge();je();hr=s((t,e)=>{if(typeof t!="string"||!t)throw new di(`${e} missing or invalid`)},"check");s(dd,"calculateJwkThumbprint");s(Ry,"calculateJwkThumbprintUri")});async function Ny(t,e){let r={...t,...e?.header};if(!Y(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await ur({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new z('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var Cy=I(()=>{_i();je();V();s(Ny,"EmbeddedJWK")});function jI(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new k('Unsupported "alg" value for a JSON Web Key Set')}}function pd(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(VI)}function VI(t){return Y(t)}function GI(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}async function xy(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await ur({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new ir("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function Ly(t){let e=new Ii(t);return async function(r,n){return e.getKey(r,n)}}var Ii,hd=I(()=>{_i();V();je();s(jI,"getKtyFromAlg");s(pd,"isJWKSLike");s(VI,"isJWKLike");s(GI,"clone");Ii=class{static{s(this,"LocalJWKSet")}constructor(e){if(this._cached=new WeakMap,!pd(e))throw new ir("JSON Web Key Set malformed");this._jwks=GI(e)}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},o=jI(n),a=this._jwks.keys.filter(l=>{let d=o===l.kty;if(d&&typeof i=="string"&&(d=i===l.kid),d&&typeof l.alg=="string"&&(d=n===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d&&n==="EdDSA"&&(d=l.crv==="Ed25519"||l.crv==="Ed448"),d)switch(n){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break}return d}),{0:c,length:u}=a;if(u===0)throw new Mr;if(u!==1){let l=new pi,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await xy(d,p,n)}catch{continue}},l}return xy(this._cached,c,n)}};s(xy,"importWithAlgCache");s(Ly,"createLocalJWKSet")});var BI,Dy,Uy=I(()=>{V();BI=s(async(t,e,r)=>{let n,i,o=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{o=!0,n.abort()},e));let a=await fetch(t.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw o?new hi:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new he("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new he("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),Dy=BI});function KI(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function ky(t,e){let r=new fd(t,e);return async function(n,i){return r.getKey(n,i)}}var fd,My=I(()=>{Uy();V();hd();s(KI,"isCloudflareWorkers");fd=class extends Ii{static{s(this,"RemoteJWKSet")}constructor(e,r){if(super({keys:[]}),this._jwks=void 0,!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(e,r)}catch(n){if(n instanceof Mr&&this.coolingDown()===!1)return await this.reload(),super.getKey(e,r);throw n}}async reload(){this._pendingFetch&&KI()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=Dy(this._url,this._timeoutDuration,this._options).then(e=>{if(!pd(e))throw new ir("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}};s(ky,"createRemoteJWKSet")});var Ls,Hy=I(()=>{Ie();ge();V();As();Ns();Ls=class extends pr{static{s(this,"UnsecuredJWT")}encode(){let e=X(JSON.stringify({alg:"none"})),r=X(JSON.stringify(this._payload));return`${e}.${r}.`}static decode(e,r){if(typeof e!="string")throw new le("Unsecured JWT must be a string");let{0:n,1:i,2:o,length:a}=e.split(".");if(a!==3||o!=="")throw new le("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ue.decode(re(n))),c.alg!=="none")throw new Error}catch{throw new le("Invalid Unsecured JWT")}return{payload:yn(c,re(i),r),header:c}}}});var md={};co(md,{decode:()=>Pi,encode:()=>JI});var JI,Pi,Ds=I(()=>{Ie();JI=X,Pi=re});function Fy(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(ue.decode(Pi(e)));if(!Y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var qy=I(()=>{Ds();ge();je();s(Fy,"decodeProtectedHeader")});function $y(t){if(typeof t!="string")throw new le("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new le("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new le("Invalid JWT");if(!e)throw new le("JWTs must contain a payload");let n;try{n=Pi(e)}catch{throw new le("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ue.decode(n))}catch{throw new le("Failed to parse the decoded payload as JSON")}if(!Y(i))throw new le("Invalid JWT Claims Set");return i}var jy=I(()=>{Ds();ge();je();V();s($y,"decodeJwt")});async function Vy(t,e){var r;let n,i,o;switch(t){case"HS256":case"HS384":case"HS512":n=parseInt(t.slice(-3),10),i={name:"HMAC",hash:`SHA-${n}`,length:n},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(t.slice(-3),10),or(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(t.slice(1,4),10),i={name:"AES-KW",length:n},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(t.slice(1,4),10),i={name:"AES-GCM",length:n},o=["encrypt","decrypt"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(i,(r=e?.extractable)!==null&&r!==void 0?r:!1,o)}function yd(t){var e;let r=(e=t?.modulusLength)!==null&&e!==void 0?e:2048;if(typeof r!="number"||r<2048)throw new k("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function Gy(t,e){var r,n,i;let o,a;switch(t){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:yd(e)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:yd(e)},a=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(t.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:yd(e)},a=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},a=["sign","verify"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},a=["sign","verify"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},a=["sign","verify"];break;case"EdDSA":a=["sign","verify"];let c=(r=e?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":o={name:c};break;default:throw new k("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{a=["deriveKey","deriveBits"];let u=(n=e?.crv)!==null&&n!==void 0?n:"P-256";switch(u){case"P-256":case"P-384":case"P-521":{o={name:"ECDH",namedCurve:u};break}case"X25519":case"X448":o={name:u};break;default:throw new k("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(o,(i=e?.extractable)!==null&&i!==void 0?i:!1,a)}var gd=I(()=>{Se();V();fi();s(Vy,"generateSecret");s(yd,"getModulusLengthOption");s(Gy,"generateKeyPair")});async function By(t,e){return Gy(t,e)}var Ky=I(()=>{gd();s(By,"generateKeyPair")});async function Jy(t,e){return Vy(t,e)}var zy=I(()=>{gd();s(Jy,"generateSecret")});var Us={};co(Us,{CompactEncrypt:()=>gn,CompactSign:()=>bn,EmbeddedJWK:()=>Ny,EncryptJWT:()=>xs,FlattenedEncrypt:()=>Ft,FlattenedSign:()=>dr,GeneralEncrypt:()=>Ts,GeneralSign:()=>Os,SignJWT:()=>Cs,UnsecuredJWT:()=>Ls,base64url:()=>md,calculateJwkThumbprint:()=>dd,calculateJwkThumbprintUri:()=>Ry,compactDecrypt:()=>ws,compactVerify:()=>Ps,createLocalJWKSet:()=>Ly,createRemoteJWKSet:()=>ky,decodeJwt:()=>$y,decodeProtectedHeader:()=>Fy,errors:()=>Ll,exportJWK:()=>Es,exportPKCS8:()=>py,exportSPKI:()=>dy,flattenedDecrypt:()=>pn,flattenedVerify:()=>hn,generalDecrypt:()=>ay,generalVerify:()=>yy,generateKeyPair:()=>By,generateSecret:()=>Jy,importJWK:()=>ur,importPKCS8:()=>ry,importSPKI:()=>ey,importX509:()=>ty,jwtDecrypt:()=>Ey,jwtVerify:()=>_y});var ks=I(()=>{Zl();_s();cy();hy();od();Is();gy();wy();vy();cd();Ss();ud();Rs();Iy();Py();Ay();Oy();Cy();hd();My();Hy();Xl();_i();qy();jy();V();Ky();zy();Ds()});var _n=y(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.fetchRetry=void 0;var zI=O();async function WI(t,e,r){for(let n=0;n<=t.retries;n++){let i=fetch(e,r);if(n===t.retries)return i;let o=await i;if(o.status<500&&o.status!==429)return o;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:o.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,n)))}throw new zI.ConfigurationError("An unknown error occurred, ensure retries is not negative")}s(WI,"fetchRetry");Ms.fetchRetry=WI});var wn=y(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.GcpServiceAccount=et.fetchToken=et.exchangeGgpJwtForIdToken=et.exchangeFirebaseJwtForIdToken=et.getTokenFromGcpServiceAccount=void 0;var Wy=(ks(),uo(Us)),QI=O(),YI=_n();async function ZI({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:o,privateKey:a}=t;return await new Wy.SignJWT(n).setProtectedHeader({alg:"RS256",kid:o}).setIssuer(i).setSubject(i).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}s(ZI,"getTokenFromGcpServiceAccount");et.getTokenFromGcpServiceAccount=ZI;async function XI(t,e,r){return _d(t,{token:e,returnSecureToken:!0},r)}s(XI,"exchangeFirebaseJwtForIdToken");et.exchangeFirebaseJwtForIdToken=XI;async function eP(t,e,r){return _d(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}s(eP,"exchangeGgpJwtForIdToken");et.exchangeGgpJwtForIdToken=eP;async function _d(t,e,r){let n=await(0,YI.fetchRetry)(r,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(n.status!==200){let o;try{let a=await n.text(),c=JSON.parse(a);o={cause:c.error??c}}catch{}throw new QI.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:o})}return await n.json()}s(_d,"fetchToken");et.fetchToken=_d;var bd=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:r}){this.#t=e,this.#e=r}static async init(e){let r=JSON.parse(e),n=await(0,Wy.importPKCS8)(r.private_key.trim(),"RS256");return new t({serviceAccount:r,privateKey:n})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};et.GcpServiceAccount=bd});var Fs=y(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.GoogleLogTransport=qt.ZuploToGCPMap=qt.GoogleCloudLoggingPlugin=void 0;var tP=O(),rP=ve(),wd=W(),Ed=wn(),nP=Mt(),Qy=Et(),vd=class extends nP.LogPlugin{static{s(this,"GoogleCloudLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Hs(this.options)}};qt.GoogleCloudLoggingPlugin=vd;var iP="https://logging.googleapis.com/v2/entries:write?alt=json";qt.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var Hs=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#r=e.logName,this.#e=e.serviceAccountJson,this.#i=wd.Environment.instance.loggingEnvironmentType,this.#o=wd.Environment.instance.loggingEnvironmentStage,this.#n=wd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async init(){this.#t=await Ed.GcpServiceAccount.init(this.#e)}log(e,r){if(!this.#t)throw new tP.SystemError("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n={allMessages:(0,Qy.makeErrorsSerializable)(e.messages)},i=this.#t.projectId??"zuplo-production",o={logName:this.#r,resource:{type:"global"},severity:qt.ZuploToGCPMap[e.level],timestamp:e.timestamp,trace:`projects/${i}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};e.rayId&&(o.labels.rayId=e.rayId);let a=(0,Qy.extractBestMessage)(n.allMessages);o.jsonPayload={...n,message:a},this.batcher.enqueue(o),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Ed.GcpServiceAccount.init(this.#e));let r=await(0,Ed.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(iP,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new rP.BatchDispatch("google-log-transport",1,this.dispatchFunction)};qt.GoogleLogTransport=Hs});var Sd=y(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.gcpLogFormat=En.GCP_LOG_FORMAT=void 0;var Yy=Et(),oP=Fs();En.GCP_LOG_FORMAT="gcp";function sP(t){let e={allMessages:(0,Yy.makeErrorsSerializable)(t.messages)},r="zuplo-production",n=(0,Yy.extractBestMessage)(e.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:oP.ZuploToGCPMap[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(i["logging.googleapis.com/labels"].rayId=t.rayId),i}s(sP,"gcpLogFormat");En.gcpLogFormat=sP});var Xy=y(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.ConsoleTransport=void 0;var Zy=Sd(),Td=class{static{s(this,"ConsoleTransport")}constructor(e,r){this.#e=e??console,this.#t=r}#e;#t;log(e){if(this.#t===Zy.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Zy.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};qs.ConsoleTransport=Td});var Nd=y(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.DataDogTransport=vn.DataDogLoggingPlugin=void 0;var aP=ve(),Id=W(),cP=Mt(),eg=Et(),Od=class extends cP.LogPlugin{static{s(this,"DataDogLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new $s(this.options)}};vn.DataDogLoggingPlugin=Od;var Pd="__ddtags",Ad="__ddattr",Rd=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),uP=s(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let i=t[n];i==null?r.push(Rd(n)):r.push(`${Rd(n)}:${Rd(i.toString())}`)}),r.join(",")},"formatTags"),$s=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=Id.Environment.instance.loggingEnvironmentType,this.#i=Id.Environment.instance.loggingEnvironmentStage,this.#r=Id.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){let n={},i=r.custom[Pd];i&&typeof i=="object"&&Object.assign(n,i);let o=[...e.messages],a=e.messages.findIndex(h=>h[Pd]!==void 0);a>-1&&(Object.assign(n,o[a][Pd]),o.splice(a,1));let c={},u=r.custom[Ad];u&&typeof u=="object"&&Object.assign(c,u);let l=e.messages.findIndex(h=>h[Ad]!==void 0);l>-1&&(Object.assign(c,o[l][Ad]),o.splice(l,1));let d=(0,eg.makeErrorsSerializable)(o),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,eg.extractBestMessage)(d),service:e.loggingId,ddtags:uP(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(m,c),this.batcher.enqueue(m),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new aP.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};vn.DataDogTransport=$s});var rg=y(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.ProcessTransport=void 0;var tg=Sd(),Cd=class{static{s(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;log(e){if(this.#t===tg.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,tg.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};js.ProcessTransport=Cd});var ig=y(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.RemoteLogTransport=void 0;var lP=ve(),ng=W(),dP=Et(),pP=s(({url:t,remoteLogToken:e,loggingId:r,sendOnlyErrors:n})=>async i=>{let o;if(n===!0?o=i.filter(a=>a.level==="error"):o=i,o.length!==0)try{await fetch(`${t}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(a=>({...a,messages:(0,dP.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":ng.Environment.instance.systemUserAgent,"zp-dn":ng.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Vs,xd=class{static{s(this,"RemoteLogTransport")}constructor(e){Vs||(Vs=new lP.BatchDispatch("remote-log-transport",1,pP(e)))}log(e,r){Vs.enqueue(e),r.waitUntil(Vs.waitUntilFlushed())}};Gs.RemoteLogTransport=xd});var og=y(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.unifiedFormatter=qr.SeverityNumberOpenTelemetryMap=void 0;qr.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var hP=s((t,e)=>r=>{let n={};return n.deploymentName=t,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:qr.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");qr.unifiedFormatter=hP});var ag=y(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.UnifiedLogTransport=void 0;var fP=ve(),sg=W(),mP=og(),yP=s(({url:t,remoteLogToken:e,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let o=(0,mP.unifiedFormatter)(r,n);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(o)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":sg.Environment.instance.systemUserAgent,"zp-dn":sg.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Bs,Ld=class{static{s(this,"UnifiedLogTransport")}constructor(e){Bs||(Bs=new fP.BatchDispatch("unified-log-transport",1,yP(e)))}async log(e,r){Bs.enqueue(e),r.waitUntil(Bs.waitUntilFlushed())}};Ks.UnifiedLogTransport=Ld});var fg=y(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.LogInitializer=void 0;var gP=Or(),bP=_t(),cg=_l(),ug=W(),lg=pm(),_P=Mt(),wP=hm(),dg=fm(),pg=Xy(),EP=Nd(),vP=Fs(),hg=rg(),SP=ig(),TP=ag(),Dd=(0,gP.debug)("zuplo:logging"),Ud=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:r}){this.systemCoreLogger=e,this.userCoreLogger=r}static async init(e){let r=await t.setupSystemCoreLogger(ug.Environment.instance,e),n=await t.setupUserCoreLogger(ug.Environment.instance,e);return new t({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(e,r){let{build:n}=e;Dd("Gateway.setupSystemCoreLogger");let i=[],o=r.getService(cg.SYSTEM_LOGGER);return o?i.push(new hg.ProcessTransport(o.logger,e.logFormat)):e.isDeno&&i.push(new pg.ConsoleTransport(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&i.push(new TP.UnifiedLogTransport({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(i.map(async a=>{a.init&&await a.init()})),new lg.CoreLogger(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,i)}static async setupUserCoreLogger(e,r){Dd("Gateway.setupUserCoreLogger");let n=[],{runtime:i,build:o}=e,a=r.getService(cg.SYSTEM_LOGGER);if(a&&a.captureUserLogs===!0?n.push(new hg.ProcessTransport(a.logger,e.logFormat)):e.isDeno&&n.push(new pg.ConsoleTransport(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new SP.RemoteLogTransport({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),i.GCP_USER_LOG_NAME&&i.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new vP.GoogleLogTransport({serviceAccountJson:i.GCP_USER_LOG_SVC_ACCT_JSON,logName:i.GCP_USER_LOG_NAME})),i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let c=i.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new EP.DataDogTransport({apiKey:i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return bP.plugins.forEach(c=>{c instanceof _P.LogPlugin&&n.push(c.getTransport())}),await Promise.all(n.map(async c=>{c.init&&await c.init()})),new lg.CoreLogger(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,r,n,i,o){Dd("Gateway.createRequestLoggers");let a=new wP.LoggingContext(n,i,o),c=new dg.RequestLogger(e,r,this.systemCoreLogger,a);return{userRequestLogger:new dg.RequestLogger(e,r,this.userCoreLogger,a),systemRequestLogger:c}}};Js.LogInitializer=Ud});var Md=y(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.UserRouteConfiguration=void 0;var kd=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};zs.UserRouteConfiguration=kd});var Fd=y(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.Router=It.RouterError=It.LookupResult=It.RouterEntry=void 0;var mg=O(),IP=at(),PP=Md(),Ws=class{static{s(this,"RouterEntry")}constructor(e,r,n,i){this.fullPath=e,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};It.RouterEntry=Ws;var Ai=class{static{s(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};It.LookupResult=Ai;var Qs=class extends Error{static{s(this,"RouterError")}constructor(e,r){super(e,r)}};It.RouterError=Qs;var Hd=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,r){if(!(e instanceof PP.UserRouteConfiguration||e instanceof IP.SystemRouteConfiguration))throw new mg.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(o=>o.name===e.version)?.pathPrefix,i;"pathPattern"in e&&e.pathPattern?i=`${n??""}${e.pathPattern}`:i=`${n??""}${e.path}`;try{let o=new URLPattern({pathname:i}),a=new Ws(i,o,e,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(o){throw new Qs(`addRoute-error: Invalid path '${i}'. '${o.message}'`,{cause:o})}}lookup(e,r){if(typeof e>"u")throw new mg.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(e));if(n.length!==0)for(let i=0;i<n.length;i++){let o=n[i],c=o.urlPattern.exec({pathname:r});if(c!==null)return new Ai(o.config,o.executableHandler,c.pathname.groups)}}lookupByPathOnly(e){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:e});if(a!==null){let c=new Ai(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};It.Router=Hd});var Nr=y(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});Zs.Gateway=void 0;var AP=Or(),yg=$f(),gg=Wf(),RP=Qf(),bg=Yf(),_g=tm(),$t=Ar(),Ys=Cr(),wg=dm(),At=O(),Ri=_t(),OP=fg(),NP=Ut(),CP=te(),xP=dl(),LP=Yt(),DP=tn(),UP=He(),kP=Fd(),qd=at(),Eg=Md(),MP=Fe(),HP=Vo(),$d=W(),vg=kr(),Sg=Bu(),Pt=(0,AP.debug)("zuplo:runtime"),FP=s(t=>{let e=t.findIndex(r=>r.name===qd.systemNoVersion.name);return e>-1?[...t.splice(e),qd.systemNoVersion]:[...t,qd.systemNoVersion]},"setupSystemNoVersion"),jd=class t{static{s(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(e,r,n,i){this.routeData=e,this.runtimeSettings=r,this.schemaValidator=i,Pt("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=n}static async initialize(e,r,n,i,o){if(Pt("Gateway.initialize"),!t.#e){await(0,Ri.initializeRuntime)(o);let a=await OP.LogInitializer.init(n),c=e(),u={...c,corsPolicies:(0,HP.parseCorsPolicies)(c.corsPolicies)},l=new t(u,r,a,i);t.#e=l}return t.#e}static purgeGatewayCache(){Pt("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new At.SystemError("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#r;#n=[DP.policyProcessor,xP.corsProcessor,LP.metricsProcessor];#i;setupRoutes=()=>{Pt("Gateway.setupRoutes");let e=this.routeData,r=FP(e.versions),n=new kP.Router(r);if(e.routes.length===0)return(0,yg.registerBuildRoute)(n,this),(0,_g.registerPingRoute)(n,this),(0,gg.registerCorsRoute)(n,this),(0,RP.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;i&&((0,wg.registerDevPortalLegacyRedirectRoute)(n,this),(0,wg.registerDevPortalV3Route)(n,this)),(0,yg.registerBuildRoute)(n,this),(0,_g.registerPingRoute)(n,this),(0,gg.registerCorsRoute)(n,this);for(let o of Ri.plugins)o instanceof Ri.SystemRuntimePlugin&&o.registerRoutes(n,this);return e.routes.forEach(o=>{let a;if(typeof o.handler?.module=="object"&&(a=o.handler?.module[o.handler.export]),typeof a!="function")throw new At.ConfigurationError(`Invalid state - No handler on route for path '${o.path}'`);let c=new NP.Pipeline({processors:this.#n,handler:a,gateway:this}),u=new Eg.UserRouteConfiguration(o);n.addRoute(u,c.execute)}),(0,bg.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new At.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((r,n,i)=>this.#o(r,n,i),"errorHandler");return e};errorHandler(e,r,n){try{return this.#i(e,r,n)}catch(i){return Pt("An error occurred in the user's errorHandler",i),this.#o(e,r,i)}}#o(e,r,n){Pt("Gateway.internalErrorResponse");let i={};if($d.Environment.instance.isDeno){if(n instanceof At.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let o=(0,vg.serializeError)(n.cause);"stack"in o&&(o.stack=(0,vg.cleanStack)(o.stack)),i={cause:o}}}return CP.HttpProblems.internalServerError(e,r,{detail:n.message,...i})}#s(e){let r=new Headers(e.headers);return $t.DISPATCH_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),$d.Environment.instance.isDeno&&$t.INTERNAL_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),new Request(e,{headers:r})}async handleRequest(e,r){let n=e.headers.get($t.REQUEST_ID_HEADER)??e.headers.get($t.LEGACY_REQUEST_ID_HEADER),i=e.headers.get($t.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let S=new Headers(e.headers);S.set($t.REQUEST_ID_HEADER,n),e=new Request(e,{headers:S})}if(["GET","HEAD"].includes(e.method)&&e.body){let S=new Headers(e.headers);S.set($t.BODY_REMOVED_HEADER,"true"),e=new Request(e,{headers:S,body:null})}let o={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,o,e),u=new URL(e.url),l=u.pathname,d=this.#r.lookup(e.method,l);if(!d)throw new At.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Ys.HeaderIncomingRequestProperties(e.headers),m=this.#s(e),h=new UP.ZuploRequest(m,{params:d.params}),g=new Ys.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,fetchEvent:r,custom:o,incomingRequestProperties:p}),_=Ys.ZuploContextExtensions.initialize(g,h);if(d.routeConfiguration===bg.notFoundRouteConfiguration&&Ri.runtimeExtensions.value?.notFoundHandler!==void 0){let S=this.#r.lookupByPathOnly(l);_.pathOnlyMatches=S.map(T=>T.routeConfiguration).filter(T=>T instanceof Eg.UserRouteConfiguration)}try{if(MP.SystemLogMap.addLogger(g,c),$d.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!(0,Sg.isSystemRoute)(u):!u.pathname.startsWith("/__zuplo")){let M=await(0,Ri.invokeOnRequestExtensions)(h,g);if(M instanceof Response)return M;{let j=Ys.ZuploContextExtensions.getContextExtensions(g);h=M,j.latestRequest=h}}(0,Sg.isSystemRoute)(u)||a.debug(`Request received '${u.pathname}'`,{method:e.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let S=d.executableHandler;qP(S,d,e),Pt("Gateway.handleRequest - call user handler");let T=await S(h,g);if(Pt("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new At.RuntimeError(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new At.RuntimeError("The response object has already been used. Return a new response instead.");if(T.headers.get($t.REQUEST_ID_HEADER)===null&&!T.webSocket){let M=new Headers(T.headers);return M.set($t.REQUEST_ID_HEADER,n),new Response(T.body,{status:T.status,statusText:T.statusText,headers:M,cf:T.cf})}else return T}catch(S){return Pt("Gateway - error executing handler",S),S instanceof At.RuntimeError?(a.error(S),c.warn(S)):c.error(S),await this.#o(h,g,S)}}};Zs.Gateway=jd;function qP(t,e,r){if(Pt("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new At.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new At.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}s(qP,"checkHandler")});var Tg=y(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.invokeInboundPolicy=void 0;var $P=O(),jP=Nr(),VP=tn(),GP=s(async(t,e,r)=>{let n=jP.Gateway.instance.routeData.policies,i=(0,VP.getInboundPolicyInstances)([t],n);if(i.length===0)throw new $P.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return i[0].handler(e,r)},"invokeInboundPolicy");Xs.invokeInboundPolicy=GP});var Cr=y(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.SystemZuploContext=tt.ZuploContextExtensions=tt.ResponseSentEvent=tt.ResponseSendingEvent=tt.HeaderIncomingRequestProperties=void 0;var _e=Ar(),BP=O(),KP=Tg(),Vd=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(_e.ZP_ASN_HEADER);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(_e.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(_e.CF_IP_CITY_HEADER)??this.#e.get(_e.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(_e.CF_IP_CONTINENT_HEADER)??this.#e.get(_e.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(_e.CF_IP_COUNTRY_HEADER)??this.#e.get(_e.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(_e.CF_IP_LATITUDE_HEADER)??this.#e.get(_e.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(_e.CF_IP_LONGITUDE_HEADER)??this.#e.get(_e.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(_e.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(_e.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(_e.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(_e.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(_e.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(_e.ZP_TIMEZONE_HEADER)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}};tt.HeaderIncomingRequestProperties=Vd;var Gd=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse};tt.ResponseSendingEvent=Gd;var Bd=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response};tt.ResponseSentEvent=Bd;var Oi=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,r){if(!t.#e.has(e)){let n=new t(r);return t.#e.set(e,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let r=t.#e.get(e);if(!r)throw new BP.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#r=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,r,n)=>{for(let i of this.#t)await i(e,r,n)};onResponseSending=async(e,r,n)=>{let i=e;for(let o of this.#r)i=await o(e,r,n);return i}};tt.ZuploContextExtensions=Oi;var Kd=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:n,fetchEvent:i,custom:o,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=r,this.requestId=n,this.custom=o,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,KP.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Oi.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Oi.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,r,n){let i=s(o=>{try{typeof r=="function"?r(o):r.handleEvent(o)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,i,n)}};tt.SystemZuploContext=Kd});var ta=y(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.ContextData=void 0;var Jd=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let i=t.#e.get(e);i||(i=new Map),i.set(r,n),t.#e.set(e,i)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};ea.ContextData=Jd});var Sn=y(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.environment=fr.isZuploReadableEnvVariableName=fr.isRestrictedEnvVariableName=void 0;var JP=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ig(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!JP.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(Ig,"isRestrictedEnvVariableName");fr.isRestrictedEnvVariableName=Ig;function Pg(t){return!!t.startsWith("ZUPLO_")}s(Pg,"isZuploReadableEnvVariableName");fr.isZuploReadableEnvVariableName=Pg;var zP=new Proxy({},{get(t,e){if(Ig(String(e))&&!Pg(String(e)))return;let r=globalThis,n;return r.process?n=r.process.env[e]:n=r[e],n}});fr.environment=zP});var zd=y(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.externalServiceHandler=Tn.externalServiceTunnelConfig=void 0;var WP=Or(),$r=O(),QP=Wd(),Ni=W(),dt=(0,WP.debug)("zuplo:runtime:external-service");function Rg(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=Ni.Environment.instance.runtime;if(e&&e!=="undefined")try{let r=atob(e);t=JSON.parse(r)}catch{}return t}s(Rg,"getServiceAuth");async function YP(t){let e=Rg();if(!e)throw dt("There is no external service auth configured for this zup."),new $r.RuntimeError("There are no external services configured for this zup.");if(typeof t!="string")throw dt("Cannot call external service with Request object"),new $r.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(t).hostname,i={};i["CF-Access-Client-Id"]=e.clientId,i["CF-Access-Client-Secret"]=e.clientSecret;let o;if(e.customServiceMapping&&e.customServiceMapping[n])o=`https://${e.customServiceMapping[n]}`;else if(Ni.Environment.instance.useSha256ServiceRouting){dt("Using sha256 service routing");let a=Ni.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)o=`https://${await Og(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw dt("Cannot use sha256 service routing, missing build variables"),new $r.RuntimeError("Failed to generate fully qualified tunnel url.")}else o=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:o,tunnelHeaders:i}}s(YP,"externalServiceTunnelConfig");Tn.externalServiceTunnelConfig=YP;async function ZP(t,e){let r=Rg();if(r)if(dt(`Using external service auth. ClientId: ${r.clientId})`),typeof t=="string"){let n=new URL(t),i=n.hostname,o=e??{},a=new Headers(o.headers||{});a.set("CF-Access-Client-Id",r.clientId),a.set("CF-Access-Client-Secret",r.clientSecret),o.headers=a;let c;if(r.customServiceMapping&&r.customServiceMapping[i])c=`https://${r.customServiceMapping[i]}`;else if(Ni.Environment.instance.useSha256ServiceRouting){dt("Using sha256 service routing");let d=Ni.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await Og(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw dt("Cannot use sha256 service routing, missing build variables"),new $r.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);dt(`Calling external service: ${u.toString()}`);let l=await(0,QP.originalFetch)(u.toString(),o);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:c}),new $r.RuntimeError("Could not connect to secure tunnel.");return l}else throw dt("Cannot call external service with Request object"),new $r.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw dt("There is no external service auth configured for this zup."),new $r.RuntimeError("There are no external services configured for this zup.")}s(ZP,"externalServiceHandler");Tn.externalServiceHandler=ZP;async function Og(t,e,r,n){let i=t.toLowerCase(),o=e.toLowerCase(),a=r.toLowerCase(),c=XP(n);dt(`Hashing service name: ${o}-${i}.${o}-${a}-${c}`);let u=await Ag(`${o}-${i}`),l=await Ag(`${o}-${a}-${c}`);return`${u}.${l}`}s(Og,"hashServiceName");async function Ag(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ag,"hashSegment");function XP(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(XP,"sanitizeEnvironmentType")});var Wd=y(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.originalFetch=void 0;var eA=zd(),Ng=new Map;Ng.set("service:",eA.externalServiceHandler);In.originalFetch=globalThis.fetch;globalThis.fetch=function(t,e){let r=tA(e);if(typeof t=="string"){let n=new URL(t),i=Ng.get(n.protocol);return i?i(t,r):(0,In.originalFetch)(t,r)}else return(0,In.originalFetch)(t,r)};var tA=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let r=t;return r.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit")});var Lg=y(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.Handler=Pn.purgeGatewayCache=void 0;var rA=O(),xg=Nr(),Cg=W(),nA=s(()=>{xg.Gateway.purgeGatewayCache()},"purgeGatewayCache");Pn.purgeGatewayCache=nA;var Qd=class{static{s(this,"Handler")}routeLoader;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(e,r,n,i,o,a,c){this.routeLoader=e,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=o,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(e,r)=>{Cg.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await xg.Gateway.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let o="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";i instanceof rA.ConfigurationError&&(o=i.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:o,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:Cg.Environment.instance.isDeno?i.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return n.handleRequest(e,r)}};Pn.Handler=Qd});var Mg=y(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.pathToRegexp=Re.tokensToRegexp=Re.regexpToFunction=Re.match=Re.tokensToFunction=Re.compile=Re.parse=void 0;function iA(t){for(var e=[],r=0;r<t.length;){var n=t[r];if(n==="*"||n==="+"||n==="?"){e.push({type:"MODIFIER",index:r,value:t[r++]});continue}if(n==="\\"){e.push({type:"ESCAPED_CHAR",index:r++,value:t[r++]});continue}if(n==="{"){e.push({type:"OPEN",index:r,value:t[r++]});continue}if(n==="}"){e.push({type:"CLOSE",index:r,value:t[r++]});continue}if(n===":"){for(var i="",o=r+1;o<t.length;){var a=t.charCodeAt(o);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=t[o++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));e.push({type:"NAME",index:r,value:i}),r=o;continue}if(n==="("){var c=1,u="",o=r+1;if(t[o]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(o));for(;o<t.length;){if(t[o]==="\\"){u+=t[o++]+t[o++];continue}if(t[o]===")"){if(c--,c===0){o++;break}}else if(t[o]==="("&&(c++,t[o+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(o));u+=t[o++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));e.push({type:"PATTERN",index:r,value:u}),r=o;continue}e.push({type:"CHAR",index:r,value:t[r++]})}return e.push({type:"END",index:r,value:""}),e}s(iA,"lexer");function Yd(t,e){e===void 0&&(e={});for(var r=iA(t),n=e.prefixes,i=n===void 0?"./":n,o="[^".concat(An(e.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=s(function(ie){if(u<r.length&&r[u].type===ie)return r[u++].value},"tryConsume"),p=s(function(ie){var me=d(ie);if(me!==void 0)return me;var Ke=r[u],E=Ke.type,H=Ke.index;throw new TypeError("Unexpected ".concat(E," at ").concat(H,", expected ").concat(ie))},"mustConsume"),m=s(function(){for(var ie="",me;me=d("CHAR")||d("ESCAPED_CHAR");)ie+=me;return ie},"consumeText");u<r.length;){var h=d("CHAR"),g=d("NAME"),_=d("PATTERN");if(g||_){var S=h||"";i.indexOf(S)===-1&&(l+=S,S=""),l&&(a.push(l),l=""),a.push({name:g||c++,prefix:S,suffix:"",pattern:_||o,modifier:d("MODIFIER")||""});continue}var T=h||d("ESCAPED_CHAR");if(T){l+=T;continue}l&&(a.push(l),l="");var M=d("OPEN");if(M){var S=m(),j=d("NAME")||"",L=d("PATTERN")||"",ne=m();p("CLOSE"),a.push({name:j||(L?c++:""),pattern:j&&!L?o:L,prefix:S,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Yd,"parse");Re.parse=Yd;function oA(t,e){return Dg(Yd(t,e),e)}s(oA,"compile");Re.compile=oA;function Dg(t,e){e===void 0&&(e={});var r=Zd(e),n=e.encode,i=n===void 0?function(u){return u}:n,o=e.validate,a=o===void 0?!0:o,c=t.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var m=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",g=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!g)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var _=0;_<m.length;_++){var S=i(m[_],p);if(a&&!c[d].test(S))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var S=i(String(m),p);if(a&&!c[d].test(S))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix;continue}if(!h){var T=g?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(T))}}return l}}s(Dg,"tokensToFunction");Re.tokensToFunction=Dg;function sA(t,e){var r=[],n=Xd(t,r,e);return Ug(n,r,e)}s(sA,"match");Re.match=sA;function Ug(t,e,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(o){return o}:n;return function(o){var a=t.exec(o);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=s(function(m){if(a[m]===void 0)return"continue";var h=e[m-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[m].split(h.prefix+h.suffix).map(function(g){return i(g,h)}):l[h.name]=i(a[m],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}s(Ug,"regexpToFunction");Re.regexpToFunction=Ug;function An(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(An,"escapeString");function Zd(t){return t&&t.sensitive?"":"i"}s(Zd,"flags");function aA(t,e){if(!e)return t;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(t.source);i;)e.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(t.source);return t}s(aA,"regexpToRegexp");function cA(t,e,r){var n=t.map(function(i){return Xd(i,e,r).source});return new RegExp("(?:".concat(n.join("|"),")"),Zd(r))}s(cA,"arrayToRegexp");function uA(t,e,r){return kg(Yd(t,r),e,r)}s(uA,"stringToRegexp");function kg(t,e,r){r===void 0&&(r={});for(var n=r.strict,i=n===void 0?!1:n,o=r.start,a=o===void 0?!0:o,c=r.end,u=c===void 0?!0:c,l=r.encode,d=l===void 0?function(H){return H}:l,p=r.delimiter,m=p===void 0?"/#?":p,h=r.endsWith,g=h===void 0?"":h,_="[".concat(An(g),"]|$"),S="[".concat(An(m),"]"),T=a?"^":"",M=0,j=t;M<j.length;M++){var L=j[M];if(typeof L=="string")T+=An(d(L));else{var ne=An(d(L.prefix)),ie=An(d(L.suffix));if(L.pattern)if(e&&e.push(L),ne||ie)if(L.modifier==="+"||L.modifier==="*"){var me=L.modifier==="*"?"?":"";T+="(?:".concat(ne,"((?:").concat(L.pattern,")(?:").concat(ie).concat(ne,"(?:").concat(L.pattern,"))*)").concat(ie,")").concat(me)}else T+="(?:".concat(ne,"(").concat(L.pattern,")").concat(ie,")").concat(L.modifier);else L.modifier==="+"||L.modifier==="*"?T+="((?:".concat(L.pattern,")").concat(L.modifier,")"):T+="(".concat(L.pattern,")").concat(L.modifier);else T+="(?:".concat(ne).concat(ie,")").concat(L.modifier)}}if(u)i||(T+="".concat(S,"?")),T+=r.endsWith?"(?=".concat(_,")"):"$";else{var Ke=t[t.length-1],E=typeof Ke=="string"?S.indexOf(Ke[Ke.length-1])>-1:Ke===void 0;i||(T+="(?:".concat(S,"(?=").concat(_,"))?")),E||(T+="(?=".concat(S,"|").concat(_,")"))}return new RegExp(T,Zd(r))}s(kg,"tokensToRegexp");Re.tokensToRegexp=kg;function Xd(t,e,r){return t instanceof RegExp?aA(t,e):Array.isArray(t)?cA(t,e,r):uA(t,e,r)}s(Xd,"pathToRegexp");Re.pathToRegexp=Xd});var np=y(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.AwsV4Signer=Rn.AwsClient=void 0;var lA=Or(),$g=O(),dA=(0,lA.debug)("zuplo:runtime"),tp=new TextEncoder,Hg={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},pA=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],rp=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:r,sessionToken:n,service:i,region:o,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=r,this.sessionToken=n,this.service=i,this.region=o,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,r){let n=new ra(Object.assign({url:e},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(e,r){dA("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:i,request:o}=await this.sign(e,r),a=fetch(i,o);if(n===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new $g.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};Rn.AwsClient=rp;var ra=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:r,headers:n,body:i,accessKeyId:o,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:g,singleEncode:_}){if(r==null)throw new TypeError("url is a required option");if(o==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(i?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=i,this.accessKeyId=o,this.secretAccessKey=a,this.sessionToken=c;let S,T;(!u||!l)&&([S,T]=hA(this.url,this.headers)),this.service=u||S||"",this.region=l||T||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let M=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),M.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&M.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>g||!pA.includes(L)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(L=>L+":"+(L==="host"?this.url.host:(this.headers.get(L)||"").replace(/\s+/g," "))).join(`
|
|
59
|
+
-----END ${e}-----`},"default")});function Bm(t){let e=[],r=0;for(;r<t.length;){let n=Ym(t.subarray(r));e.push(n),r+=n.byteLength}return e}function Ym(t){let e=0,r=t[0]&31;if(e++,r===31){for(r=0;t[e]>=128;)r=r*128+t[e]-128,e++;r=r*128+t[e]-128,e++}let n=0;if(t[e]<128)n=t[e],e++;else if(n===128){for(n=0;t[e+n]!==0||t[e+n+1]!==0;){if(n>t.byteLength)throw new TypeError("invalid indefinite form length");n++}let o=e+n+2;return{byteLength:o,contents:t.subarray(e,e+n),raw:t.subarray(0,o)}}else{let o=t[e]&127;e++,n=0;for(let a=0;a<o;a++)n=n*256+t[e],e++}let i=e+n;return{byteLength:i,contents:t.subarray(e,i),raw:t.subarray(0,i)}}function SI(t){let e=Bm(Bm(Ym(t).contents)[0].contents);return cs(e[e[0].raw[0]===160?6:5].raw)}function TI(t){let e=t.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=xl(e);return Kl(SI(r),"PUBLIC KEY")}var Km,Jm,zm,cr,Gm,Wm,Qm,Jl,Zm,bs=I(()=>{Se();ut();Ie();Vm();V();lt();Km=s(async(t,e,r)=>{if(!ae(r))throw new TypeError(oe(r,...Q));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return Kl(cs(new Uint8Array(await D.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},"genericExport"),Jm=s(t=>Km("public","spki",t),"toSPKI"),zm=s(t=>Km("private","pkcs8",t),"toPKCS8"),cr=s((t,e,r=0)=>{r===0&&(e.unshift(e.length),e.unshift(6));let n=t.indexOf(e[0],r);if(n===-1)return!1;let i=t.subarray(n,n+e.length);return i.length!==e.length?!1:i.every((o,a)=>o===e[a])||cr(t,e,n+1)},"findOid"),Gm=s(t=>{switch(!0){case cr(t,[42,134,72,206,61,3,1,7]):return"P-256";case cr(t,[43,129,4,0,34]):return"P-384";case cr(t,[43,129,4,0,35]):return"P-521";case cr(t,[43,101,110]):return"X25519";case cr(t,[43,101,111]):return"X448";case cr(t,[43,101,112]):return"Ed25519";case cr(t,[43,101,113]):return"Ed448";default:throw new k("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),Wm=s(async(t,e,r,n,i)=>{var o;let a,c,u=new Uint8Array(atob(r.replace(t,"")).split("").map(d=>d.charCodeAt(0))),l=e==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},c=l?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},c=l?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},c=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=Gm(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:Gm(u)},c=l?["verify"]:["sign"];break;default:throw new k('Invalid or unsupported "alg" (Algorithm) value')}return D.subtle.importKey(e,u,a,(o=i?.extractable)!==null&&o!==void 0?o:!1,c)},"genericImport"),Qm=s((t,e,r)=>Wm(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,e,r),"fromPKCS8"),Jl=s((t,e,r)=>Wm(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",t,e,r),"fromSPKI");s(Bm,"getElement");s(Ym,"parseElement");s(SI,"spkiFromX509");s(TI,"getSPKI");Zm=s((t,e,r)=>{let n;try{n=TI(t)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return Jl(n,e,r)},"fromX509")});function II(t){let e,r;switch(t.kty){case"oct":{switch(t.alg){case"HS256":case"HS384":case"HS512":e={name:"HMAC",hash:`SHA-${t.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new k(`${t.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":e={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":e={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":e={name:"PBKDF2"},r=["deriveBits"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new k('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var PI,zl,Xm=I(()=>{Se();V();Ie();s(II,"subtleMapping");PI=s(async t=>{var e,r;if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=II(t),o=[n,(e=t.ext)!==null&&e!==void 0?e:!1,(r=t.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return D.subtle.importKey("raw",re(t.k),...o);let a={...t};return delete a.alg,delete a.use,D.subtle.importKey("jwk",a,...o)},"parse"),zl=PI});async function ey(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Jl(t,e,r)}async function ty(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Zm(t,e,r)}async function ry(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Qm(t,e,r)}async function ur(t,e,r){var n;if(!Y(t))throw new TypeError("JWK must be an object");switch(e||(e=t.alg),t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=t.ext!==!0),r?zl({...t,alg:e,ext:(n=t.ext)!==null&&n!==void 0?n:!1}):re(t.k);case"RSA":if(t.oth!==void 0)throw new k('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return zl({...t,alg:e});default:throw new k('Unsupported "kty" (Key Type) Parameter value')}}var _i=I(()=>{Ie();bs();Xm();V();je();s(ey,"importSPKI");s(ty,"importX509");s(ry,"importPKCS8");s(ur,"importJWK")});var AI,RI,OI,lr,wi=I(()=>{ut();lt();AI=s((t,e)=>{if(!(e instanceof Uint8Array)){if(!Hl(e))throw new TypeError(Ml(t,e,...Q,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Q.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),RI=s((t,e,r)=>{if(!Hl(e))throw new TypeError(Ml(t,e,...Q));if(e.type==="secret")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),OI=s((t,e,r)=>{t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?AI(t,e):RI(t,e,r)},"checkKeyType"),lr=OI});async function NI(t,e,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(oe(r,"Uint8Array"));let o=parseInt(t.slice(1,4),10),a=await D.subtle.importKey("raw",r.subarray(o>>3),"AES-CBC",!1,["encrypt"]),c=await D.subtle.importKey("raw",r.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await D.subtle.encrypt({iv:n,name:"AES-CBC"},a,e)),l=Te(i,n,u,os(i.length<<3)),d=new Uint8Array((await D.subtle.sign("HMAC",c,l)).slice(0,o>>3));return{ciphertext:u,tag:d}}async function CI(t,e,r,n,i){let o;r instanceof Uint8Array?o=await D.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($e(r,t,"encrypt"),o=r);let a=new Uint8Array(await D.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},o,e)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var xI,Ei,Wl=I(()=>{ge();Ul();kl();Se();ar();ut();V();lt();s(NI,"cbcEncrypt");s(CI,"gcmEncrypt");xI=s(async(t,e,r,n,i)=>{if(!ae(r)&&!(r instanceof Uint8Array))throw new TypeError(oe(r,...Q,"Uint8Array"));switch(ds(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&an(r,parseInt(t.slice(-3),10)),NI(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&an(r,parseInt(t.slice(1,4),10)),CI(t,e,r,n,i);default:throw new k("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),Ei=xI});async function ny(t,e,r,n){let i=t.slice(0,7);n||(n=us(i));let{ciphertext:o,tag:a}=await Ei(i,r,e,n,new Uint8Array(0));return{encryptedKey:o,iv:X(n),tag:X(a)}}async function iy(t,e,r,n,i){let o=t.slice(0,7);return hs(o,e,r,n,i,new Uint8Array(0))}var Ql=I(()=>{Wl();Fl();ls();Ie();s(ny,"wrap");s(iy,"unwrap")});async function LI(t,e,r,n,i){switch(lr(t,e,"decrypt"),t){case"dir":{if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Y(n.epk))throw new R('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!ys(e))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await ur(n.epk,t),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new R('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=re(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new R('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=re(n.apv)}let u=await ms(o,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?gi(n.enc):parseInt(t.slice(-5,-2),10),a,c);if(t==="ECDH-ES")return u;if(r===void 0)throw new R("JWE Encrypted Key missing");return yi(t.slice(-6),u,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new R("JWE Encrypted Key missing");return jm(t,e,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new R('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new R('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new R('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return Fm(t,e,r,n.p2c,re(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");return yi(t,e,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new R('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new R('JOSE Header "tag" (Authentication Tag) missing or invalid');let o=re(n.iv),a=re(n.tag);return iy(t,e,r,o,a)}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var oy,sy=I(()=>{fs();jl();Gl();Bl();Ie();V();bi();_i();wi();je();Ql();s(LI,"decryptKeyManagement");oy=LI});function DI(t,e,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...e.entries()]):o=e;for(let a of n.crit){if(!o.has(a))throw new k(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new t(`Extension Header Parameter "${a}" is missing`);if(o.get(a)&&n[a]===void 0)throw new t(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var Tt,dn=I(()=>{V();s(DI,"validateCrit");Tt=DI});var UI,vi,Yl=I(()=>{UI=s((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`);if(e)return new Set(e)},"validateAlgorithms"),vi=UI});async function pn(t,e,r){var n;if(!Y(t))throw new R("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new R("JOSE Header missing");if(typeof t.iv!="string")throw new R("JWE Initialization Vector missing or incorrect type");if(typeof t.ciphertext!="string")throw new R("JWE Ciphertext missing or incorrect type");if(typeof t.tag!="string")throw new R("JWE Authentication Tag missing or incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new R("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new R("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new R("JWE AAD incorrect type");if(t.header!==void 0&&!Y(t.header))throw new R("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!Y(t.unprotected))throw new R("JWE Per-Recipient Unprotected Header incorrect type");let i;if(t.protected)try{let j=re(t.protected);i=JSON.parse(ue.decode(j))}catch{throw new R("JWE Protected Header is invalid")}if(!vt(i,t.header,t.unprotected))throw new R("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...i,...t.header,...t.unprotected};if(Tt(R,new Map,r?.crit,i,o),o.zip!==void 0){if(!i||!i.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(o.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=o;if(typeof a!="string"||!a)throw new R("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new R("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&vi("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&vi("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new nr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new nr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;t.encrypted_key!==void 0&&(d=re(t.encrypted_key));let p=!1;typeof e=="function"&&(e=await e(i,t),p=!0);let m;try{m=await oy(a,e,d,o,r)}catch(j){if(j instanceof TypeError||j instanceof R||j instanceof k)throw j;m=St(c)}let h=re(t.iv),g=re(t.tag),_=Z.encode((n=t.protected)!==null&&n!==void 0?n:""),S;t.aad!==void 0?S=Te(_,Z.encode("."),Z.encode(t.aad)):S=_;let T=await hs(c,m,re(t.ciphertext),h,g,S);o.zip==="DEF"&&(T=await(r?.inflateRaw||Nm)(T));let M={plaintext:T};return t.protected!==void 0&&(M.protectedHeader=i),t.aad!==void 0&&(M.additionalAuthenticatedData=re(t.aad)),t.unprotected!==void 0&&(M.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(M.unprotectedHeader=t.header),p?{...M,key:e}:M}var _s=I(()=>{Ie();Fl();ql();V();cn();je();sy();ge();bi();dn();Yl();s(pn,"flattenedDecrypt")});async function ws(t,e,r){if(t instanceof Uint8Array&&(t=ue.decode(t)),typeof t!="string")throw new R("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:o,3:a,4:c,length:u}=t.split(".");if(u!==5)throw new R("Invalid Compact JWE");let l=await pn({ciphertext:a,iv:o||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},e,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...d,key:l.key}:d}var Zl=I(()=>{_s();V();ge();s(ws,"compactDecrypt")});async function ay(t,e,r){if(!Y(t))throw new R("General JWE must be an object");if(!Array.isArray(t.recipients)||!t.recipients.every(Y))throw new R("JWE Recipients missing or incorrect type");if(!t.recipients.length)throw new R("JWE Recipients has no members");for(let n of t.recipients)try{return await pn({aad:t.aad,ciphertext:t.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:t.iv,protected:t.protected,tag:t.tag,unprotected:t.unprotected},e,r)}catch{}throw new Ht}var cy=I(()=>{_s();V();je();s(ay,"generalDecrypt")});var kI,uy,ly=I(()=>{Se();ut();Ie();lt();kI=s(async t=>{if(t instanceof Uint8Array)return{kty:"oct",k:X(t)};if(!ae(t))throw new TypeError(oe(t,...Q,"Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...o}=await D.subtle.exportKey("jwk",t);return o},"keyToJWK"),uy=kI});async function dy(t){return Jm(t)}async function py(t){return zm(t)}async function Es(t){return uy(t)}var Xl=I(()=>{bs();bs();ly();s(dy,"exportSPKI");s(py,"exportPKCS8");s(Es,"exportJWK")});async function MI(t,e,r,n,i={}){let o,a,c;switch(lr(t,r,"encrypt"),t){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!ys(r))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:u,apv:l}=i,{epk:d}=i;d||(d=(await Dm(r)).privateKey);let{x:p,y:m,crv:h,kty:g}=await Es(d),_=await ms(r,d,t==="ECDH-ES"?e:t,t==="ECDH-ES"?gi(e):parseInt(t.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:g}},g==="EC"&&(a.epk.y=m),u&&(a.apu=X(u)),l&&(a.apv=X(l)),t==="ECDH-ES"){c=_;break}c=n||St(e);let S=t.slice(-6);o=await mi(S,_,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||St(e),o=await $m(t,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||St(e);let{p2c:u,p2s:l}=i;({encryptedKey:o,...a}=await Hm(t,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||St(e),o=await mi(t,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||St(e);let{iv:u}=i;({encryptedKey:o,...a}=await ny(t,r,c,u));break}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:o,parameters:a}}var vs,ed=I(()=>{fs();jl();Gl();Bl();Ie();bi();V();Xl();wi();Ql();s(MI,"encryptKeyManagement");vs=MI});var td,Ft,Ss=I(()=>{Ie();Wl();ql();ls();ed();V();cn();ge();dn();td=Symbol(),Ft=class{static{s(this,"FlattenedEncrypt")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new R("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!vt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(Tt(R,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:o}=n;if(typeof i!="string"||!i)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(i==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(i==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let c;{let g;({cek:c,encryptedKey:a,parameters:g}=await vs(i,o,e,this._cek,this._keyManagementParameters)),g&&(r&&td in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...g}:this.setUnprotectedHeader(g):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...g}:this.setProtectedHeader(g))}this._iv||(this._iv=us(o));let u,l,d;this._protectedHeader?l=Z.encode(X(JSON.stringify(this._protectedHeader))):l=Z.encode(""),this._aad?(d=X(this._aad),u=Te(l,Z.encode("."),Z.encode(d))):u=l;let p,m;if(n.zip==="DEF"){let g=await(r?.deflateRaw||Cm)(this._plaintext);({ciphertext:p,tag:m}=await Ei(o,g,c,this._iv,u))}else({ciphertext:p,tag:m}=await Ei(o,this._plaintext,c,this._iv,u));let h={ciphertext:X(p),iv:X(this._iv),tag:X(m)};return a&&(h.encrypted_key=X(a)),d&&(h.aad=d),this._protectedHeader&&(h.protected=ue.decode(l)),this._sharedUnprotectedHeader&&(h.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(h.header=this._unprotectedHeader),h}}});var rd,Ts,hy=I(()=>{Ss();V();bi();cn();ed();Ie();dn();rd=class{static{s(this,"IndividualRecipient")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}},Ts=class{static{s(this,"GeneralEncrypt")}constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,r){let n=new rd(this,e,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var r,n,i;if(!this._recipients.length)throw new R("at least one recipient must be added");if(e={deflateRaw:e?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Ft(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...e}),d={ciphertext:l.ciphertext,iv:l.iv,recipients:[{}],tag:l.tag};return l.aad&&(d.aad=l.aad),l.protected&&(d.protected=l.protected),l.unprotected&&(d.unprotected=l.unprotected),l.encrypted_key&&(d.recipients[0].encrypted_key=l.encrypted_key),l.header&&(d.recipients[0].header=l.header),d}let o;for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u];if(!vt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let d={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader},{alg:p}=d;if(typeof p!="string"||!p)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new R('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!o)o=d.enc;else if(o!==d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(Tt(R,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=St(o),c={ciphertext:"",iv:"",recipients:[],tag:""};for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u],d={};c.recipients.push(d);let m={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let _=await new Ft(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:m}).encrypt(l.key,{...l.options,...e,[td]:!0});c.ciphertext=_.ciphertext,c.iv=_.iv,c.tag=_.tag,_.aad&&(c.aad=_.aad),_.protected&&(c.protected=_.protected),_.unprotected&&(c.unprotected=_.unprotected),d.encrypted_key=_.encrypted_key,_.header&&(d.header=_.header);continue}let{encryptedKey:h,parameters:g}=await vs(((r=l.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((i=this._unprotectedHeader)===null||i===void 0?void 0:i.alg),o,l.key,a,{p2c:m});d.encrypted_key=X(h),(l.unprotectedHeader||g)&&(d.header={...l.unprotectedHeader,...g})}return c}}});function Si(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"EdDSA":return{name:e.name};default:throw new k(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var nd=I(()=>{V();s(Si,"subtleDsa")});function Ti(t,e,r){if(ae(e))return Rm(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(oe(e,...Q));return D.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(oe(e,...Q,"Uint8Array"))}var id=I(()=>{Se();ar();ut();lt();s(Ti,"getCryptoKey")});var HI,fy,my=I(()=>{nd();Se();gs();id();HI=s(async(t,e,r,n)=>{let i=await Ti(t,e,"verify");Fr(t,i);let o=Si(t,i.algorithm);try{return await D.subtle.verify(o,i,r,n)}catch{return!1}},"verify"),fy=HI});async function hn(t,e,r){var n;if(!Y(t))throw new z("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new z("JWS Protected Header incorrect type");if(t.payload===void 0)throw new z("JWS Payload missing");if(typeof t.signature!="string")throw new z("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Y(t.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(t.protected)try{let S=re(t.protected);i=JSON.parse(ue.decode(S))}catch{throw new z("JWS Protected Header is invalid")}if(!vt(i,t.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...i,...t.header},a=Tt(z,new Map([["b64",!0]]),r?.crit,i,o),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=o;if(typeof u!="string"||!u)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&vi("algorithms",r.algorithms);if(l&&!l.has(u))throw new nr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof t.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof e=="function"&&(e=await e(i,t),d=!0),lr(u,e,"verify");let p=Te(Z.encode((n=t.protected)!==null&&n!==void 0?n:""),Z.encode("."),typeof t.payload=="string"?Z.encode(t.payload):t.payload),m=re(t.signature);if(!await fy(u,e,m,p))throw new Hr;let g;c?g=re(t.payload):typeof t.payload=="string"?g=Z.encode(t.payload):g=t.payload;let _={payload:g};return t.protected!==void 0&&(_.protectedHeader=i),t.header!==void 0&&(_.unprotectedHeader=t.header),d?{..._,key:e}:_}var Is=I(()=>{Ie();my();V();ge();cn();je();wi();dn();Yl();s(hn,"flattenedVerify")});async function Ps(t,e,r){if(t instanceof Uint8Array&&(t=ue.decode(t)),typeof t!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:o,length:a}=t.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await hn({payload:i,protected:n,signature:o},e,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof e=="function"?{...u,key:c.key}:u}var od=I(()=>{Is();V();ge();s(Ps,"compactVerify")});async function yy(t,e,r){if(!Y(t))throw new z("General JWS must be an object");if(!Array.isArray(t.signatures)||!t.signatures.every(Y))throw new z("JWS Signatures missing or incorrect type");for(let n of t.signatures)try{return await hn({header:n.header,payload:t.payload,protected:n.protected,signature:n.signature},e,r)}catch{}throw new Hr}var gy=I(()=>{Is();V();je();s(yy,"generalVerify")});var fn,sd=I(()=>{fn=s(t=>Math.floor(t.getTime()/1e3),"default")});var FI,mn,ad=I(()=>{FI=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,mn=s(t=>{let e=FI.exec(t);if(!e)throw new TypeError("Invalid time period format");let r=parseFloat(e[1]);switch(e[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}},"default")});var by,qI,yn,As=I(()=>{V();ge();sd();ad();je();by=s(t=>t.toLowerCase().replace(/^application\//,""),"normalizeTyp"),qI=s((t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1,"checkAudiencePresence"),yn=s((t,e,r={})=>{let{typ:n}=r;if(n&&(typeof t.typ!="string"||by(t.typ)!==by(n)))throw new be('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ue.decode(e))}catch{}if(!Y(i))throw new le("JWT Claims Set must be a top-level JSON object");let{requiredClaims:o=[],issuer:a,subject:c,audience:u,maxTokenAge:l}=r;l!==void 0&&o.push("iat"),u!==void 0&&o.push("aud"),c!==void 0&&o.push("sub"),a!==void 0&&o.push("iss");for(let h of new Set(o.reverse()))if(!(h in i))throw new be(`missing required "${h}" claim`,h,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new be('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new be('unexpected "sub" claim value',"sub","check_failed");if(u&&!qI(i.aud,typeof u=="string"?[u]:u))throw new be('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=mn(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,m=fn(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new be('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new be('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>m+d)throw new be('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new be('"exp" claim must be a number',"exp","invalid");if(i.exp<=m-d)throw new sn('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=m-i.iat,g=typeof l=="number"?l:mn(l);if(h-d>g)throw new sn('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(h<0-d)throw new be('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function _y(t,e,r){var n;let i=await Ps(t,e,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new le("JWTs MUST NOT use unencoded payload");let a={payload:yn(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof e=="function"?{...a,key:i.key}:a}var wy=I(()=>{od();As();V();s(_y,"jwtVerify")});async function Ey(t,e,r){let n=await ws(t,e,r),i=yn(n.protectedHeader,n.plaintext,r),{protectedHeader:o}=n;if(o.iss!==void 0&&o.iss!==i.iss)throw new be('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(o.sub!==void 0&&o.sub!==i.sub)throw new be('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(o.aud!==void 0&&JSON.stringify(o.aud)!==JSON.stringify(i.aud))throw new be('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:o};return typeof e=="function"?{...a,key:n.key}:a}var vy=I(()=>{Zl();As();V();s(Ey,"jwtDecrypt")});var gn,cd=I(()=>{Ss();gn=class{static{s(this,"CompactEncrypt")}constructor(e){this._flattened=new Ft(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this._flattened.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var $I,Sy,Ty=I(()=>{nd();Se();gs();id();$I=s(async(t,e,r)=>{let n=await Ti(t,e,"sign");Fr(t,n);let i=await D.subtle.sign(Si(t,n.algorithm),n,r);return new Uint8Array(i)},"sign"),Sy=$I});var dr,Rs=I(()=>{Ie();Ty();cn();V();ge();wi();dn();dr=class{static{s(this,"FlattenedSign")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!vt(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=Tt(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(i.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');lr(a,e,"sign");let c=this._payload;o&&(c=Z.encode(X(c)));let u;this._protectedHeader?u=Z.encode(X(JSON.stringify(this._protectedHeader))):u=Z.encode("");let l=Te(u,Z.encode("."),c),d=await Sy(a,e,l),p={signature:X(d),payload:""};return o&&(p.payload=ue.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ue.decode(u)),p}}});var bn,ud=I(()=>{Rs();bn=class{static{s(this,"CompactSign")}constructor(e){this._flattened=new dr(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var ld,Os,Iy=I(()=>{Rs();V();ld=class{static{s(this,"IndividualSignature")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setProtectedHeader(e){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=e,this}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addSignature(...e){return this.parent.addSignature(...e)}sign(...e){return this.parent.sign(...e)}done(){return this.parent}},Os=class{static{s(this,"GeneralSign")}constructor(e){this._signatures=[],this._payload=e}addSignature(e,r){let n=new ld(this,e,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("at least one signature must be added");let e={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new dr(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:o,...a}=await i.sign(n.key,n.options);if(r===0)e.payload=o;else if(e.payload!==o)throw new z("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(a)}return e}}});var pr,Ns=I(()=>{sd();je();ad();pr=class{static{s(this,"ProduceJWT")}constructor(e){if(!Y(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:e}:this._payload={...this._payload,nbf:fn(new Date)+mn(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:fn(new Date)+mn(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:fn(new Date)}:this._payload={...this._payload,iat:e},this}}});var Cs,Py=I(()=>{ud();V();ge();Ns();Cs=class extends pr{static{s(this,"SignJWT")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var n;let i=new bn(Z.encode(JSON.stringify(this._payload)));if(i.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new le("JWTs MUST NOT use unencoded payload");return i.sign(e,r)}}});var xs,Ay=I(()=>{cd();ge();Ns();xs=class extends pr{static{s(this,"EncryptJWT")}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(e,r){let n=new gn(Z.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(e,r)}}});async function dd(t,e){if(!Y(t))throw new TypeError("JWK must be an object");if(e??(e="sha256"),e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(t.kty){case"EC":hr(t.crv,'"crv" (Curve) Parameter'),hr(t.x,'"x" (X Coordinate) Parameter'),hr(t.y,'"y" (Y Coordinate) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":hr(t.crv,'"crv" (Subtype of Key Pair) Parameter'),hr(t.x,'"x" (Public Key) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":hr(t.e,'"e" (Exponent) Parameter'),hr(t.n,'"n" (Modulus) Parameter'),r={e:t.e,kty:t.kty,n:t.n};break;case"oct":hr(t.k,'"k" (Key Value) Parameter'),r={k:t.k,kty:t.kty};break;default:throw new k('"kty" (Key Type) Parameter missing or unsupported')}let n=Z.encode(JSON.stringify(r));return X(await ns(e,n))}async function Ry(t,e){e??(e="sha256");let r=await dd(t,e);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${e.slice(-3)}:${r}`}var hr,Oy=I(()=>{Nl();Ie();V();ge();je();hr=s((t,e)=>{if(typeof t!="string"||!t)throw new di(`${e} missing or invalid`)},"check");s(dd,"calculateJwkThumbprint");s(Ry,"calculateJwkThumbprintUri")});async function Ny(t,e){let r={...t,...e?.header};if(!Y(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await ur({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new z('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var Cy=I(()=>{_i();je();V();s(Ny,"EmbeddedJWK")});function jI(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new k('Unsupported "alg" value for a JSON Web Key Set')}}function pd(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(VI)}function VI(t){return Y(t)}function GI(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}async function xy(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await ur({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new ir("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function Ly(t){let e=new Ii(t);return async function(r,n){return e.getKey(r,n)}}var Ii,hd=I(()=>{_i();V();je();s(jI,"getKtyFromAlg");s(pd,"isJWKSLike");s(VI,"isJWKLike");s(GI,"clone");Ii=class{static{s(this,"LocalJWKSet")}constructor(e){if(this._cached=new WeakMap,!pd(e))throw new ir("JSON Web Key Set malformed");this._jwks=GI(e)}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},o=jI(n),a=this._jwks.keys.filter(l=>{let d=o===l.kty;if(d&&typeof i=="string"&&(d=i===l.kid),d&&typeof l.alg=="string"&&(d=n===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d&&n==="EdDSA"&&(d=l.crv==="Ed25519"||l.crv==="Ed448"),d)switch(n){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break}return d}),{0:c,length:u}=a;if(u===0)throw new Mr;if(u!==1){let l=new pi,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await xy(d,p,n)}catch{continue}},l}return xy(this._cached,c,n)}};s(xy,"importWithAlgCache");s(Ly,"createLocalJWKSet")});var BI,Dy,Uy=I(()=>{V();BI=s(async(t,e,r)=>{let n,i,o=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{o=!0,n.abort()},e));let a=await fetch(t.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw o?new hi:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new he("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new he("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),Dy=BI});function KI(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function ky(t,e){let r=new fd(t,e);return async function(n,i){return r.getKey(n,i)}}var fd,My=I(()=>{Uy();V();hd();s(KI,"isCloudflareWorkers");fd=class extends Ii{static{s(this,"RemoteJWKSet")}constructor(e,r){if(super({keys:[]}),this._jwks=void 0,!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(e,r)}catch(n){if(n instanceof Mr&&this.coolingDown()===!1)return await this.reload(),super.getKey(e,r);throw n}}async reload(){this._pendingFetch&&KI()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=Dy(this._url,this._timeoutDuration,this._options).then(e=>{if(!pd(e))throw new ir("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}};s(ky,"createRemoteJWKSet")});var Ls,Hy=I(()=>{Ie();ge();V();As();Ns();Ls=class extends pr{static{s(this,"UnsecuredJWT")}encode(){let e=X(JSON.stringify({alg:"none"})),r=X(JSON.stringify(this._payload));return`${e}.${r}.`}static decode(e,r){if(typeof e!="string")throw new le("Unsecured JWT must be a string");let{0:n,1:i,2:o,length:a}=e.split(".");if(a!==3||o!=="")throw new le("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ue.decode(re(n))),c.alg!=="none")throw new Error}catch{throw new le("Invalid Unsecured JWT")}return{payload:yn(c,re(i),r),header:c}}}});var md={};co(md,{decode:()=>Pi,encode:()=>JI});var JI,Pi,Ds=I(()=>{Ie();JI=X,Pi=re});function Fy(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(ue.decode(Pi(e)));if(!Y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var qy=I(()=>{Ds();ge();je();s(Fy,"decodeProtectedHeader")});function $y(t){if(typeof t!="string")throw new le("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new le("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new le("Invalid JWT");if(!e)throw new le("JWTs must contain a payload");let n;try{n=Pi(e)}catch{throw new le("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ue.decode(n))}catch{throw new le("Failed to parse the decoded payload as JSON")}if(!Y(i))throw new le("Invalid JWT Claims Set");return i}var jy=I(()=>{Ds();ge();je();V();s($y,"decodeJwt")});async function Vy(t,e){var r;let n,i,o;switch(t){case"HS256":case"HS384":case"HS512":n=parseInt(t.slice(-3),10),i={name:"HMAC",hash:`SHA-${n}`,length:n},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(t.slice(-3),10),or(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(t.slice(1,4),10),i={name:"AES-KW",length:n},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(t.slice(1,4),10),i={name:"AES-GCM",length:n},o=["encrypt","decrypt"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(i,(r=e?.extractable)!==null&&r!==void 0?r:!1,o)}function yd(t){var e;let r=(e=t?.modulusLength)!==null&&e!==void 0?e:2048;if(typeof r!="number"||r<2048)throw new k("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function Gy(t,e){var r,n,i;let o,a;switch(t){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:yd(e)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:yd(e)},a=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(t.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:yd(e)},a=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},a=["sign","verify"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},a=["sign","verify"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},a=["sign","verify"];break;case"EdDSA":a=["sign","verify"];let c=(r=e?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":o={name:c};break;default:throw new k("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{a=["deriveKey","deriveBits"];let u=(n=e?.crv)!==null&&n!==void 0?n:"P-256";switch(u){case"P-256":case"P-384":case"P-521":{o={name:"ECDH",namedCurve:u};break}case"X25519":case"X448":o={name:u};break;default:throw new k("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(o,(i=e?.extractable)!==null&&i!==void 0?i:!1,a)}var gd=I(()=>{Se();V();fi();s(Vy,"generateSecret");s(yd,"getModulusLengthOption");s(Gy,"generateKeyPair")});async function By(t,e){return Gy(t,e)}var Ky=I(()=>{gd();s(By,"generateKeyPair")});async function Jy(t,e){return Vy(t,e)}var zy=I(()=>{gd();s(Jy,"generateSecret")});var Us={};co(Us,{CompactEncrypt:()=>gn,CompactSign:()=>bn,EmbeddedJWK:()=>Ny,EncryptJWT:()=>xs,FlattenedEncrypt:()=>Ft,FlattenedSign:()=>dr,GeneralEncrypt:()=>Ts,GeneralSign:()=>Os,SignJWT:()=>Cs,UnsecuredJWT:()=>Ls,base64url:()=>md,calculateJwkThumbprint:()=>dd,calculateJwkThumbprintUri:()=>Ry,compactDecrypt:()=>ws,compactVerify:()=>Ps,createLocalJWKSet:()=>Ly,createRemoteJWKSet:()=>ky,decodeJwt:()=>$y,decodeProtectedHeader:()=>Fy,errors:()=>Ll,exportJWK:()=>Es,exportPKCS8:()=>py,exportSPKI:()=>dy,flattenedDecrypt:()=>pn,flattenedVerify:()=>hn,generalDecrypt:()=>ay,generalVerify:()=>yy,generateKeyPair:()=>By,generateSecret:()=>Jy,importJWK:()=>ur,importPKCS8:()=>ry,importSPKI:()=>ey,importX509:()=>ty,jwtDecrypt:()=>Ey,jwtVerify:()=>_y});var ks=I(()=>{Zl();_s();cy();hy();od();Is();gy();wy();vy();cd();Ss();ud();Rs();Iy();Py();Ay();Oy();Cy();hd();My();Hy();Xl();_i();qy();jy();V();Ky();zy();Ds()});var _n=y(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.fetchRetry=void 0;var zI=O();async function WI(t,e,r){for(let n=0;n<=t.retries;n++){let i=fetch(e,r);if(n===t.retries)return i;let o=await i;if(o.status<500&&o.status!==429)return o;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:o.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,n)))}throw new zI.ConfigurationError("An unknown error occurred, ensure retries is not negative")}s(WI,"fetchRetry");Ms.fetchRetry=WI});var wn=y(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.GcpServiceAccount=et.fetchToken=et.exchangeGgpJwtForIdToken=et.exchangeFirebaseJwtForIdToken=et.getTokenFromGcpServiceAccount=void 0;var Wy=(ks(),uo(Us)),QI=O(),YI=_n();async function ZI({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:o,privateKey:a}=t;return await new Wy.SignJWT(n).setProtectedHeader({alg:"RS256",kid:o}).setIssuer(i).setSubject(i).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}s(ZI,"getTokenFromGcpServiceAccount");et.getTokenFromGcpServiceAccount=ZI;async function XI(t,e,r){return _d(t,{token:e,returnSecureToken:!0},r)}s(XI,"exchangeFirebaseJwtForIdToken");et.exchangeFirebaseJwtForIdToken=XI;async function eP(t,e,r){return _d(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}s(eP,"exchangeGgpJwtForIdToken");et.exchangeGgpJwtForIdToken=eP;async function _d(t,e,r){let n=await(0,YI.fetchRetry)(r,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(n.status!==200){let o;try{let a=await n.text(),c=JSON.parse(a);o={cause:c.error??c}}catch{}throw new QI.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:o})}return await n.json()}s(_d,"fetchToken");et.fetchToken=_d;var bd=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:r}){this.#t=e,this.#e=r}static async init(e){let r=JSON.parse(e),n=await(0,Wy.importPKCS8)(r.private_key.trim(),"RS256");return new t({serviceAccount:r,privateKey:n})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};et.GcpServiceAccount=bd});var Fs=y(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.GoogleLogTransport=qt.ZuploToGCPMap=qt.GoogleCloudLoggingPlugin=void 0;var tP=O(),rP=ve(),wd=W(),Ed=wn(),nP=Mt(),Qy=Et(),vd=class extends nP.LogPlugin{static{s(this,"GoogleCloudLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Hs(this.options)}};qt.GoogleCloudLoggingPlugin=vd;var iP="https://logging.googleapis.com/v2/entries:write?alt=json";qt.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var Hs=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#r=e.logName,this.#e=e.serviceAccountJson,this.#i=wd.Environment.instance.loggingEnvironmentType,this.#o=wd.Environment.instance.loggingEnvironmentStage,this.#n=wd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async init(){this.#t=await Ed.GcpServiceAccount.init(this.#e)}log(e,r){if(!this.#t)throw new tP.SystemError("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n={allMessages:(0,Qy.makeErrorsSerializable)(e.messages)},i=this.#t.projectId??"zuplo-production",o={logName:this.#r,resource:{type:"global"},severity:qt.ZuploToGCPMap[e.level],timestamp:e.timestamp,trace:`projects/${i}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};e.rayId&&(o.labels.rayId=e.rayId);let a=(0,Qy.extractBestMessage)(n.allMessages);o.jsonPayload={...n,message:a},this.batcher.enqueue(o),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Ed.GcpServiceAccount.init(this.#e));let r=await(0,Ed.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(iP,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new rP.BatchDispatch("google-log-transport",1,this.dispatchFunction)};qt.GoogleLogTransport=Hs});var Sd=y(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.gcpLogFormat=En.GCP_LOG_FORMAT=void 0;var Yy=Et(),oP=Fs();En.GCP_LOG_FORMAT="gcp";function sP(t){let e={allMessages:(0,Yy.makeErrorsSerializable)(t.messages)},r="zuplo-production",n=(0,Yy.extractBestMessage)(e.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:oP.ZuploToGCPMap[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(i["logging.googleapis.com/labels"].rayId=t.rayId),i}s(sP,"gcpLogFormat");En.gcpLogFormat=sP});var Xy=y(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.ConsoleTransport=void 0;var Zy=Sd(),Td=class{static{s(this,"ConsoleTransport")}constructor(e,r){this.#e=e??console,this.#t=r}#e;#t;log(e){if(this.#t===Zy.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Zy.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};qs.ConsoleTransport=Td});var Nd=y(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.DataDogTransport=vn.DataDogLoggingPlugin=void 0;var aP=ve(),Id=W(),cP=Mt(),eg=Et(),Od=class extends cP.LogPlugin{static{s(this,"DataDogLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new $s(this.options)}};vn.DataDogLoggingPlugin=Od;var Pd="__ddtags",Ad="__ddattr",Rd=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),uP=s(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let i=t[n];i==null?r.push(Rd(n)):r.push(`${Rd(n)}:${Rd(i.toString())}`)}),r.join(",")},"formatTags"),$s=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=Id.Environment.instance.loggingEnvironmentType,this.#i=Id.Environment.instance.loggingEnvironmentStage,this.#r=Id.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){let n={},i=r.custom[Pd];i&&typeof i=="object"&&Object.assign(n,i);let o=[...e.messages],a=e.messages.findIndex(h=>h[Pd]!==void 0);a>-1&&(Object.assign(n,o[a][Pd]),o.splice(a,1));let c={},u=r.custom[Ad];u&&typeof u=="object"&&Object.assign(c,u);let l=e.messages.findIndex(h=>h[Ad]!==void 0);l>-1&&(Object.assign(c,o[l][Ad]),o.splice(l,1));let d=(0,eg.makeErrorsSerializable)(o),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,eg.extractBestMessage)(d),service:e.loggingId,ddtags:uP(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(m,c),this.batcher.enqueue(m),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new aP.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};vn.DataDogTransport=$s});var rg=y(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.ProcessTransport=void 0;var tg=Sd(),Cd=class{static{s(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;log(e){if(this.#t===tg.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,tg.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};js.ProcessTransport=Cd});var ig=y(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.RemoteLogTransport=void 0;var lP=ve(),ng=W(),dP=Et(),pP=s(({url:t,remoteLogToken:e,loggingId:r,sendOnlyErrors:n})=>async i=>{let o;if(n===!0?o=i.filter(a=>a.level==="error"):o=i,o.length!==0)try{await fetch(`${t}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(a=>({...a,messages:(0,dP.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":ng.Environment.instance.systemUserAgent,"zp-dn":ng.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Vs,xd=class{static{s(this,"RemoteLogTransport")}constructor(e){Vs||(Vs=new lP.BatchDispatch("remote-log-transport",1,pP(e)))}log(e,r){Vs.enqueue(e),r.waitUntil(Vs.waitUntilFlushed())}};Gs.RemoteLogTransport=xd});var og=y(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.unifiedFormatter=qr.SeverityNumberOpenTelemetryMap=void 0;qr.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var hP=s((t,e)=>r=>{let n={};return n.deploymentName=t,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:qr.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");qr.unifiedFormatter=hP});var ag=y(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.UnifiedLogTransport=void 0;var fP=ve(),sg=W(),mP=og(),yP=s(({url:t,remoteLogToken:e,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let o=(0,mP.unifiedFormatter)(r,n);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(o)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":sg.Environment.instance.systemUserAgent,"zp-dn":sg.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Bs,Ld=class{static{s(this,"UnifiedLogTransport")}constructor(e){Bs||(Bs=new fP.BatchDispatch("unified-log-transport",1,yP(e)))}async log(e,r){Bs.enqueue(e),r.waitUntil(Bs.waitUntilFlushed())}};Ks.UnifiedLogTransport=Ld});var fg=y(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.LogInitializer=void 0;var gP=Or(),bP=_t(),cg=_l(),ug=W(),lg=pm(),_P=Mt(),wP=hm(),dg=fm(),pg=Xy(),EP=Nd(),vP=Fs(),hg=rg(),SP=ig(),TP=ag(),Dd=(0,gP.debug)("zuplo:logging"),Ud=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:r}){this.systemCoreLogger=e,this.userCoreLogger=r}static async init(e){let r=await t.setupSystemCoreLogger(ug.Environment.instance,e),n=await t.setupUserCoreLogger(ug.Environment.instance,e);return new t({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(e,r){let{build:n}=e;Dd("Gateway.setupSystemCoreLogger");let i=[],o=r.getService(cg.SYSTEM_LOGGER);return o?i.push(new hg.ProcessTransport(o.logger,e.logFormat)):e.isDeno&&i.push(new pg.ConsoleTransport(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&i.push(new TP.UnifiedLogTransport({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(i.map(async a=>{a.init&&await a.init()})),new lg.CoreLogger(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,i)}static async setupUserCoreLogger(e,r){Dd("Gateway.setupUserCoreLogger");let n=[],{runtime:i,build:o}=e,a=r.getService(cg.SYSTEM_LOGGER);if(a&&a.captureUserLogs===!0?n.push(new hg.ProcessTransport(a.logger,e.logFormat)):e.isDeno&&n.push(new pg.ConsoleTransport(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new SP.RemoteLogTransport({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),i.GCP_USER_LOG_NAME&&i.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new vP.GoogleLogTransport({serviceAccountJson:i.GCP_USER_LOG_SVC_ACCT_JSON,logName:i.GCP_USER_LOG_NAME})),i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let c=i.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new EP.DataDogTransport({apiKey:i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return bP.plugins.forEach(c=>{c instanceof _P.LogPlugin&&n.push(c.getTransport())}),await Promise.all(n.map(async c=>{c.init&&await c.init()})),new lg.CoreLogger(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,r,n,i,o){Dd("Gateway.createRequestLoggers");let a=new wP.LoggingContext(n,i,o),c=new dg.RequestLogger(e,r,this.systemCoreLogger,a);return{userRequestLogger:new dg.RequestLogger(e,r,this.userCoreLogger,a),systemRequestLogger:c}}};Js.LogInitializer=Ud});var Md=y(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.UserRouteConfiguration=void 0;var kd=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};zs.UserRouteConfiguration=kd});var Fd=y(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.Router=It.RouterError=It.LookupResult=It.RouterEntry=void 0;var mg=O(),IP=at(),PP=Md(),Ws=class{static{s(this,"RouterEntry")}constructor(e,r,n,i){this.fullPath=e,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};It.RouterEntry=Ws;var Ai=class{static{s(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};It.LookupResult=Ai;var Qs=class extends Error{static{s(this,"RouterError")}constructor(e,r){super(e,r)}};It.RouterError=Qs;var Hd=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,r){if(!(e instanceof PP.UserRouteConfiguration||e instanceof IP.SystemRouteConfiguration))throw new mg.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(o=>o.name===e.version)?.pathPrefix,i;"pathPattern"in e&&e.pathPattern?i=`${n??""}${e.pathPattern}`:i=`${n??""}${e.path}`;try{let o=new URLPattern({pathname:i}),a=new Ws(i,o,e,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(o){throw new Qs(`addRoute-error: Invalid path '${i}'. '${o.message}'`,{cause:o})}}lookup(e,r){if(typeof e>"u")throw new mg.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(e));if(n.length!==0)for(let i=0;i<n.length;i++){let o=n[i],c=o.urlPattern.exec({pathname:r});if(c!==null)return new Ai(o.config,o.executableHandler,c.pathname.groups)}}lookupByPathOnly(e){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:e});if(a!==null){let c=new Ai(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};It.Router=Hd});var Nr=y(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});Zs.Gateway=void 0;var AP=Or(),yg=$f(),gg=Wf(),RP=Qf(),bg=Yf(),_g=tm(),$t=Ar(),Ys=Cr(),wg=dm(),At=O(),Ri=_t(),OP=fg(),NP=Ut(),CP=te(),xP=dl(),LP=Yt(),DP=tn(),UP=He(),kP=Fd(),qd=at(),Eg=Md(),MP=Fe(),HP=Vo(),$d=W(),vg=kr(),Sg=Bu(),Pt=(0,AP.debug)("zuplo:runtime"),FP=s(t=>{let e=t.findIndex(r=>r.name===qd.systemNoVersion.name);return e>-1?[...t.splice(e),qd.systemNoVersion]:[...t,qd.systemNoVersion]},"setupSystemNoVersion"),jd=class t{static{s(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(e,r,n,i){this.routeData=e,this.runtimeSettings=r,this.schemaValidator=i,Pt("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=n}static async initialize(e,r,n,i,o){if(Pt("Gateway.initialize"),!t.#e){await(0,Ri.initializeRuntime)(o);let a=await OP.LogInitializer.init(n),c=e(),u={...c,corsPolicies:(0,HP.parseCorsPolicies)(c.corsPolicies)},l=new t(u,r,a,i);t.#e=l}return t.#e}static purgeGatewayCache(){Pt("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new At.SystemError("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#r;#n=[DP.policyProcessor,xP.corsProcessor,LP.metricsProcessor];#i;setupRoutes=()=>{Pt("Gateway.setupRoutes");let e=this.routeData,r=FP(e.versions),n=new kP.Router(r);if(e.routes.length===0)return(0,yg.registerBuildRoute)(n,this),(0,_g.registerPingRoute)(n,this),(0,gg.registerCorsRoute)(n,this),(0,RP.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;i&&((0,wg.registerDevPortalLegacyRedirectRoute)(n,this),(0,wg.registerDevPortalV3Route)(n,this)),(0,yg.registerBuildRoute)(n,this),(0,_g.registerPingRoute)(n,this),(0,gg.registerCorsRoute)(n,this);for(let o of Ri.plugins)o instanceof Ri.SystemRuntimePlugin&&o.registerRoutes(n,this);return e.routes.forEach(o=>{let a;if(typeof o.handler?.module=="object"&&(a=o.handler?.module[o.handler.export]),typeof a!="function")throw new At.ConfigurationError(`Invalid state - No handler on route for path '${o.path}'`);let c=new NP.Pipeline({processors:this.#n,handler:a,gateway:this}),u=new Eg.UserRouteConfiguration(o);n.addRoute(u,c.execute)}),(0,bg.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new At.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((r,n,i)=>this.#o(r,n,i),"errorHandler");return e};errorHandler(e,r,n){try{return this.#i(e,r,n)}catch(i){return Pt("An error occurred in the user's errorHandler",i),this.#o(e,r,i)}}#o(e,r,n){Pt("Gateway.internalErrorResponse");let i={};if($d.Environment.instance.isDeno){if(n instanceof At.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let o=(0,vg.serializeError)(n.cause);"stack"in o&&(o.stack=(0,vg.cleanStack)(o.stack)),i={cause:o}}}return CP.HttpProblems.internalServerError(e,r,{detail:n.message,...i})}#s(e){let r=new Headers(e.headers);return $t.DISPATCH_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),$d.Environment.instance.isDeno&&$t.INTERNAL_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),new Request(e,{headers:r})}async handleRequest(e,r){let n=e.headers.get($t.REQUEST_ID_HEADER)??e.headers.get($t.LEGACY_REQUEST_ID_HEADER),i=e.headers.get($t.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let S=new Headers(e.headers);S.set($t.REQUEST_ID_HEADER,n),e=new Request(e,{headers:S})}if(["GET","HEAD"].includes(e.method)&&e.body){let S=new Headers(e.headers);S.set($t.BODY_REMOVED_HEADER,"true"),e=new Request(e,{headers:S,body:null})}let o={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,o,e),u=new URL(e.url),l=u.pathname,d=this.#r.lookup(e.method,l);if(!d)throw new At.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Ys.HeaderIncomingRequestProperties(e.headers),m=this.#s(e),h=new UP.ZuploRequest(m,{params:d.params}),g=new Ys.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,event:r,custom:o,incomingRequestProperties:p}),_=Ys.ZuploContextExtensions.initialize(g,h);if(d.routeConfiguration===bg.notFoundRouteConfiguration&&Ri.runtimeExtensions.value?.notFoundHandler!==void 0){let S=this.#r.lookupByPathOnly(l);_.pathOnlyMatches=S.map(T=>T.routeConfiguration).filter(T=>T instanceof Eg.UserRouteConfiguration)}try{if(MP.SystemLogMap.addLogger(g,c),$d.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!(0,Sg.isSystemRoute)(u):!u.pathname.startsWith("/__zuplo")){let M=await(0,Ri.invokeOnRequestExtensions)(h,g);if(M instanceof Response)return M;{let j=Ys.ZuploContextExtensions.getContextExtensions(g);h=M,j.latestRequest=h}}(0,Sg.isSystemRoute)(u)||a.debug(`Request received '${u.pathname}'`,{method:e.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let S=d.executableHandler;qP(S,d,e),Pt("Gateway.handleRequest - call user handler");let T=await S(h,g);if(Pt("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new At.RuntimeError(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new At.RuntimeError("The response object has already been used. Return a new response instead.");if(T.headers.get($t.REQUEST_ID_HEADER)===null&&!T.webSocket){let M=new Headers(T.headers);return M.set($t.REQUEST_ID_HEADER,n),new Response(T.body,{status:T.status,statusText:T.statusText,headers:M,cf:T.cf})}else return T}catch(S){return Pt("Gateway - error executing handler",S),S instanceof At.RuntimeError?(a.error(S),c.warn(S)):c.error(S),await this.#o(h,g,S)}}};Zs.Gateway=jd;function qP(t,e,r){if(Pt("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new At.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new At.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}s(qP,"checkHandler")});var Tg=y(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.invokeInboundPolicy=void 0;var $P=O(),jP=Nr(),VP=tn(),GP=s(async(t,e,r)=>{let n=jP.Gateway.instance.routeData.policies,i=(0,VP.getInboundPolicyInstances)([t],n);if(i.length===0)throw new $P.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return i[0].handler(e,r)},"invokeInboundPolicy");Xs.invokeInboundPolicy=GP});var Cr=y(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.SystemZuploContext=tt.ZuploContextExtensions=tt.ResponseSentEvent=tt.ResponseSendingEvent=tt.HeaderIncomingRequestProperties=void 0;var _e=Ar(),BP=O(),KP=Tg(),Vd=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(_e.ZP_ASN_HEADER);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(_e.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(_e.CF_IP_CITY_HEADER)??this.#e.get(_e.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(_e.CF_IP_CONTINENT_HEADER)??this.#e.get(_e.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(_e.CF_IP_COUNTRY_HEADER)??this.#e.get(_e.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(_e.CF_IP_LATITUDE_HEADER)??this.#e.get(_e.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(_e.CF_IP_LONGITUDE_HEADER)??this.#e.get(_e.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(_e.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(_e.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(_e.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(_e.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(_e.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(_e.ZP_TIMEZONE_HEADER)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}};tt.HeaderIncomingRequestProperties=Vd;var Gd=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse};tt.ResponseSendingEvent=Gd;var Bd=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response};tt.ResponseSentEvent=Bd;var Oi=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,r){if(!t.#e.has(e)){let n=new t(r);return t.#e.set(e,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let r=t.#e.get(e);if(!r)throw new BP.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#r=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,r,n)=>{for(let i of this.#t)await i(e,r,n)};onResponseSending=async(e,r,n)=>{let i=e;for(let o of this.#r)i=await o(e,r,n);return i}};tt.ZuploContextExtensions=Oi;var Kd=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:n,event:i,custom:o,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=r,this.requestId=n,this.custom=o,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,KP.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Oi.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Oi.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,r,n){let i=s(o=>{try{typeof r=="function"?r(o):r.handleEvent(o)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,i,n)}};tt.SystemZuploContext=Kd});var ta=y(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.ContextData=void 0;var Jd=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let i=t.#e.get(e);i||(i=new Map),i.set(r,n),t.#e.set(e,i)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};ea.ContextData=Jd});var Sn=y(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.environment=fr.isZuploReadableEnvVariableName=fr.isRestrictedEnvVariableName=void 0;var JP=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ig(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!JP.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(Ig,"isRestrictedEnvVariableName");fr.isRestrictedEnvVariableName=Ig;function Pg(t){return!!t.startsWith("ZUPLO_")}s(Pg,"isZuploReadableEnvVariableName");fr.isZuploReadableEnvVariableName=Pg;var zP=new Proxy({},{get(t,e){if(Ig(String(e))&&!Pg(String(e)))return;let r=globalThis,n;return r.process?n=r.process.env[e]:n=r[e],n}});fr.environment=zP});var zd=y(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.externalServiceHandler=Tn.externalServiceTunnelConfig=void 0;var WP=Or(),$r=O(),QP=Wd(),Ni=W(),dt=(0,WP.debug)("zuplo:runtime:external-service");function Rg(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=Ni.Environment.instance.runtime;if(e&&e!=="undefined")try{let r=atob(e);t=JSON.parse(r)}catch{}return t}s(Rg,"getServiceAuth");async function YP(t){let e=Rg();if(!e)throw dt("There is no external service auth configured for this zup."),new $r.RuntimeError("There are no external services configured for this zup.");if(typeof t!="string")throw dt("Cannot call external service with Request object"),new $r.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(t).hostname,i={};i["CF-Access-Client-Id"]=e.clientId,i["CF-Access-Client-Secret"]=e.clientSecret;let o;if(e.customServiceMapping&&e.customServiceMapping[n])o=`https://${e.customServiceMapping[n]}`;else if(Ni.Environment.instance.useSha256ServiceRouting){dt("Using sha256 service routing");let a=Ni.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)o=`https://${await Og(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw dt("Cannot use sha256 service routing, missing build variables"),new $r.RuntimeError("Failed to generate fully qualified tunnel url.")}else o=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:o,tunnelHeaders:i}}s(YP,"externalServiceTunnelConfig");Tn.externalServiceTunnelConfig=YP;async function ZP(t,e){let r=Rg();if(r)if(dt(`Using external service auth. ClientId: ${r.clientId})`),typeof t=="string"){let n=new URL(t),i=n.hostname,o=e??{},a=new Headers(o.headers||{});a.set("CF-Access-Client-Id",r.clientId),a.set("CF-Access-Client-Secret",r.clientSecret),o.headers=a;let c;if(r.customServiceMapping&&r.customServiceMapping[i])c=`https://${r.customServiceMapping[i]}`;else if(Ni.Environment.instance.useSha256ServiceRouting){dt("Using sha256 service routing");let d=Ni.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await Og(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw dt("Cannot use sha256 service routing, missing build variables"),new $r.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);dt(`Calling external service: ${u.toString()}`);let l=await(0,QP.originalFetch)(u.toString(),o);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:c}),new $r.RuntimeError("Could not connect to secure tunnel.");return l}else throw dt("Cannot call external service with Request object"),new $r.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw dt("There is no external service auth configured for this zup."),new $r.RuntimeError("There are no external services configured for this zup.")}s(ZP,"externalServiceHandler");Tn.externalServiceHandler=ZP;async function Og(t,e,r,n){let i=t.toLowerCase(),o=e.toLowerCase(),a=r.toLowerCase(),c=XP(n);dt(`Hashing service name: ${o}-${i}.${o}-${a}-${c}`);let u=await Ag(`${o}-${i}`),l=await Ag(`${o}-${a}-${c}`);return`${u}.${l}`}s(Og,"hashServiceName");async function Ag(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ag,"hashSegment");function XP(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(XP,"sanitizeEnvironmentType")});var Wd=y(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.originalFetch=void 0;var eA=zd(),Ng=new Map;Ng.set("service:",eA.externalServiceHandler);In.originalFetch=globalThis.fetch;globalThis.fetch=function(t,e){let r=tA(e);if(typeof t=="string"){let n=new URL(t),i=Ng.get(n.protocol);return i?i(t,r):(0,In.originalFetch)(t,r)}else return(0,In.originalFetch)(t,r)};var tA=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let r=t;return r.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit")});var Lg=y(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.Handler=Pn.purgeGatewayCache=void 0;var rA=O(),xg=Nr(),Cg=W(),nA=s(()=>{xg.Gateway.purgeGatewayCache()},"purgeGatewayCache");Pn.purgeGatewayCache=nA;var Qd=class{static{s(this,"Handler")}routeLoader;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(e,r,n,i,o,a,c){this.routeLoader=e,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=o,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(e,r)=>{Cg.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await xg.Gateway.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let o="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";i instanceof rA.ConfigurationError&&(o=i.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:o,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:Cg.Environment.instance.isDeno?i.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return n.handleRequest(e,r)}};Pn.Handler=Qd});var Mg=y(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.pathToRegexp=Re.tokensToRegexp=Re.regexpToFunction=Re.match=Re.tokensToFunction=Re.compile=Re.parse=void 0;function iA(t){for(var e=[],r=0;r<t.length;){var n=t[r];if(n==="*"||n==="+"||n==="?"){e.push({type:"MODIFIER",index:r,value:t[r++]});continue}if(n==="\\"){e.push({type:"ESCAPED_CHAR",index:r++,value:t[r++]});continue}if(n==="{"){e.push({type:"OPEN",index:r,value:t[r++]});continue}if(n==="}"){e.push({type:"CLOSE",index:r,value:t[r++]});continue}if(n===":"){for(var i="",o=r+1;o<t.length;){var a=t.charCodeAt(o);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=t[o++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));e.push({type:"NAME",index:r,value:i}),r=o;continue}if(n==="("){var c=1,u="",o=r+1;if(t[o]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(o));for(;o<t.length;){if(t[o]==="\\"){u+=t[o++]+t[o++];continue}if(t[o]===")"){if(c--,c===0){o++;break}}else if(t[o]==="("&&(c++,t[o+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(o));u+=t[o++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));e.push({type:"PATTERN",index:r,value:u}),r=o;continue}e.push({type:"CHAR",index:r,value:t[r++]})}return e.push({type:"END",index:r,value:""}),e}s(iA,"lexer");function Yd(t,e){e===void 0&&(e={});for(var r=iA(t),n=e.prefixes,i=n===void 0?"./":n,o="[^".concat(An(e.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=s(function(ie){if(u<r.length&&r[u].type===ie)return r[u++].value},"tryConsume"),p=s(function(ie){var me=d(ie);if(me!==void 0)return me;var Ke=r[u],E=Ke.type,H=Ke.index;throw new TypeError("Unexpected ".concat(E," at ").concat(H,", expected ").concat(ie))},"mustConsume"),m=s(function(){for(var ie="",me;me=d("CHAR")||d("ESCAPED_CHAR");)ie+=me;return ie},"consumeText");u<r.length;){var h=d("CHAR"),g=d("NAME"),_=d("PATTERN");if(g||_){var S=h||"";i.indexOf(S)===-1&&(l+=S,S=""),l&&(a.push(l),l=""),a.push({name:g||c++,prefix:S,suffix:"",pattern:_||o,modifier:d("MODIFIER")||""});continue}var T=h||d("ESCAPED_CHAR");if(T){l+=T;continue}l&&(a.push(l),l="");var M=d("OPEN");if(M){var S=m(),j=d("NAME")||"",L=d("PATTERN")||"",ne=m();p("CLOSE"),a.push({name:j||(L?c++:""),pattern:j&&!L?o:L,prefix:S,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Yd,"parse");Re.parse=Yd;function oA(t,e){return Dg(Yd(t,e),e)}s(oA,"compile");Re.compile=oA;function Dg(t,e){e===void 0&&(e={});var r=Zd(e),n=e.encode,i=n===void 0?function(u){return u}:n,o=e.validate,a=o===void 0?!0:o,c=t.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var m=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",g=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!g)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var _=0;_<m.length;_++){var S=i(m[_],p);if(a&&!c[d].test(S))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var S=i(String(m),p);if(a&&!c[d].test(S))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix;continue}if(!h){var T=g?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(T))}}return l}}s(Dg,"tokensToFunction");Re.tokensToFunction=Dg;function sA(t,e){var r=[],n=Xd(t,r,e);return Ug(n,r,e)}s(sA,"match");Re.match=sA;function Ug(t,e,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(o){return o}:n;return function(o){var a=t.exec(o);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=s(function(m){if(a[m]===void 0)return"continue";var h=e[m-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[m].split(h.prefix+h.suffix).map(function(g){return i(g,h)}):l[h.name]=i(a[m],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}s(Ug,"regexpToFunction");Re.regexpToFunction=Ug;function An(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(An,"escapeString");function Zd(t){return t&&t.sensitive?"":"i"}s(Zd,"flags");function aA(t,e){if(!e)return t;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(t.source);i;)e.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(t.source);return t}s(aA,"regexpToRegexp");function cA(t,e,r){var n=t.map(function(i){return Xd(i,e,r).source});return new RegExp("(?:".concat(n.join("|"),")"),Zd(r))}s(cA,"arrayToRegexp");function uA(t,e,r){return kg(Yd(t,r),e,r)}s(uA,"stringToRegexp");function kg(t,e,r){r===void 0&&(r={});for(var n=r.strict,i=n===void 0?!1:n,o=r.start,a=o===void 0?!0:o,c=r.end,u=c===void 0?!0:c,l=r.encode,d=l===void 0?function(H){return H}:l,p=r.delimiter,m=p===void 0?"/#?":p,h=r.endsWith,g=h===void 0?"":h,_="[".concat(An(g),"]|$"),S="[".concat(An(m),"]"),T=a?"^":"",M=0,j=t;M<j.length;M++){var L=j[M];if(typeof L=="string")T+=An(d(L));else{var ne=An(d(L.prefix)),ie=An(d(L.suffix));if(L.pattern)if(e&&e.push(L),ne||ie)if(L.modifier==="+"||L.modifier==="*"){var me=L.modifier==="*"?"?":"";T+="(?:".concat(ne,"((?:").concat(L.pattern,")(?:").concat(ie).concat(ne,"(?:").concat(L.pattern,"))*)").concat(ie,")").concat(me)}else T+="(?:".concat(ne,"(").concat(L.pattern,")").concat(ie,")").concat(L.modifier);else L.modifier==="+"||L.modifier==="*"?T+="((?:".concat(L.pattern,")").concat(L.modifier,")"):T+="(".concat(L.pattern,")").concat(L.modifier);else T+="(?:".concat(ne).concat(ie,")").concat(L.modifier)}}if(u)i||(T+="".concat(S,"?")),T+=r.endsWith?"(?=".concat(_,")"):"$";else{var Ke=t[t.length-1],E=typeof Ke=="string"?S.indexOf(Ke[Ke.length-1])>-1:Ke===void 0;i||(T+="(?:".concat(S,"(?=").concat(_,"))?")),E||(T+="(?=".concat(S,"|").concat(_,")"))}return new RegExp(T,Zd(r))}s(kg,"tokensToRegexp");Re.tokensToRegexp=kg;function Xd(t,e,r){return t instanceof RegExp?aA(t,e):Array.isArray(t)?cA(t,e,r):uA(t,e,r)}s(Xd,"pathToRegexp");Re.pathToRegexp=Xd});var np=y(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.AwsV4Signer=Rn.AwsClient=void 0;var lA=Or(),$g=O(),dA=(0,lA.debug)("zuplo:runtime"),tp=new TextEncoder,Hg={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},pA=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],rp=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:r,sessionToken:n,service:i,region:o,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=r,this.sessionToken=n,this.service=i,this.region=o,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,r){let n=new ra(Object.assign({url:e},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(e,r){dA("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:i,request:o}=await this.sign(e,r),a=fetch(i,o);if(n===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new $g.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};Rn.AwsClient=rp;var ra=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:r,headers:n,body:i,accessKeyId:o,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:g,singleEncode:_}){if(r==null)throw new TypeError("url is a required option");if(o==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(i?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=i,this.accessKeyId=o,this.secretAccessKey=a,this.sessionToken=c;let S,T;(!u||!l)&&([S,T]=hA(this.url,this.headers)),this.service=u||S||"",this.region=l||T||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let M=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),M.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&M.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>g||!pA.includes(L)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(L=>L+":"+(L==="host"?this.url.host:(this.headers.get(L)||"").replace(/\s+/g," "))).join(`
|
|
60
60
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!M.has("X-Amz-Expires")&&M.set("X-Amz-Expires","86400"),M.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),M.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),M.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");_||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=qg(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([L])=>{if(!L)return!1;if(this.service==="s3"){if(j.has(L))return!1;j.add(L)}return!0}).map(L=>L.map(ne=>qg(encodeURIComponent(ne)))).sort(([L,ne],[ie,me])=>L<ie?-1:L>ie?1:ne<me?-1:ne>me?1:0).map(L=>L.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),r=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(r);if(!n){let i=await Ci("AWS4"+this.secretAccessKey,e),o=await Ci(i,this.region),a=await Ci(o,this.service);n=await Ci(a,"aws4_request"),this.cache.set(r,n)}return ep(await Ci(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,ep(await Fg(await this.canonicalString()))].join(`
|
|
61
61
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
62
62
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|