@zuplo/graphql 5.1761.0 → 5.1763.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.minified.js +2 -2
- package/package.json +1 -1
package/index.minified.js
CHANGED
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
`)}s(US,"messagesToMultilineText");Fe.messagesToMultilineText=US;function Vf(e){return typeof e=="string"?e:JSON.stringify(e)}s(Vf,"stringifyNonString");Fe.stringifyNonString=Vf;function Gf(e){return typeof e=="string"?e:e===null?"null":typeof e>"u"?"undefined":typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"?e.toString():typeof e=="function"?`[function ${e.name}]`:typeof e=="object"&&Array.isArray(e)?`[array ${e.length}]`:e instanceof Error?`${e.name??"Error"}: ${e.message??"unknown"}`:typeof e=="object"?(0,jf.toString)(e):"unknown"}s(Gf,"stringifyNonStringToText");Fe.stringifyNonStringToText=Gf});var D,ae,Te=I(()=>{D=crypto,ae=s(e=>e instanceof CryptoKey,"isCryptoKey")});var MS,Jo,dl=I(()=>{Te();MS=s(async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await D.subtle.digest(r,t))},"digest"),Jo=MS});function Se(...e){let t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r}function Bf(e,t){return Se(Z.encode(e),new Uint8Array([0]),t)}function pl(e,t,r){if(t<0||t>=zo)throw new RangeError(`value must be >= 0 and <= ${zo-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function Wo(e){let t=Math.floor(e/zo),r=e%zo,n=new Uint8Array(8);return pl(n,t,0),pl(n,r,4),n}function Qo(e){let t=new Uint8Array(4);return pl(t,e),t}function Yo(e){return Se(Qo(e.length),e)}async function Kf(e,t,r){let n=Math.ceil((t>>3)/32),i=new Uint8Array(n*32);for(let o=0;o<n;o++){let a=new Uint8Array(4+e.length+r.length);a.set(Qo(o+1)),a.set(e,4),a.set(r,4+e.length),i.set(await Jo("sha256",a),o*32)}return i.slice(0,t>>3)}var Z,ue,zo,ge=I(()=>{dl();Z=new TextEncoder,ue=new TextDecoder,zo=2**32;s(Se,"concat");s(Bf,"p2s");s(pl,"writeUInt32BE");s(Wo,"uint64be");s(Qo,"uint32be");s(Yo,"lengthAndInput");s(Kf,"concatKdf")});var Zo,X,hl,re,Ie=I(()=>{ge();Zo=s(e=>{let t=e;typeof t=="string"&&(t=Z.encode(t));let r=32768,n=[];for(let i=0;i<t.length;i+=r)n.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));return btoa(n.join(""))},"encodeBase64"),X=s(e=>Zo(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),"encode"),hl=s(e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},"decodeBase64"),re=s(e=>{let t=e;t instanceof Uint8Array&&(t=ue.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return hl(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}},"decode")});var fl={};ro(fl,{JOSEAlgNotAllowed:()=>tr,JOSEError:()=>he,JOSENotSupported:()=>M,JWEDecryptionFailed:()=>Mt,JWEInvalid:()=>A,JWKInvalid:()=>ai,JWKSInvalid:()=>rr,JWKSMultipleMatchingKeys:()=>ci,JWKSNoMatchingKey:()=>Cr,JWKSTimeout:()=>ui,JWSInvalid:()=>z,JWSSignatureVerificationFailed:()=>Lr,JWTClaimValidationFailed:()=>be,JWTExpired:()=>Xr,JWTInvalid:()=>le});var he,be,Xr,tr,M,Mt,A,z,le,ai,rr,Cr,ci,ui,Lr,j=I(()=>{he=class extends Error{static{s(this,"JOSEError")}static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),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(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},Xr=class extends he{static{s(this,"JWTExpired")}static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},tr=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"}},M=class extends he{static{s(this,"JOSENotSupported")}constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},Mt=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"}},A=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"}},ai=class extends he{static{s(this,"JWKInvalid")}constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},rr=class extends he{static{s(this,"JWKSInvalid")}constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Cr=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"}},ci=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"}},ui=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"}},Lr=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 nr,li=I(()=>{Te();nr=D.getRandomValues.bind(D)});function ml(e){switch(e){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 M(`Unsupported JWE Algorithm: ${e}`)}}var Xo,es=I(()=>{j();li();s(ml,"bitLength");Xo=s(e=>nr(new Uint8Array(ml(e)>>3)),"default")});var kS,ts,yl=I(()=>{j();es();kS=s((e,t)=>{if(t.length<<3!==ml(e))throw new A("Invalid Initialization Vector length")},"checkIvLength"),ts=kS});var HS,en,gl=I(()=>{j();HS=s((e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new A(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},"checkCekLength"),en=HS});var FS,zf,Wf=I(()=>{FS=s((e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,i=-1;for(;++i<r;)n|=e[i]^t[i];return n===0},"timingSafeEqual"),zf=FS});function Pe(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ir(e,t){return e.name===t}function rs(e){return parseInt(e.name.slice(4),10)}function qS(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Qf(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Yf(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ir(e.algorithm,"HMAC"))throw Pe("HMAC");let n=parseInt(t.slice(2),10);if(rs(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ir(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Pe("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(rs(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ir(e.algorithm,"RSA-PSS"))throw Pe("RSA-PSS");let n=parseInt(t.slice(2),10);if(rs(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw Pe("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ir(e.algorithm,"ECDSA"))throw Pe("ECDSA");let n=qS(t);if(e.algorithm.namedCurve!==n)throw Pe(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Qf(e,r)}function qe(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!ir(e.algorithm,"AES-GCM"))throw Pe("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw Pe(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!ir(e.algorithm,"AES-KW"))throw Pe("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw Pe(n,"algorithm.length");break}case"ECDH":{switch(e.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(!ir(e.algorithm,"PBKDF2"))throw Pe("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!ir(e.algorithm,"RSA-OAEP"))throw Pe("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(rs(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Qf(e,r)}var or=I(()=>{s(Pe,"unusable");s(ir,"isAlgorithm");s(rs,"getHashLength");s(qS,"getNamedCurve");s(Qf,"checkUsage");s(Yf,"checkSigCryptoKey");s(qe,"checkEncCryptoKey")});function Zf(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function bl(e,t,...r){return Zf(`Key for the ${e} algorithm must be `,t,...r)}var oe,ct=I(()=>{s(Zf,"message");oe=s((e,...t)=>Zf("Key must be ",e,...t),"default");s(bl,"withAlg")});var _l,Q,ut=I(()=>{Te();_l=s(e=>ae(e),"default"),Q=["CryptoKey"]});async function $S(e,t,r,n,i,o){if(!(t instanceof Uint8Array))throw new TypeError(oe(t,"Uint8Array"));let a=parseInt(e.slice(1,4),10),c=await D.subtle.importKey("raw",t.subarray(a>>3),"AES-CBC",!1,["decrypt"]),u=await D.subtle.importKey("raw",t.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),l=Se(o,n,r,Wo(o.length<<3)),d=new Uint8Array((await D.subtle.sign("HMAC",u,l)).slice(0,a>>3)),p;try{p=zf(i,d)}catch{}if(!p)throw new Mt;let f;try{f=new Uint8Array(await D.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!f)throw new Mt;return f}async function jS(e,t,r,n,i,o){let a;t instanceof Uint8Array?a=await D.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(qe(t,e,"decrypt"),a=t);try{return new Uint8Array(await D.subtle.decrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,Se(r,i)))}catch{throw new Mt}}var VS,ns,El=I(()=>{ge();yl();gl();Wf();j();Te();or();ct();ut();s($S,"cbcDecrypt");s(jS,"gcmDecrypt");VS=s(async(e,t,r,n,i,o)=>{if(!ae(t)&&!(t instanceof Uint8Array))throw new TypeError(oe(t,...Q,"Uint8Array"));switch(ts(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&en(t,parseInt(e.slice(-3),10)),$S(e,t,r,n,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&en(t,parseInt(e.slice(1,4),10)),jS(e,t,r,n,i,o);default:throw new M("Unsupported JWE Content Encryption Algorithm")}},"decrypt"),ns=VS});var Xf,em,wl=I(()=>{j();Xf=s(async()=>{throw new M('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"),em=s(async()=>{throw new M('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 GS,Et,tn=I(()=>{GS=s((...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){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"),Et=GS});function BS(e){return typeof e=="object"&&e!==null}function Y(e){if(!BS(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var $e=I(()=>{s(BS,"isObjectLike");s(Y,"isObject")});var KS,rn,vl=I(()=>{KS=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],rn=KS});function tm(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function rm(e,t,r){if(ae(e))return qe(e,t,r),e;if(e instanceof Uint8Array)return D.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(oe(e,...Q,"Uint8Array"))}var di,pi,is=I(()=>{vl();Te();or();ct();ut();s(tm,"checkKeySize");s(rm,"getCryptoKey");di=s(async(e,t,r)=>{let n=await rm(t,e,"wrapKey");tm(n,e);let i=await D.subtle.importKey("raw",r,...rn);return new Uint8Array(await D.subtle.wrapKey("raw",i,n,"AES-KW"))},"wrap"),pi=s(async(e,t,r)=>{let n=await rm(t,e,"unwrapKey");tm(n,e);let i=await D.subtle.unwrapKey("raw",r,n,"AES-KW",...rn);return new Uint8Array(await D.subtle.exportKey("raw",i))},"unwrap")});async function os(e,t,r,n,i=new Uint8Array(0),o=new Uint8Array(0)){if(!ae(e))throw new TypeError(oe(e,...Q));if(qe(e,"ECDH"),!ae(t))throw new TypeError(oe(t,...Q));qe(t,"ECDH","deriveBits");let a=Se(Yo(Z.encode(r)),Yo(i),Yo(o),Qo(n)),c;e.algorithm.name==="X25519"?c=256:e.algorithm.name==="X448"?c=448:c=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let u=new Uint8Array(await D.subtle.deriveBits({name:e.algorithm.name,public:e},t,c));return Kf(u,n,a)}async function nm(e){if(!ae(e))throw new TypeError(oe(e,...Q));return D.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function ss(e){if(!ae(e))throw new TypeError(oe(e,...Q));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}var Tl=I(()=>{ge();Te();or();ct();ut();s(os,"deriveKey");s(nm,"generateEpk");s(ss,"ecdhAllowed")});function Sl(e){if(!(e instanceof Uint8Array)||e.length<8)throw new A("PBES2 Salt Input must be 8 or more octets")}var om=I(()=>{j();s(Sl,"checkP2s")});function JS(e,t){if(e instanceof Uint8Array)return D.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(ae(e))return qe(e,t,"deriveBits","deriveKey"),e;throw new TypeError(oe(e,...Q,"Uint8Array"))}async function sm(e,t,r,n){Sl(e);let i=Bf(t,e),o=parseInt(t.slice(13,16),10),a={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},c={length:o,name:"AES-KW"},u=await JS(n,t);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 am,cm,Il=I(()=>{li();ge();Ie();is();om();Te();or();ct();ut();s(JS,"getCryptoKey");s(sm,"deriveKey");am=s(async(e,t,r,n=2048,i=nr(new Uint8Array(16)))=>{let o=await sm(i,e,n,t);return{encryptedKey:await di(e.slice(-6),o,r),p2c:n,p2s:X(i)}},"encrypt"),cm=s(async(e,t,r,n,i)=>{let o=await sm(i,e,n,t);return pi(e.slice(-6),o,r)},"decrypt")});function nn(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var um=I(()=>{j();s(nn,"subtleRsaEs")});var Dr,as=I(()=>{Dr=s((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}},"default")});var lm,dm,Pl=I(()=>{um();vl();Te();or();as();ct();ut();lm=s(async(e,t,r)=>{if(!ae(t))throw new TypeError(oe(t,...Q));if(qe(t,e,"encrypt","wrapKey"),Dr(e,t),t.usages.includes("encrypt"))return new Uint8Array(await D.subtle.encrypt(nn(e),t,r));if(t.usages.includes("wrapKey")){let n=await D.subtle.importKey("raw",r,...rn);return new Uint8Array(await D.subtle.wrapKey("raw",n,t,nn(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},"encrypt"),dm=s(async(e,t,r)=>{if(!ae(t))throw new TypeError(oe(t,...Q));if(qe(t,e,"decrypt","unwrapKey"),Dr(e,t),t.usages.includes("decrypt"))return new Uint8Array(await D.subtle.decrypt(nn(e),t,r));if(t.usages.includes("unwrapKey")){let n=await D.subtle.unwrapKey("raw",r,t,nn(e),...rn);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 hi(e){switch(e){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 M(`Unsupported JWE Algorithm: ${e}`)}}var wt,fi=I(()=>{j();li();s(hi,"bitLength");wt=s(e=>nr(new Uint8Array(hi(e)>>3)),"default")});var Al,pm=I(()=>{Al=s((e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
|
|
57
57
|
`);return`-----BEGIN ${t}-----
|
|
58
58
|
${r}
|
|
59
|
-
-----END ${t}-----`},"default")});function fm(e){let t=[],r=0;for(;r<e.length;){let n=Em(e.subarray(r));t.push(n),r+=n.byteLength}return t}function Em(e){let t=0,r=e[0]&31;if(t++,r===31){for(r=0;e[t]>=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let o=t+n+2;return{byteLength:o,contents:e.subarray(t,t+n),raw:e.subarray(0,o)}}else{let o=e[t]&127;t++,n=0;for(let a=0;a<o;a++)n=n*256+e[t],t++}let i=t+n;return{byteLength:i,contents:e.subarray(t,i),raw:e.subarray(0,i)}}function zS(e){let t=fm(fm(Em(e).contents)[0].contents);return Zo(t[t[0].raw[0]===160?6:5].raw)}function WS(e){let t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=hl(t);return Al(zS(r),"PUBLIC KEY")}var mm,ym,gm,sr,hm,bm,_m,Rl,wm,cs=I(()=>{Te();ct();Ie();pm();j();ut();mm=s(async(e,t,r)=>{if(!ae(r))throw new TypeError(oe(r,...Q));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return Al(Zo(new Uint8Array(await D.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},"genericExport"),ym=s(e=>mm("public","spki",e),"toSPKI"),gm=s(e=>mm("private","pkcs8",e),"toPKCS8"),sr=s((e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((o,a)=>o===t[a])||sr(e,t,n+1)},"findOid"),hm=s(e=>{switch(!0){case sr(e,[42,134,72,206,61,3,1,7]):return"P-256";case sr(e,[43,129,4,0,34]):return"P-384";case sr(e,[43,129,4,0,35]):return"P-521";case sr(e,[43,101,110]):return"X25519";case sr(e,[43,101,111]):return"X448";case sr(e,[43,101,112]):return"Ed25519";case sr(e,[43,101,113]):return"Ed448";default:throw new M("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),bm=s(async(e,t,r,n,i)=>{var o;let a,c,u=new Uint8Array(atob(r.replace(e,"")).split("").map(d=>d.charCodeAt(0))),l=t==="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=hm(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:hm(u)},c=l?["verify"]:["sign"];break;default:throw new M('Invalid or unsupported "alg" (Algorithm) value')}return D.subtle.importKey(t,u,a,(o=i?.extractable)!==null&&o!==void 0?o:!1,c)},"genericImport"),_m=s((e,t,r)=>bm(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),"fromPKCS8"),Rl=s((e,t,r)=>bm(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r),"fromSPKI");s(fm,"getElement");s(Em,"parseElement");s(zS,"spkiFromX509");s(WS,"getSPKI");wm=s((e,t,r)=>{let n;try{n=WS(e)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return Rl(n,t,r)},"fromX509")});function QS(e){let t,r;switch(e.kty){case"oct":{switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new M(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new M('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var YS,Ol,vm=I(()=>{Te();j();Ie();s(QS,"subtleMapping");YS=s(async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=QS(e),o=[n,(t=e.ext)!==null&&t!==void 0?t:!1,(r=e.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return D.subtle.importKey("raw",re(e.k),...o);let a={...e};return delete a.alg,delete a.use,D.subtle.importKey("jwk",a,...o)},"parse"),Ol=YS});async function Tm(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Rl(e,t,r)}async function Sm(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return wm(e,t,r)}async function Im(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return _m(e,t,r)}async function ar(e,t,r){var n;if(!Y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=e.ext!==!0),r?Ol({...e,alg:t,ext:(n=e.ext)!==null&&n!==void 0?n:!1}):re(e.k);case"RSA":if(e.oth!==void 0)throw new M('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ol({...e,alg:t});default:throw new M('Unsupported "kty" (Key Type) Parameter value')}}var mi=I(()=>{Ie();cs();vm();j();$e();s(Tm,"importSPKI");s(Sm,"importX509");s(Im,"importPKCS8");s(ar,"importJWK")});var ZS,XS,eI,cr,yi=I(()=>{ct();ut();ZS=s((e,t)=>{if(!(t instanceof Uint8Array)){if(!_l(t))throw new TypeError(bl(e,t,...Q,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${Q.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),XS=s((e,t,r)=>{if(!_l(t))throw new TypeError(bl(e,t,...Q));if(t.type==="secret")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),eI=s((e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ZS(e,t):XS(e,t,r)},"checkKeyType"),cr=eI});async function tI(e,t,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(oe(r,"Uint8Array"));let o=parseInt(e.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,t)),l=Se(i,n,u,Wo(i.length<<3)),d=new Uint8Array((await D.subtle.sign("HMAC",c,l)).slice(0,o>>3));return{ciphertext:u,tag:d}}async function rI(e,t,r,n,i){let o;r instanceof Uint8Array?o=await D.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(qe(r,e,"encrypt"),o=r);let a=new Uint8Array(await D.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},o,t)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var nI,gi,Nl=I(()=>{ge();yl();gl();Te();or();ct();j();ut();s(tI,"cbcEncrypt");s(rI,"gcmEncrypt");nI=s(async(e,t,r,n,i)=>{if(!ae(r)&&!(r instanceof Uint8Array))throw new TypeError(oe(r,...Q,"Uint8Array"));switch(ts(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&en(r,parseInt(e.slice(-3),10)),tI(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&en(r,parseInt(e.slice(1,4),10)),rI(e,t,r,n,i);default:throw new M("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),gi=nI});async function Pm(e,t,r,n){let i=e.slice(0,7);n||(n=Xo(i));let{ciphertext:o,tag:a}=await gi(i,r,t,n,new Uint8Array(0));return{encryptedKey:o,iv:X(n),tag:X(a)}}async function Am(e,t,r,n,i){let o=e.slice(0,7);return ns(o,t,r,n,i,new Uint8Array(0))}var xl=I(()=>{Nl();El();es();Ie();s(Pm,"wrap");s(Am,"unwrap")});async function iI(e,t,r,n,i){switch(cr(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new A("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new A("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Y(n.epk))throw new A('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!ss(t))throw new M("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await ar(n.epk,e),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new A('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=re(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new A('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=re(n.apv)}let u=await os(o,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?hi(n.enc):parseInt(e.slice(-5,-2),10),a,c);if(e==="ECDH-ES")return u;if(r===void 0)throw new A("JWE Encrypted Key missing");return pi(e.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 A("JWE Encrypted Key missing");return dm(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new A("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new A('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new A('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new A('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return cm(e,t,r,n.p2c,re(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new A("JWE Encrypted Key missing");return pi(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new A("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new A('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new A('JOSE Header "tag" (Authentication Tag) missing or invalid');let o=re(n.iv),a=re(n.tag);return Am(e,t,r,o,a)}default:throw new M('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Rm,Om=I(()=>{is();Tl();Il();Pl();Ie();j();fi();mi();yi();$e();xl();s(iI,"decryptKeyManagement");Rm=iI});function oI(e,t,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new e('"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 e('"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),...t.entries()]):o=t;for(let a of n.crit){if(!o.has(a))throw new M(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(o.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var vt,on=I(()=>{j();s(oI,"validateCrit");vt=oI});var sI,bi,Cl=I(()=>{sI=s((e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},"validateAlgorithms"),bi=sI});async function sn(e,t,r){var n;if(!Y(e))throw new A("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new A("JOSE Header missing");if(typeof e.iv!="string")throw new A("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new A("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new A("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new A("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new A("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new A("JWE AAD incorrect type");if(e.header!==void 0&&!Y(e.header))throw new A("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!Y(e.unprotected))throw new A("JWE Per-Recipient Unprotected Header incorrect type");let i;if(e.protected)try{let K=re(e.protected);i=JSON.parse(ue.decode(K))}catch{throw new A("JWE Protected Header is invalid")}if(!Et(i,e.header,e.unprotected))throw new A("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...i,...e.header,...e.unprotected};if(vt(A,new Map,r?.crit,i,o),o.zip!==void 0){if(!i||!i.zip)throw new A('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(o.zip!=="DEF")throw new M('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=o;if(typeof a!="string"||!a)throw new A("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new A("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&bi("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&bi("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new tr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;e.encrypted_key!==void 0&&(d=re(e.encrypted_key));let p=!1;typeof t=="function"&&(t=await t(i,e),p=!0);let f;try{f=await Rm(a,t,d,o,r)}catch(K){if(K instanceof TypeError||K instanceof A||K instanceof M)throw K;f=wt(c)}let h=re(e.iv),g=re(e.tag),_=Z.encode((n=e.protected)!==null&&n!==void 0?n:""),T;e.aad!==void 0?T=Se(_,Z.encode("."),Z.encode(e.aad)):T=_;let S=await ns(c,f,re(e.ciphertext),h,g,T);o.zip==="DEF"&&(S=await(r?.inflateRaw||Xf)(S));let H={plaintext:S};return e.protected!==void 0&&(H.protectedHeader=i),e.aad!==void 0&&(H.additionalAuthenticatedData=re(e.aad)),e.unprotected!==void 0&&(H.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(H.unprotectedHeader=e.header),p?{...H,key:t}:H}var us=I(()=>{Ie();El();wl();j();tn();$e();Om();ge();fi();on();Cl();s(sn,"flattenedDecrypt")});async function ls(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new A("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:o,3:a,4:c,length:u}=e.split(".");if(u!==5)throw new A("Invalid Compact JWE");let l=await sn({ciphertext:a,iv:o||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},t,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof t=="function"?{...d,key:l.key}:d}var Ll=I(()=>{us();j();ge();s(ls,"compactDecrypt")});async function Nm(e,t,r){if(!Y(e))throw new A("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(Y))throw new A("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new A("JWE Recipients has no members");for(let n of e.recipients)try{return await sn({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new Mt}var xm=I(()=>{us();j();$e();s(Nm,"generalDecrypt")});var aI,Cm,Lm=I(()=>{Te();ct();Ie();ut();aI=s(async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:X(e)};if(!ae(e))throw new TypeError(oe(e,...Q,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:i,...o}=await D.subtle.exportKey("jwk",e);return o},"keyToJWK"),Cm=aI});async function Dm(e){return ym(e)}async function Um(e){return gm(e)}async function ds(e){return Cm(e)}var Dl=I(()=>{cs();cs();Lm();s(Dm,"exportSPKI");s(Um,"exportPKCS8");s(ds,"exportJWK")});async function cI(e,t,r,n,i={}){let o,a,c;switch(cr(e,r,"encrypt"),e){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!ss(r))throw new M("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 nm(r)).privateKey);let{x:p,y:f,crv:h,kty:g}=await ds(d),_=await os(r,d,e==="ECDH-ES"?t:e,e==="ECDH-ES"?hi(t):parseInt(e.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:g}},g==="EC"&&(a.epk.y=f),u&&(a.apu=X(u)),l&&(a.apv=X(l)),e==="ECDH-ES"){c=_;break}c=n||wt(t);let T=e.slice(-6);o=await di(T,_,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||wt(t),o=await lm(e,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||wt(t);let{p2c:u,p2s:l}=i;({encryptedKey:o,...a}=await am(e,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||wt(t),o=await di(e,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||wt(t);let{iv:u}=i;({encryptedKey:o,...a}=await Pm(e,r,c,u));break}default:throw new M('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:o,parameters:a}}var ps,Ul=I(()=>{is();Tl();Il();Pl();Ie();fi();j();Dl();yi();xl();s(cI,"encryptKeyManagement");ps=cI});var Ml,kt,hs=I(()=>{Ie();Nl();wl();es();Ul();j();tn();ge();on();Ml=Symbol(),kt=class{static{s(this,"FlattenedEncrypt")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new A("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Et(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new A("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(vt(A,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new A('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new M('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:o}=n;if(typeof i!="string"||!i)throw new A('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new A('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 ps(i,o,t,this._cek,this._keyManagementParameters)),g&&(r&&Ml 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=Xo(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=Se(l,Z.encode("."),Z.encode(d))):u=l;let p,f;if(n.zip==="DEF"){let g=await(r?.deflateRaw||em)(this._plaintext);({ciphertext:p,tag:f}=await gi(o,g,c,this._iv,u))}else({ciphertext:p,tag:f}=await gi(o,this._plaintext,c,this._iv,u));let h={ciphertext:X(p),iv:X(this._iv),tag:X(f)};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 kl,fs,Mm=I(()=>{hs();j();fi();tn();Ul();Ie();on();kl=class{static{s(this,"IndividualRecipient")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},fs=class{static{s(this,"GeneralEncrypt")}constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new kl(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,i;if(!this._recipients.length)throw new A("at least one recipient must be added");if(t={deflateRaw:t?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new kt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...t}),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(!Et(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new A("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 A('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new A('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new A('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!o)o=d.enc;else if(o!==d.enc)throw new A('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(vt(A,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new A('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=wt(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 f={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let _=await new kt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:f}).encrypt(l.key,{...l.options,...t,[Ml]:!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 ps(((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:f});d.encrypted_key=X(h),(l.unprotectedHeader||g)&&(d.header={...l.unprotectedHeader,...g})}return c}}});function _i(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.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:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Hl=I(()=>{j();s(_i,"subtleDsa")});function Ei(e,t,r){if(ae(t))return Yf(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(oe(t,...Q));return D.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(oe(t,...Q,"Uint8Array"))}var Fl=I(()=>{Te();or();ct();ut();s(Ei,"getCryptoKey")});var uI,km,Hm=I(()=>{Hl();Te();as();Fl();uI=s(async(e,t,r,n)=>{let i=await Ei(e,t,"verify");Dr(e,i);let o=_i(e,i.algorithm);try{return await D.subtle.verify(o,i,r,n)}catch{return!1}},"verify"),km=uI});async function an(e,t,r){var n;if(!Y(e))throw new z("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new z("JWS Protected Header incorrect type");if(e.payload===void 0)throw new z("JWS Payload missing");if(typeof e.signature!="string")throw new z("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Y(e.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{let T=re(e.protected);i=JSON.parse(ue.decode(T))}catch{throw new z("JWS Protected Header is invalid")}if(!Et(i,e.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...i,...e.header},a=vt(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&&bi("algorithms",r.algorithms);if(l&&!l.has(u))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof e.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(i,e),d=!0),cr(u,t,"verify");let p=Se(Z.encode((n=e.protected)!==null&&n!==void 0?n:""),Z.encode("."),typeof e.payload=="string"?Z.encode(e.payload):e.payload),f=re(e.signature);if(!await km(u,t,f,p))throw new Lr;let g;c?g=re(e.payload):typeof e.payload=="string"?g=Z.encode(e.payload):g=e.payload;let _={payload:g};return e.protected!==void 0&&(_.protectedHeader=i),e.header!==void 0&&(_.unprotectedHeader=e.header),d?{..._,key:t}:_}var ms=I(()=>{Ie();Hm();j();ge();tn();$e();yi();on();Cl();s(an,"flattenedVerify")});async function ys(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:o,length:a}=e.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await an({payload:i,protected:n,signature:o},t,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...u,key:c.key}:u}var ql=I(()=>{ms();j();ge();s(ys,"compactVerify")});async function Fm(e,t,r){if(!Y(e))throw new z("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(Y))throw new z("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await an({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Lr}var qm=I(()=>{ms();j();$e();s(Fm,"generalVerify")});var cn,$l=I(()=>{cn=s(e=>Math.floor(e.getTime()/1e3),"default")});var lI,un,jl=I(()=>{lI=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,un=s(e=>{let t=lI.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[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 $m,dI,ln,gs=I(()=>{j();ge();$l();jl();$e();$m=s(e=>e.toLowerCase().replace(/^application\//,""),"normalizeTyp"),dI=s((e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,"checkAudiencePresence"),ln=s((e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||$m(e.typ)!==$m(n)))throw new be('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ue.decode(t))}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&&!dI(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=un(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,f=cn(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>f+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<=f-d)throw new Xr('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=f-i.iat,g=typeof l=="number"?l:un(l);if(h-d>g)throw new Xr('"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 jm(e,t,r){var n;let i=await ys(e,t,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:ln(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof t=="function"?{...a,key:i.key}:a}var Vm=I(()=>{ql();gs();j();s(jm,"jwtVerify")});async function Gm(e,t,r){let n=await ls(e,t,r),i=ln(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 t=="function"?{...a,key:n.key}:a}var Bm=I(()=>{Ll();gs();j();s(Gm,"jwtDecrypt")});var dn,Vl=I(()=>{hs();dn=class{static{s(this,"CompactEncrypt")}constructor(t){this._flattened=new kt(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var pI,Km,Jm=I(()=>{Hl();Te();as();Fl();pI=s(async(e,t,r)=>{let n=await Ei(e,t,"sign");Dr(e,n);let i=await D.subtle.sign(_i(e,n.algorithm),n,r);return new Uint8Array(i)},"sign"),Km=pI});var ur,bs=I(()=>{Ie();Jm();tn();j();ge();yi();on();ur=class{static{s(this,"FlattenedSign")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Et(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=vt(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');cr(a,t,"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=Se(u,Z.encode("."),c),d=await Km(a,t,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 pn,Gl=I(()=>{bs();pn=class{static{s(this,"CompactSign")}constructor(t){this._flattened=new ur(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,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 Bl,_s,zm=I(()=>{bs();j();Bl=class{static{s(this,"IndividualSignature")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},_s=class{static{s(this,"GeneralSign")}constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new Bl(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new ur(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:o,...a}=await i.sign(n.key,n.options);if(r===0)t.payload=o;else if(t.payload!==o)throw new z("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(a)}return t}}});var lr,Es=I(()=>{$l();$e();jl();lr=class{static{s(this,"ProduceJWT")}constructor(t){if(!Y(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:cn(new Date)+un(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:cn(new Date)+un(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:cn(new Date)}:this._payload={...this._payload,iat:t},this}}});var ws,Wm=I(()=>{Gl();j();ge();Es();ws=class extends lr{static{s(this,"SignJWT")}setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var n;let i=new pn(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(t,r)}}});var vs,Qm=I(()=>{Vl();ge();Es();vs=class extends lr{static{s(this,"EncryptJWT")}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new dn(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(t,r)}}});async function Kl(e,t){if(!Y(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":dr(e.crv,'"crv" (Curve) Parameter'),dr(e.x,'"x" (X Coordinate) Parameter'),dr(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":dr(e.crv,'"crv" (Subtype of Key Pair) Parameter'),dr(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":dr(e.e,'"e" (Exponent) Parameter'),dr(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":dr(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new M('"kty" (Key Type) Parameter missing or unsupported')}let n=Z.encode(JSON.stringify(r));return X(await Jo(t,n))}async function Ym(e,t){t??(t="sha256");let r=await Kl(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}var dr,Zm=I(()=>{dl();Ie();j();ge();$e();dr=s((e,t)=>{if(typeof e!="string"||!e)throw new ai(`${t} missing or invalid`)},"check");s(Kl,"calculateJwkThumbprint");s(Ym,"calculateJwkThumbprintUri")});async function Xm(e,t){let r={...e,...t?.header};if(!Y(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await ar({...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 ey=I(()=>{mi();$e();j();s(Xm,"EmbeddedJWK")});function hI(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new M('Unsupported "alg" value for a JSON Web Key Set')}}function Jl(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(fI)}function fI(e){return Y(e)}function mI(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async function ty(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let i=await ar({...t,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new rr("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function ry(e){let t=new wi(e);return async function(r,n){return t.getKey(r,n)}}var wi,zl=I(()=>{mi();j();$e();s(hI,"getKtyFromAlg");s(Jl,"isJWKSLike");s(fI,"isJWKLike");s(mI,"clone");wi=class{static{s(this,"LocalJWKSet")}constructor(t){if(this._cached=new WeakMap,!Jl(t))throw new rr("JSON Web Key Set malformed");this._jwks=mI(t)}async getKey(t,r){let{alg:n,kid:i}={...t,...r?.header},o=hI(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 Cr;if(u!==1){let l=new ci,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await ty(d,p,n)}catch{continue}},l}return ty(this._cached,c,n)}};s(ty,"importWithAlgCache");s(ry,"createLocalJWKSet")});var yI,ny,iy=I(()=>{j();yI=s(async(e,t,r)=>{let n,i,o=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{o=!0,n.abort()},t));let a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw o?new ui: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"),ny=yI});function gI(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function oy(e,t){let r=new Wl(e,t);return async function(n,i){return r.getKey(n,i)}}var Wl,sy=I(()=>{iy();j();zl();s(gI,"isCloudflareWorkers");Wl=class extends wi{static{s(this,"RemoteJWKSet")}constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.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(t,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(t,r)}catch(n){if(n instanceof Cr&&this.coolingDown()===!1)return await this.reload(),super.getKey(t,r);throw n}}async reload(){this._pendingFetch&&gI()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=ny(this._url,this._timeoutDuration,this._options).then(t=>{if(!Jl(t))throw new rr("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}};s(oy,"createRemoteJWKSet")});var Ts,ay=I(()=>{Ie();ge();j();gs();Es();Ts=class extends lr{static{s(this,"UnsecuredJWT")}encode(){let t=X(JSON.stringify({alg:"none"})),r=X(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new le("Unsecured JWT must be a string");let{0:n,1:i,2:o,length:a}=t.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:ln(c,re(i),r),header:c}}}});var Ql={};ro(Ql,{decode:()=>vi,encode:()=>bI});var bI,vi,Ss=I(()=>{Ie();bI=X,vi=re});function cy(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(ue.decode(vi(t)));if(!Y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var uy=I(()=>{Ss();ge();$e();s(cy,"decodeProtectedHeader")});function ly(e){if(typeof e!="string")throw new le("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.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(!t)throw new le("JWTs must contain a payload");let n;try{n=vi(t)}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 dy=I(()=>{Ss();ge();$e();j();s(ly,"decodeJwt")});async function py(e,t){var r;let n,i,o;switch(e){case"HS256":case"HS384":case"HS512":n=parseInt(e.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(e.slice(-3),10),nr(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(e.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(e.slice(1,4),10),i={name:"AES-GCM",length:n},o=["encrypt","decrypt"];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(i,(r=t?.extractable)!==null&&r!==void 0?r:!1,o)}function Yl(e){var t;let r=(t=e?.modulusLength)!==null&&t!==void 0?t:2048;if(typeof r!="number"||r<2048)throw new M("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function hy(e,t){var r,n,i;let o,a;switch(e){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yl(t)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yl(t)},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(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yl(t)},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=t?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":o={name:c};break;default:throw new M("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=t?.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 M("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(o,(i=t?.extractable)!==null&&i!==void 0?i:!1,a)}var Zl=I(()=>{Te();j();li();s(py,"generateSecret");s(Yl,"getModulusLengthOption");s(hy,"generateKeyPair")});async function fy(e,t){return hy(e,t)}var my=I(()=>{Zl();s(fy,"generateKeyPair")});async function yy(e,t){return py(e,t)}var gy=I(()=>{Zl();s(yy,"generateSecret")});var Is={};ro(Is,{CompactEncrypt:()=>dn,CompactSign:()=>pn,EmbeddedJWK:()=>Xm,EncryptJWT:()=>vs,FlattenedEncrypt:()=>kt,FlattenedSign:()=>ur,GeneralEncrypt:()=>fs,GeneralSign:()=>_s,SignJWT:()=>ws,UnsecuredJWT:()=>Ts,base64url:()=>Ql,calculateJwkThumbprint:()=>Kl,calculateJwkThumbprintUri:()=>Ym,compactDecrypt:()=>ls,compactVerify:()=>ys,createLocalJWKSet:()=>ry,createRemoteJWKSet:()=>oy,decodeJwt:()=>ly,decodeProtectedHeader:()=>cy,errors:()=>fl,exportJWK:()=>ds,exportPKCS8:()=>Um,exportSPKI:()=>Dm,flattenedDecrypt:()=>sn,flattenedVerify:()=>an,generalDecrypt:()=>Nm,generalVerify:()=>Fm,generateKeyPair:()=>fy,generateSecret:()=>yy,importJWK:()=>ar,importPKCS8:()=>Im,importSPKI:()=>Tm,importX509:()=>Sm,jwtDecrypt:()=>Gm,jwtVerify:()=>jm});var Ps=I(()=>{Ll();us();xm();Mm();ql();ms();qm();Vm();Bm();Vl();hs();Gl();bs();zm();Wm();Qm();Zm();ey();zl();sy();ay();Dl();mi();uy();dy();j();my();gy();Ss()});var hn=y(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.fetchRetry=void 0;var _I=O();async function EI(e,t,r){for(let n=0;n<=e.retries;n++){let i=fetch(t,r);if(n===e.retries)return i;let o=await i;if(o.status<500&&o.status!==429)return o;e?.logger?.error("Request failed, retrying",{method:typeof t=="string"?"GET":t.method,url:typeof t=="string"?t:t.url,status:o.status}),await new Promise(a=>setTimeout(a,e.retryDelayMs*Math.pow(2,n)))}throw new _I.ConfigurationError("An unknown error occurred, ensure retries is not negative")}s(EI,"fetchRetry");As.fetchRetry=EI});var fn=y(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.GcpServiceAccount=Ze.fetchToken=Ze.exchangeGgpJwtForIdToken=Ze.exchangeFirebaseJwtForIdToken=Ze.getTokenFromGcpServiceAccount=void 0;var by=(Ps(),no(Is)),wI=O(),vI=hn();async function TI({serviceAccount:e,audience:t,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:o,privateKey:a}=e;return await new by.SignJWT(n).setProtectedHeader({alg:"RS256",kid:o}).setIssuer(i).setSubject(i).setAudience(t).setIssuedAt().setExpirationTime(r).sign(a)}s(TI,"getTokenFromGcpServiceAccount");Ze.getTokenFromGcpServiceAccount=TI;async function SI(e,t,r){return ed(e,{token:t,returnSecureToken:!0},r)}s(SI,"exchangeFirebaseJwtForIdToken");Ze.exchangeFirebaseJwtForIdToken=SI;async function II(e,t,r){return ed(e,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:t},r)}s(II,"exchangeGgpJwtForIdToken");Ze.exchangeGgpJwtForIdToken=II;async function ed(e,t,r){let n=await(0,vI.fetchRetry)(r,e,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(t)});if(n.status!==200){let o;try{let a=await n.text(),c=JSON.parse(a);o={cause:c.error??c}}catch{}throw new wI.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:o})}return await n.json()}s(ed,"fetchToken");Ze.fetchToken=ed;var Xl=class e{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:t,privateKey:r}){this.#t=t,this.#e=r}static async init(t){let r=JSON.parse(t),n=await(0,by.importPKCS8)(r.private_key.trim(),"RS256");return new e({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}};Ze.GcpServiceAccount=Xl});var Os=y(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleLogTransport=Ht.ZuploToGCPMap=Ht.GoogleCloudLoggingPlugin=void 0;var PI=O(),AI=ve(),td=W(),rd=fn(),RI=Ut(),_y=_t(),nd=class extends RI.LogPlugin{static{s(this,"GoogleCloudLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Rs(this.options)}};Ht.GoogleCloudLoggingPlugin=nd;var OI="https://logging.googleapis.com/v2/entries:write?alt=json";Ht.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var Rs=class{static{s(this,"GoogleLogTransport")}constructor(t){this.#r=t.logName,this.#e=t.serviceAccountJson,this.#i=td.Environment.instance.loggingEnvironmentType,this.#o=td.Environment.instance.loggingEnvironmentStage,this.#n=td.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async init(){this.#t=await rd.GcpServiceAccount.init(this.#e)}log(t,r){if(!this.#t)throw new PI.SystemError("Invalid state - Google log transport is not initialized");if(t.messages.length===0)return;let n={allMessages:(0,_y.makeErrorsSerializable)(t.messages)},i=this.#t.projectId??"zuplo-production",o={logName:this.#r,resource:{type:"global"},severity:Ht.ZuploToGCPMap[t.level],timestamp:t.timestamp,trace:`projects/${i}/traces/${t.requestId}`,labels:{requestId:t.requestId,buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};t.rayId&&(o.labels.rayId=t.rayId);let a=(0,_y.extractBestMessage)(n.allMessages);o.jsonPayload={...n,message:a},this.batcher.enqueue(o),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{if(t.length===0)return;this.#t||(this.#t=await rd.GcpServiceAccount.init(this.#e));let r=await(0,rd.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(OI,{method:"POST",body:JSON.stringify({entries:t}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new AI.BatchDispatch("google-log-transport",1,this.dispatchFunction)};Ht.GoogleLogTransport=Rs});var id=y(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.gcpLogFormat=mn.GCP_LOG_FORMAT=void 0;var Ey=_t(),NI=Os();mn.GCP_LOG_FORMAT="gcp";function xI(e){let t={allMessages:(0,Ey.makeErrorsSerializable)(e.messages)},r="zuplo-production",n=(0,Ey.extractBestMessage)(t.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:NI.ZuploToGCPMap[e.level],timestamp:e.timestamp,"logging.googleapis.com/labels":{buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${e.requestId}`,allMessages:t.allMessages};return e.rayId&&(i["logging.googleapis.com/labels"].rayId=e.rayId),i}s(xI,"gcpLogFormat");mn.gcpLogFormat=xI});var vy=y(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.ConsoleTransport=void 0;var wy=id(),od=class{static{s(this,"ConsoleTransport")}constructor(t,r){this.#e=t??console,this.#t=r}#e;#t;log(t){if(this.#t===wy.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,wy.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,level:t.level,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId}])}};Ns.ConsoleTransport=od});var dd=y(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.DataDogTransport=yn.DataDogLoggingPlugin=void 0;var CI=ve(),sd=W(),LI=Ut(),Ty=_t(),ld=class extends LI.LogPlugin{static{s(this,"DataDogLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new xs(this.options)}};yn.DataDogLoggingPlugin=ld;var ad="__ddtags",cd="__ddattr",ud=s(e=>e.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),DI=s(e=>{let t=Object.keys(e),r=[];return t.forEach(n=>{let i=e[n];i==null?r.push(ud(n)):r.push(`${ud(n)}:${ud(i.toString())}`)}),r.join(",")},"formatTags"),xs=class{static{s(this,"DataDogTransport")}constructor(t){this.#e=t.apiKey,this.#t=t.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=sd.Environment.instance.loggingEnvironmentType,this.#i=sd.Environment.instance.loggingEnvironmentStage,this.#r=sd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(t,r){let n={},i=r.custom[ad];i&&typeof i=="object"&&Object.assign(n,i);let o=[...t.messages],a=t.messages.findIndex(h=>h[ad]!==void 0);a>-1&&(Object.assign(n,o[a][ad]),o.splice(a,1));let c={},u=r.custom[cd];u&&typeof u=="object"&&Object.assign(c,u);let l=t.messages.findIndex(h=>h[cd]!==void 0);l>-1&&(Object.assign(c,o[l][cd]),o.splice(l,1));let d=(0,Ty.makeErrorsSerializable)(o),f={message:{...{...t,activityId:t.requestId,trace:t.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Ty.extractBestMessage)(d),service:t.loggingId,ddtags:DI(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(f,c),this.batcher.enqueue(f),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{t.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...t]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new CI.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};yn.DataDogTransport=xs});var Iy=y(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.ProcessTransport=void 0;var Sy=id(),pd=class{static{s(this,"ProcessTransport")}constructor(t,r){this.#e=t,this.#t=r}#e;#t;log(t){if(this.#t===Sy.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,Sy.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId,vectorClock:t.vectorClock}])}};Cs.ProcessTransport=pd});var Ay=y(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.RemoteLogTransport=void 0;var UI=ve(),Py=W(),MI=_t(),kI=s(({url:e,remoteLogToken:t,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(`${e}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(a=>({...a,messages:(0,MI.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":Py.Environment.instance.systemUserAgent,"zp-dn":Py.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Ls,hd=class{static{s(this,"RemoteLogTransport")}constructor(t){Ls||(Ls=new UI.BatchDispatch("remote-log-transport",1,kI(t)))}log(t,r){Ls.enqueue(t),r.waitUntil(Ls.waitUntilFlushed())}};Ds.RemoteLogTransport=hd});var Ry=y(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.unifiedFormatter=Ur.SeverityNumberOpenTelemetryMap=void 0;Ur.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var HI=s((e,t)=>r=>{let n={};return n.deploymentName=e,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:t.BUILD_ID,buildTimestamp:t.TIMESTAMP,gitSHA:t.GIT_SHA,version:t.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:Ur.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Ur.unifiedFormatter=HI});var Ny=y(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.UnifiedLogTransport=void 0;var FI=ve(),Oy=W(),qI=Ry(),$I=s(({url:e,remoteLogToken:t,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let o=(0,qI.unifiedFormatter)(r,n);try{await fetch(`${e}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(o)}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":Oy.Environment.instance.systemUserAgent,"zp-dn":Oy.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Us,fd=class{static{s(this,"UnifiedLogTransport")}constructor(t){Us||(Us=new FI.BatchDispatch("unified-log-transport",1,$I(t)))}async log(t,r){Us.enqueue(t),r.waitUntil(Us.waitUntilFlushed())}};Ms.UnifiedLogTransport=fd});var ky=y(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.LogInitializer=void 0;var jI=Sr(),VI=gt(),xy=el(),Cy=W(),Ly=Uf(),GI=Ut(),BI=Mf(),Dy=kf(),Uy=vy(),KI=dd(),JI=Os(),My=Iy(),zI=Ay(),WI=Ny(),md=(0,jI.debug)("zuplo:logging"),yd=class e{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:t,userCoreLogger:r}){this.systemCoreLogger=t,this.userCoreLogger=r}static async init(t){let r=await e.setupSystemCoreLogger(Cy.Environment.instance,t),n=await e.setupUserCoreLogger(Cy.Environment.instance,t);return new e({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(t,r){let{build:n}=t;md("Gateway.setupSystemCoreLogger");let i=[],o=r.getService(xy.SYSTEM_LOGGER);return o?i.push(new My.ProcessTransport(o.logger,t.logFormat)):t.isDeno&&i.push(new Uy.ConsoleTransport(console,t.logFormat)),t.isCloudflare&&t.deploymentName&&t.remoteLogToken&&i.push(new WI.UnifiedLogTransport({url:t.remoteLogURL,deploymentName:t.deploymentName,remoteLogToken:t.remoteLogToken,build:t.build})),await Promise.all(i.map(async a=>{a.init&&await a.init()})),new Ly.CoreLogger(t.systemLogLevel,"system",t.loggingId,n.BUILD_ID,i)}static async setupUserCoreLogger(t,r){md("Gateway.setupUserCoreLogger");let n=[],{runtime:i,build:o}=t,a=r.getService(xy.SYSTEM_LOGGER);if(a&&a.captureUserLogs===!0?n.push(new My.ProcessTransport(a.logger,t.logFormat)):t.isDeno&&n.push(new Uy.ConsoleTransport(console,t.logFormat)),t.remoteLogToken&&t.loggingId&&n.push(new zI.RemoteLogTransport({loggingId:t.loggingId,url:t.remoteLogURL,remoteLogToken:t.remoteLogToken,sendOnlyErrors:t.isCloudflare})),i.GCP_USER_LOG_NAME&&i.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new JI.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 KI.DataDogTransport({apiKey:i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return VI.plugins.forEach(c=>{c instanceof GI.LogPlugin&&n.push(c.getTransport())}),await Promise.all(n.map(async c=>{c.init&&await c.init()})),new Ly.CoreLogger(t.userLogLevel,"user",t.loggingId,o.BUILD_ID,n)}createRequestLoggers(t,r,n,i,o){md("Gateway.createRequestLoggers");let a=new BI.LoggingContext(n,i,o),c=new Dy.RequestLogger(t,r,this.systemCoreLogger,a);return{userRequestLogger:new Dy.RequestLogger(t,r,this.userCoreLogger,a),systemRequestLogger:c}}};ks.LogInitializer=yd});var bd=y(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.UserRouteConfiguration=void 0;var gd=class{static{s(this,"UserRouteConfiguration")}constructor(t){this.path=t.path,this.methods=t.methods,this.label=t.label,this.key=t.key,this.handler=t.handler,this.corsPolicy=t.corsPolicy,this.custom=t.custom,this.version=t.version,this.policies=t.policies,this.excludeFromOpenApi=t.excludeFromOpenApi,this.pathPattern=t.pathPattern,t.raw?(this.#e=t.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=t.operationId,this.summary=t.summary,this.tags=t.tags,this.parameters=t.parameters,this.responses=t.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};Hs.UserRouteConfiguration=gd});var Ed=y(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.Router=Tt.RouterError=Tt.LookupResult=Tt.RouterEntry=void 0;var Hy=O(),QI=ot(),YI=bd(),Fs=class{static{s(this,"RouterEntry")}constructor(t,r,n,i){this.fullPath=t,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};Tt.RouterEntry=Fs;var Ti=class{static{s(this,"LookupResult")}constructor(t,r,n){this.routeConfiguration=t,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};Tt.LookupResult=Ti;var qs=class extends Error{static{s(this,"RouterError")}constructor(t,r){super(t,r)}};Tt.RouterError=qs;var _d=class{static{s(this,"Router")}constructor(t){this.routeEntries=[],this.versions=t}versions;routeEntries;addRoute(t,r){if(!(t instanceof YI.UserRouteConfiguration||t instanceof QI.SystemRouteConfiguration))throw new Hy.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(o=>o.name===t.version)?.pathPrefix,i;"pathPattern"in t&&t.pathPattern?i=`${n??""}${t.pathPattern}`:i=`${n??""}${t.path}`;try{let o=new URLPattern({pathname:i}),a=new Fs(i,o,t,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(o){throw new qs(`addRoute-error: Invalid path '${i}'. '${o.message}'`,{cause:o})}}lookup(t,r){if(typeof t>"u")throw new Hy.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(t));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 Ti(o.config,o.executableHandler,c.pathname.groups)}}lookupByPathOnly(t){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:t});if(a!==null){let c=new Ti(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};Tt.Router=_d});var Ir=y(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.Gateway=void 0;var ZI=Sr(),Fy=lf(),qy=bf(),XI=_f(),$y=Ef(),jy=Sf(),Ft=ni(),$s=Pr(),Vy=Df(),It=O(),Si=gt(),eP=ky(),tP=Lt(),rP=te(),nP=Zu(),iP=Qt(),oP=Wr(),sP=ke(),aP=Ed(),wd=ot(),Gy=bd(),cP=He(),uP=Mo(),vd=W(),By=xr(),Ky=Cu(),St=(0,ZI.debug)("zuplo:runtime"),lP=s(e=>{let t=e.findIndex(r=>r.name===wd.systemNoVersion.name);return t>-1?[...e.splice(t),wd.systemNoVersion]:[...e,wd.systemNoVersion]},"setupSystemNoVersion"),Td=class e{static{s(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(t,r,n,i){this.routeData=t,this.runtimeSettings=r,this.schemaValidator=i,St("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=n}static async initialize(t,r,n,i,o){if(St("Gateway.initialize"),!e.#e){await(0,Si.initializeRuntime)(o);let a=await eP.LogInitializer.init(n),c=t(),u={...c,corsPolicies:(0,uP.parseCorsPolicies)(c.corsPolicies)},l=new e(u,r,a,i);e.#e=l}return e.#e}static purgeGatewayCache(){St("Gateway.purgeGatewayCache"),e.#e=void 0}static get instance(){if(!e.#e)throw new It.SystemError("Gateway cannot be used before it is initialized");return e.#e}instanceId=crypto.randomUUID();#t;#r;#n=[oP.policyProcessor,nP.corsProcessor,iP.metricsProcessor];#i;setupRoutes=()=>{St("Gateway.setupRoutes");let t=this.routeData,r=lP(t.versions),n=new aP.Router(r);if(t.routes.length===0)return(0,Fy.registerBuildRoute)(n,this),(0,jy.registerPingRoute)(n,this),(0,qy.registerCorsRoute)(n,this),(0,XI.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;i&&((0,Vy.registerDevPortalLegacyRedirectRoute)(n,this),(0,Vy.registerDevPortalV3Route)(n,this)),(0,Fy.registerBuildRoute)(n,this),(0,jy.registerPingRoute)(n,this),(0,qy.registerCorsRoute)(n,this);for(let o of Si.plugins)o instanceof Si.SystemRuntimePlugin&&o.registerRoutes(n,this);return t.routes.forEach(o=>{let a;if(typeof o.handler?.module=="object"&&(a=o.handler?.module[o.handler.export]),typeof a!="function")throw new It.ConfigurationError(`Invalid state - No handler on route for path '${o.path}'`);let c=new tP.Pipeline({processors:this.#n,handler:a,gateway:this}),u=new Gy.UserRouteConfiguration(o);n.addRoute(u,c.execute)}),(0,$y.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let t;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(t=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof t!="function")throw new It.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else t=s((r,n,i)=>this.#o(r,n,i),"errorHandler");return t};errorHandler(t,r,n){try{return this.#i(t,r,n)}catch(i){return St("An error occurred in the user's errorHandler",i),this.#o(t,r,i)}}#o(t,r,n){St("Gateway.internalErrorResponse");let i={};if(vd.Environment.instance.isDeno){if(n instanceof It.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let o=(0,By.serializeError)(n.cause);"stack"in o&&(o.stack=(0,By.cleanStack)(o.stack)),i={cause:o}}}return rP.HttpProblems.internalServerError(t,r,{detail:n.message,...i})}#s(t){let r=new Headers(t.headers);return Ft.DISPATCH_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),vd.Environment.instance.isDeno&&Ft.INTERNAL_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),new Request(t,{headers:r})}async handleRequest(t,r){let n=t.headers.get(Ft.REQUEST_ID_HEADER)??t.headers.get(Ft.LEGACY_REQUEST_ID_HEADER),i=t.headers.get(Ft.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let T=new Headers(t.headers);T.set(Ft.REQUEST_ID_HEADER,n),t=new Request(t,{headers:T})}if(["GET","HEAD"].includes(t.method)&&t.body){let T=new Headers(t.headers);T.set(Ft.BODY_REMOVED_HEADER,"true"),t=new Request(t,{headers:T,body:null})}let o={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,o,t),u=new URL(t.url),l=u.pathname,d=this.#r.lookup(t.method,l);if(!d)throw new It.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new $s.HeaderIncomingRequestProperties(t.headers),f=this.#s(t),h=new sP.ZuploRequest(f,{params:d.params}),g=new $s.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,fetchEvent:r,custom:o,incomingRequestProperties:p}),_=$s.ZuploContextExtensions.initialize(g,h);if(d.routeConfiguration===$y.notFoundRouteConfiguration&&Si.runtimeExtensions.value?.notFoundHandler!==void 0){let T=this.#r.lookupByPathOnly(l);_.pathOnlyMatches=T.map(S=>S.routeConfiguration).filter(S=>S instanceof Gy.UserRouteConfiguration)}try{if(cP.SystemLogMap.addLogger(g,c),vd.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!(0,Ky.isSystemRoute)(u):!u.pathname.startsWith("/__zuplo")){let H=await(0,Si.invokeOnRequestExtensions)(h,g);if(H instanceof Response)return H;{let K=$s.ZuploContextExtensions.getContextExtensions(g);h=H,K.latestRequest=h}}(0,Ky.isSystemRoute)(u)&&a.debug(`Request received '${u.pathname}'`,{method:t.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let T=d.executableHandler;dP(T,d,t),St("Gateway.handleRequest - call user handler");let S=await T(h,g);if(St("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new It.RuntimeError(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new It.RuntimeError("The response object has already been used. Return a new response instead.");if(S.headers.get(Ft.REQUEST_ID_HEADER)===null&&!S.webSocket){let H=new Headers(S.headers);return H.set(Ft.REQUEST_ID_HEADER,n),new Response(S.body,{status:S.status,statusText:S.statusText,headers:H,cf:S.cf})}else return S}catch(T){return St("Gateway - error executing handler",T),T instanceof It.RuntimeError?(a.error(T),c.warn(T)):c.error(T),await this.#o(h,g,T)}}};js.Gateway=Td;function dP(e,t,r){if(St("Gateway.checkHandler"),!e)throw typeof t.routeConfiguration>"u"?new It.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new It.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${t.routeConfiguration.path}'`)}s(dP,"checkHandler")});var Jy=y(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.invokeInboundPolicy=void 0;var pP=O(),hP=Ir(),fP=Wr(),mP=s(async(e,t,r)=>{let n=hP.Gateway.instance.routeData.policies,i=(0,fP.getInboundPolicyHandlerAndOptions)([e],n);if(i.length===0)throw new pP.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${e}' found.`);let o=i[0];return o.handler(t,r,o.options,e)},"invokeInboundPolicy");Vs.invokeInboundPolicy=mP});var Pr=y(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.SystemZuploContext=Xe.ZuploContextExtensions=Xe.ResponseSentEvent=Xe.ResponseSendingEvent=Xe.HeaderIncomingRequestProperties=void 0;var _e=ni(),yP=O(),gP=Jy(),Sd=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(t){this.#e=t}get asn(){try{let t=this.#e.get(_e.ZP_ASN_HEADER);if(typeof t=="string")return parseInt(t)}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}}};Xe.HeaderIncomingRequestProperties=Sd;var Id=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(t,r){super("responseSending"),this.request=t,this.mutableResponse=r}request;mutableResponse};Xe.ResponseSendingEvent=Id;var Pd=class extends Event{static{s(this,"ResponseSentEvent")}constructor(t,r){super("responseSent"),this.request=t,this.response=r}request;response};Xe.ResponseSentEvent=Pd;var Ii=class e{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(t,r){if(!e.#e.has(t)){let n=new e(r);return e.#e.set(t,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${t.requestId}'`)}static getContextExtensions(t){let r=e.#e.get(t);if(!r)throw new yP.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${t.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(t){this.latestRequest=t,this.#t=[],this.#r=[]}addResponseSendingHook(t){this.#r.push(t)}addResponseSendingFinalHook(t){this.#t.push(t)}onResponseSendingFinal=async(t,r,n)=>{for(let i of this.#t)await i(t,r,n)};onResponseSending=async(t,r,n)=>{let i=t;for(let o of this.#r)i=await o(t,r,n);return i}};Xe.ZuploContextExtensions=Ii;var Ad=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:t,route:r,requestId:n,fetchEvent:i,custom:o,incomingRequestProperties:a}){super(),this.log=Object.freeze(t),this.route=r,this.requestId=n,this.custom=o,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,gP.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Ii.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Ii.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(t,r,n){let i=s(o=>{try{typeof r=="function"?r(o):r.handleEvent(o)}catch(a){throw this.log.error(`Error invoking event ${t}. See following logs for details.`),a}},"wrapped");super.addEventListener(t,i,n)}};Xe.SystemZuploContext=Ad});var Bs=y(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.ContextData=void 0;var Rd=class e{static{s(this,"ContextData")}static#e;#t;constructor(t){this.#t=t}set(t,r){e.set(t,this.#t,r)}get(t){return e.get(t,this.#t)}static set(t,r,n){e.#e||(e.#e=new WeakMap);let i=e.#e.get(t);i||(i=new Map),i.set(r,n),e.#e.set(t,i)}static get(t,r){return e.#e||(e.#e=new WeakMap),e.#e.get(t)?.get(r)}};Gs.ContextData=Rd});var gn=y(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.environment=pr.isZuploReadableEnvVariableName=pr.isRestrictedEnvVariableName=void 0;var bP=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function zy(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!bP.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}s(zy,"isRestrictedEnvVariableName");pr.isRestrictedEnvVariableName=zy;function Wy(e){return!!e.startsWith("ZUPLO_")}s(Wy,"isZuploReadableEnvVariableName");pr.isZuploReadableEnvVariableName=Wy;var _P=new Proxy({},{get(e,t){if(zy(String(t))&&!Wy(String(t)))return;let r=globalThis,n;return r.process?n=r.process.env[t]:n=r[t],n}});pr.environment=_P});var Od=y(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.externalServiceHandler=bn.externalServiceTunnelConfig=void 0;var EP=Sr(),Mr=O(),wP=Nd(),Pi=W(),lt=(0,EP.debug)("zuplo:runtime:external-service");function Yy(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=Pi.Environment.instance.runtime;if(t&&t!=="undefined")try{let r=atob(t);e=JSON.parse(r)}catch{}return e}s(Yy,"getServiceAuth");async function vP(e){let t=Yy();if(!t)throw lt("There is no external service auth configured for this zup."),new Mr.RuntimeError("There are no external services configured for this zup.");if(typeof e!="string")throw lt("Cannot call external service with Request object"),new Mr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(e).hostname,i={};i["CF-Access-Client-Id"]=t.clientId,i["CF-Access-Client-Secret"]=t.clientSecret;let o;if(t.customServiceMapping&&t.customServiceMapping[n])o=`https://${t.customServiceMapping[n]}`;else if(Pi.Environment.instance.useSha256ServiceRouting){lt("Using sha256 service routing");let a=Pi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)o=`https://${await Zy(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw lt("Cannot use sha256 service routing, missing build variables"),new Mr.RuntimeError("Failed to generate fully qualified tunnel url.")}else o=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:o,tunnelHeaders:i}}s(vP,"externalServiceTunnelConfig");bn.externalServiceTunnelConfig=vP;async function TP(e,t){let r=Yy();if(r)if(lt(`Using external service auth. ClientId: ${r.clientId})`),typeof e=="string"){let n=new URL(e),i=n.hostname,o=t??{},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(Pi.Environment.instance.useSha256ServiceRouting){lt("Using sha256 service routing");let d=Pi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await Zy(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw lt("Cannot use sha256 service routing, missing build variables"),new Mr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);lt(`Calling external service: ${u.toString()}`);let l=await(0,wP.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 Mr.RuntimeError("Could not connect to secure tunnel.");return l}else throw lt("Cannot call external service with Request object"),new Mr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw lt("There is no external service auth configured for this zup."),new Mr.RuntimeError("There are no external services configured for this zup.")}s(TP,"externalServiceHandler");bn.externalServiceHandler=TP;async function Zy(e,t,r,n){let i=e.toLowerCase(),o=t.toLowerCase(),a=r.toLowerCase(),c=SP(n);lt(`Hashing service name: ${o}-${i}.${o}-${a}-${c}`);let u=await Qy(`${o}-${i}`),l=await Qy(`${o}-${a}-${c}`);return`${u}.${l}`}s(Zy,"hashServiceName");async function Qy(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Qy,"hashSegment");function SP(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}s(SP,"sanitizeEnvironmentType")});var Nd=y(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.originalFetch=void 0;var IP=Od(),Xy=new Map;Xy.set("service:",IP.externalServiceHandler);_n.originalFetch=globalThis.fetch;globalThis.fetch=function(e,t){let r=PP(t);if(typeof e=="string"){let n=new URL(e),i=Xy.get(n.protocol);return i?i(e,r):(0,_n.originalFetch)(e,r)}else return(0,_n.originalFetch)(e,r)};var PP=s(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let r=e;return r.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit")});var rg=y(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.Handler=En.purgeGatewayCache=void 0;var AP=O(),tg=Ir(),eg=W(),RP=s(()=>{tg.Gateway.purgeGatewayCache()},"purgeGatewayCache");En.purgeGatewayCache=RP;var xd=class{static{s(this,"Handler")}routeLoader;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(t,r,n,i,o,a,c){this.routeLoader=t,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=o,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(t,r)=>{eg.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await tg.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 AP.ConfigurationError&&(o=i.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:o,instance:t.url,trace:{timestamp:Date.now(),rayId:t.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:eg.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(t,r)}};En.Handler=xd});var sg=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 OP(e){for(var t=[],r=0;r<e.length;){var n=e[r];if(n==="*"||n==="+"||n==="?"){t.push({type:"MODIFIER",index:r,value:e[r++]});continue}if(n==="\\"){t.push({type:"ESCAPED_CHAR",index:r++,value:e[r++]});continue}if(n==="{"){t.push({type:"OPEN",index:r,value:e[r++]});continue}if(n==="}"){t.push({type:"CLOSE",index:r,value:e[r++]});continue}if(n===":"){for(var i="",o=r+1;o<e.length;){var a=e.charCodeAt(o);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=e[o++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));t.push({type:"NAME",index:r,value:i}),r=o;continue}if(n==="("){var c=1,u="",o=r+1;if(e[o]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(o));for(;o<e.length;){if(e[o]==="\\"){u+=e[o++]+e[o++];continue}if(e[o]===")"){if(c--,c===0){o++;break}}else if(e[o]==="("&&(c++,e[o+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(o));u+=e[o++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));t.push({type:"PATTERN",index:r,value:u}),r=o;continue}t.push({type:"CHAR",index:r,value:e[r++]})}return t.push({type:"END",index:r,value:""}),t}s(OP,"lexer");function Cd(e,t){t===void 0&&(t={});for(var r=OP(e),n=t.prefixes,i=n===void 0?"./":n,o="[^".concat(wn(t.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 Be=r[u],w=Be.type,k=Be.index;throw new TypeError("Unexpected ".concat(w," at ").concat(k,", expected ").concat(ie))},"mustConsume"),f=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 T=h||"";i.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:g||c++,prefix:T,suffix:"",pattern:_||o,modifier:d("MODIFIER")||""});continue}var S=h||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var H=d("OPEN");if(H){var T=f(),K=d("NAME")||"",L=d("PATTERN")||"",ne=f();p("CLOSE"),a.push({name:K||(L?c++:""),pattern:K&&!L?o:L,prefix:T,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Cd,"parse");Re.parse=Cd;function NP(e,t){return ng(Cd(e,t),t)}s(NP,"compile");Re.compile=NP;function ng(e,t){t===void 0&&(t={});var r=Ld(t),n=t.encode,i=n===void 0?function(u){return u}:n,o=t.validate,a=o===void 0?!0:o,c=e.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<e.length;d++){var p=e[d];if(typeof p=="string"){l+=p;continue}var f=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",g=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!g)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var _=0;_<f.length;_++){var T=i(f[_],p);if(a&&!c[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var T=i(String(f),p);if(a&&!c[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!h){var S=g?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}s(ng,"tokensToFunction");Re.tokensToFunction=ng;function xP(e,t){var r=[],n=Dd(e,r,t);return ig(n,r,t)}s(xP,"match");Re.match=xP;function ig(e,t,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(o){return o}:n;return function(o){var a=e.exec(o);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=s(function(f){if(a[f]===void 0)return"continue";var h=t[f-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[f].split(h.prefix+h.suffix).map(function(g){return i(g,h)}):l[h.name]=i(a[f],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}s(ig,"regexpToFunction");Re.regexpToFunction=ig;function wn(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(wn,"escapeString");function Ld(e){return e&&e.sensitive?"":"i"}s(Ld,"flags");function CP(e,t){if(!t)return e;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(e.source);i;)t.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(e.source);return e}s(CP,"regexpToRegexp");function LP(e,t,r){var n=e.map(function(i){return Dd(i,t,r).source});return new RegExp("(?:".concat(n.join("|"),")"),Ld(r))}s(LP,"arrayToRegexp");function DP(e,t,r){return og(Cd(e,r),t,r)}s(DP,"stringToRegexp");function og(e,t,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(k){return k}:l,p=r.delimiter,f=p===void 0?"/#?":p,h=r.endsWith,g=h===void 0?"":h,_="[".concat(wn(g),"]|$"),T="[".concat(wn(f),"]"),S=a?"^":"",H=0,K=e;H<K.length;H++){var L=K[H];if(typeof L=="string")S+=wn(d(L));else{var ne=wn(d(L.prefix)),ie=wn(d(L.suffix));if(L.pattern)if(t&&t.push(L),ne||ie)if(L.modifier==="+"||L.modifier==="*"){var me=L.modifier==="*"?"?":"";S+="(?:".concat(ne,"((?:").concat(L.pattern,")(?:").concat(ie).concat(ne,"(?:").concat(L.pattern,"))*)").concat(ie,")").concat(me)}else S+="(?:".concat(ne,"(").concat(L.pattern,")").concat(ie,")").concat(L.modifier);else L.modifier==="+"||L.modifier==="*"?S+="((?:".concat(L.pattern,")").concat(L.modifier,")"):S+="(".concat(L.pattern,")").concat(L.modifier);else S+="(?:".concat(ne).concat(ie,")").concat(L.modifier)}}if(u)i||(S+="".concat(T,"?")),S+=r.endsWith?"(?=".concat(_,")"):"$";else{var Be=e[e.length-1],w=typeof Be=="string"?T.indexOf(Be[Be.length-1])>-1:Be===void 0;i||(S+="(?:".concat(T,"(?=").concat(_,"))?")),w||(S+="(?=".concat(T,"|").concat(_,")"))}return new RegExp(S,Ld(r))}s(og,"tokensToRegexp");Re.tokensToRegexp=og;function Dd(e,t,r){return e instanceof RegExp?CP(e,t):Array.isArray(e)?LP(e,t,r):DP(e,t,r)}s(Dd,"pathToRegexp");Re.pathToRegexp=Dd});var Hd=y(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.AwsV4Signer=vn.AwsClient=void 0;var UP=Sr(),lg=O(),MP=(0,UP.debug)("zuplo:runtime"),Md=new TextEncoder,ag={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"},kP=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],kd=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:t,secretAccessKey:r,sessionToken:n,service:i,region:o,cache:a,retries:c,initRetryMs:u}){if(t==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=t,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(t,r){let n=new Ks(Object.assign({url:t},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(t,r){MP("AWS fetch",t);for(let n=0;n<=this.retries;n++){let{url:i,request:o}=await this.sign(t,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 lg.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};vn.AwsClient=kd;var Ks=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:t,url:r,headers:n,body:i,accessKeyId:o,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:f,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=t||(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 T,S;(!u||!l)&&([T,S]=HP(this.url,this.headers)),this.service=u||T||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let H=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"),H.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&H.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>g||!kP.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 ${t}-----`},"default")});function fm(e){let t=[],r=0;for(;r<e.length;){let n=Em(e.subarray(r));t.push(n),r+=n.byteLength}return t}function Em(e){let t=0,r=e[0]&31;if(t++,r===31){for(r=0;e[t]>=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let o=t+n+2;return{byteLength:o,contents:e.subarray(t,t+n),raw:e.subarray(0,o)}}else{let o=e[t]&127;t++,n=0;for(let a=0;a<o;a++)n=n*256+e[t],t++}let i=t+n;return{byteLength:i,contents:e.subarray(t,i),raw:e.subarray(0,i)}}function zS(e){let t=fm(fm(Em(e).contents)[0].contents);return Zo(t[t[0].raw[0]===160?6:5].raw)}function WS(e){let t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=hl(t);return Al(zS(r),"PUBLIC KEY")}var mm,ym,gm,sr,hm,bm,_m,Rl,wm,cs=I(()=>{Te();ct();Ie();pm();j();ut();mm=s(async(e,t,r)=>{if(!ae(r))throw new TypeError(oe(r,...Q));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return Al(Zo(new Uint8Array(await D.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},"genericExport"),ym=s(e=>mm("public","spki",e),"toSPKI"),gm=s(e=>mm("private","pkcs8",e),"toPKCS8"),sr=s((e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((o,a)=>o===t[a])||sr(e,t,n+1)},"findOid"),hm=s(e=>{switch(!0){case sr(e,[42,134,72,206,61,3,1,7]):return"P-256";case sr(e,[43,129,4,0,34]):return"P-384";case sr(e,[43,129,4,0,35]):return"P-521";case sr(e,[43,101,110]):return"X25519";case sr(e,[43,101,111]):return"X448";case sr(e,[43,101,112]):return"Ed25519";case sr(e,[43,101,113]):return"Ed448";default:throw new M("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),bm=s(async(e,t,r,n,i)=>{var o;let a,c,u=new Uint8Array(atob(r.replace(e,"")).split("").map(d=>d.charCodeAt(0))),l=t==="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=hm(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:hm(u)},c=l?["verify"]:["sign"];break;default:throw new M('Invalid or unsupported "alg" (Algorithm) value')}return D.subtle.importKey(t,u,a,(o=i?.extractable)!==null&&o!==void 0?o:!1,c)},"genericImport"),_m=s((e,t,r)=>bm(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),"fromPKCS8"),Rl=s((e,t,r)=>bm(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r),"fromSPKI");s(fm,"getElement");s(Em,"parseElement");s(zS,"spkiFromX509");s(WS,"getSPKI");wm=s((e,t,r)=>{let n;try{n=WS(e)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return Rl(n,t,r)},"fromX509")});function QS(e){let t,r;switch(e.kty){case"oct":{switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new M(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new M('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var YS,Ol,vm=I(()=>{Te();j();Ie();s(QS,"subtleMapping");YS=s(async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=QS(e),o=[n,(t=e.ext)!==null&&t!==void 0?t:!1,(r=e.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return D.subtle.importKey("raw",re(e.k),...o);let a={...e};return delete a.alg,delete a.use,D.subtle.importKey("jwk",a,...o)},"parse"),Ol=YS});async function Tm(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Rl(e,t,r)}async function Sm(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return wm(e,t,r)}async function Im(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return _m(e,t,r)}async function ar(e,t,r){var n;if(!Y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=e.ext!==!0),r?Ol({...e,alg:t,ext:(n=e.ext)!==null&&n!==void 0?n:!1}):re(e.k);case"RSA":if(e.oth!==void 0)throw new M('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ol({...e,alg:t});default:throw new M('Unsupported "kty" (Key Type) Parameter value')}}var mi=I(()=>{Ie();cs();vm();j();$e();s(Tm,"importSPKI");s(Sm,"importX509");s(Im,"importPKCS8");s(ar,"importJWK")});var ZS,XS,eI,cr,yi=I(()=>{ct();ut();ZS=s((e,t)=>{if(!(t instanceof Uint8Array)){if(!_l(t))throw new TypeError(bl(e,t,...Q,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${Q.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),XS=s((e,t,r)=>{if(!_l(t))throw new TypeError(bl(e,t,...Q));if(t.type==="secret")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${Q.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),eI=s((e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ZS(e,t):XS(e,t,r)},"checkKeyType"),cr=eI});async function tI(e,t,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(oe(r,"Uint8Array"));let o=parseInt(e.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,t)),l=Se(i,n,u,Wo(i.length<<3)),d=new Uint8Array((await D.subtle.sign("HMAC",c,l)).slice(0,o>>3));return{ciphertext:u,tag:d}}async function rI(e,t,r,n,i){let o;r instanceof Uint8Array?o=await D.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(qe(r,e,"encrypt"),o=r);let a=new Uint8Array(await D.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},o,t)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var nI,gi,Nl=I(()=>{ge();yl();gl();Te();or();ct();j();ut();s(tI,"cbcEncrypt");s(rI,"gcmEncrypt");nI=s(async(e,t,r,n,i)=>{if(!ae(r)&&!(r instanceof Uint8Array))throw new TypeError(oe(r,...Q,"Uint8Array"));switch(ts(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&en(r,parseInt(e.slice(-3),10)),tI(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&en(r,parseInt(e.slice(1,4),10)),rI(e,t,r,n,i);default:throw new M("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),gi=nI});async function Pm(e,t,r,n){let i=e.slice(0,7);n||(n=Xo(i));let{ciphertext:o,tag:a}=await gi(i,r,t,n,new Uint8Array(0));return{encryptedKey:o,iv:X(n),tag:X(a)}}async function Am(e,t,r,n,i){let o=e.slice(0,7);return ns(o,t,r,n,i,new Uint8Array(0))}var xl=I(()=>{Nl();El();es();Ie();s(Pm,"wrap");s(Am,"unwrap")});async function iI(e,t,r,n,i){switch(cr(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new A("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new A("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Y(n.epk))throw new A('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!ss(t))throw new M("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await ar(n.epk,e),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new A('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=re(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new A('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=re(n.apv)}let u=await os(o,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?hi(n.enc):parseInt(e.slice(-5,-2),10),a,c);if(e==="ECDH-ES")return u;if(r===void 0)throw new A("JWE Encrypted Key missing");return pi(e.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 A("JWE Encrypted Key missing");return dm(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new A("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new A('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new A('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new A('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return cm(e,t,r,n.p2c,re(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new A("JWE Encrypted Key missing");return pi(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new A("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new A('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new A('JOSE Header "tag" (Authentication Tag) missing or invalid');let o=re(n.iv),a=re(n.tag);return Am(e,t,r,o,a)}default:throw new M('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Rm,Om=I(()=>{is();Tl();Il();Pl();Ie();j();fi();mi();yi();$e();xl();s(iI,"decryptKeyManagement");Rm=iI});function oI(e,t,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new e('"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 e('"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),...t.entries()]):o=t;for(let a of n.crit){if(!o.has(a))throw new M(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(o.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var vt,on=I(()=>{j();s(oI,"validateCrit");vt=oI});var sI,bi,Cl=I(()=>{sI=s((e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},"validateAlgorithms"),bi=sI});async function sn(e,t,r){var n;if(!Y(e))throw new A("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new A("JOSE Header missing");if(typeof e.iv!="string")throw new A("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new A("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new A("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new A("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new A("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new A("JWE AAD incorrect type");if(e.header!==void 0&&!Y(e.header))throw new A("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!Y(e.unprotected))throw new A("JWE Per-Recipient Unprotected Header incorrect type");let i;if(e.protected)try{let K=re(e.protected);i=JSON.parse(ue.decode(K))}catch{throw new A("JWE Protected Header is invalid")}if(!Et(i,e.header,e.unprotected))throw new A("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...i,...e.header,...e.unprotected};if(vt(A,new Map,r?.crit,i,o),o.zip!==void 0){if(!i||!i.zip)throw new A('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(o.zip!=="DEF")throw new M('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=o;if(typeof a!="string"||!a)throw new A("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new A("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&bi("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&bi("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new tr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;e.encrypted_key!==void 0&&(d=re(e.encrypted_key));let p=!1;typeof t=="function"&&(t=await t(i,e),p=!0);let f;try{f=await Rm(a,t,d,o,r)}catch(K){if(K instanceof TypeError||K instanceof A||K instanceof M)throw K;f=wt(c)}let h=re(e.iv),g=re(e.tag),_=Z.encode((n=e.protected)!==null&&n!==void 0?n:""),T;e.aad!==void 0?T=Se(_,Z.encode("."),Z.encode(e.aad)):T=_;let S=await ns(c,f,re(e.ciphertext),h,g,T);o.zip==="DEF"&&(S=await(r?.inflateRaw||Xf)(S));let H={plaintext:S};return e.protected!==void 0&&(H.protectedHeader=i),e.aad!==void 0&&(H.additionalAuthenticatedData=re(e.aad)),e.unprotected!==void 0&&(H.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(H.unprotectedHeader=e.header),p?{...H,key:t}:H}var us=I(()=>{Ie();El();wl();j();tn();$e();Om();ge();fi();on();Cl();s(sn,"flattenedDecrypt")});async function ls(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new A("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:o,3:a,4:c,length:u}=e.split(".");if(u!==5)throw new A("Invalid Compact JWE");let l=await sn({ciphertext:a,iv:o||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},t,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof t=="function"?{...d,key:l.key}:d}var Ll=I(()=>{us();j();ge();s(ls,"compactDecrypt")});async function Nm(e,t,r){if(!Y(e))throw new A("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(Y))throw new A("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new A("JWE Recipients has no members");for(let n of e.recipients)try{return await sn({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new Mt}var xm=I(()=>{us();j();$e();s(Nm,"generalDecrypt")});var aI,Cm,Lm=I(()=>{Te();ct();Ie();ut();aI=s(async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:X(e)};if(!ae(e))throw new TypeError(oe(e,...Q,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:i,...o}=await D.subtle.exportKey("jwk",e);return o},"keyToJWK"),Cm=aI});async function Dm(e){return ym(e)}async function Um(e){return gm(e)}async function ds(e){return Cm(e)}var Dl=I(()=>{cs();cs();Lm();s(Dm,"exportSPKI");s(Um,"exportPKCS8");s(ds,"exportJWK")});async function cI(e,t,r,n,i={}){let o,a,c;switch(cr(e,r,"encrypt"),e){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!ss(r))throw new M("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 nm(r)).privateKey);let{x:p,y:f,crv:h,kty:g}=await ds(d),_=await os(r,d,e==="ECDH-ES"?t:e,e==="ECDH-ES"?hi(t):parseInt(e.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:g}},g==="EC"&&(a.epk.y=f),u&&(a.apu=X(u)),l&&(a.apv=X(l)),e==="ECDH-ES"){c=_;break}c=n||wt(t);let T=e.slice(-6);o=await di(T,_,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||wt(t),o=await lm(e,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||wt(t);let{p2c:u,p2s:l}=i;({encryptedKey:o,...a}=await am(e,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||wt(t),o=await di(e,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||wt(t);let{iv:u}=i;({encryptedKey:o,...a}=await Pm(e,r,c,u));break}default:throw new M('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:o,parameters:a}}var ps,Ul=I(()=>{is();Tl();Il();Pl();Ie();fi();j();Dl();yi();xl();s(cI,"encryptKeyManagement");ps=cI});var Ml,kt,hs=I(()=>{Ie();Nl();wl();es();Ul();j();tn();ge();on();Ml=Symbol(),kt=class{static{s(this,"FlattenedEncrypt")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new A("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Et(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new A("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(vt(A,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new A('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new M('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:o}=n;if(typeof i!="string"||!i)throw new A('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new A('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 ps(i,o,t,this._cek,this._keyManagementParameters)),g&&(r&&Ml 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=Xo(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=Se(l,Z.encode("."),Z.encode(d))):u=l;let p,f;if(n.zip==="DEF"){let g=await(r?.deflateRaw||em)(this._plaintext);({ciphertext:p,tag:f}=await gi(o,g,c,this._iv,u))}else({ciphertext:p,tag:f}=await gi(o,this._plaintext,c,this._iv,u));let h={ciphertext:X(p),iv:X(this._iv),tag:X(f)};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 kl,fs,Mm=I(()=>{hs();j();fi();tn();Ul();Ie();on();kl=class{static{s(this,"IndividualRecipient")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},fs=class{static{s(this,"GeneralEncrypt")}constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new kl(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,i;if(!this._recipients.length)throw new A("at least one recipient must be added");if(t={deflateRaw:t?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new kt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...t}),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(!Et(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new A("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 A('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new A('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new A('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!o)o=d.enc;else if(o!==d.enc)throw new A('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(vt(A,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new A('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=wt(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 f={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let _=await new kt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:f}).encrypt(l.key,{...l.options,...t,[Ml]:!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 ps(((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:f});d.encrypted_key=X(h),(l.unprotectedHeader||g)&&(d.header={...l.unprotectedHeader,...g})}return c}}});function _i(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.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:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new M(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Hl=I(()=>{j();s(_i,"subtleDsa")});function Ei(e,t,r){if(ae(t))return Yf(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(oe(t,...Q));return D.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(oe(t,...Q,"Uint8Array"))}var Fl=I(()=>{Te();or();ct();ut();s(Ei,"getCryptoKey")});var uI,km,Hm=I(()=>{Hl();Te();as();Fl();uI=s(async(e,t,r,n)=>{let i=await Ei(e,t,"verify");Dr(e,i);let o=_i(e,i.algorithm);try{return await D.subtle.verify(o,i,r,n)}catch{return!1}},"verify"),km=uI});async function an(e,t,r){var n;if(!Y(e))throw new z("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new z("JWS Protected Header incorrect type");if(e.payload===void 0)throw new z("JWS Payload missing");if(typeof e.signature!="string")throw new z("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Y(e.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{let T=re(e.protected);i=JSON.parse(ue.decode(T))}catch{throw new z("JWS Protected Header is invalid")}if(!Et(i,e.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...i,...e.header},a=vt(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&&bi("algorithms",r.algorithms);if(l&&!l.has(u))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof e.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(i,e),d=!0),cr(u,t,"verify");let p=Se(Z.encode((n=e.protected)!==null&&n!==void 0?n:""),Z.encode("."),typeof e.payload=="string"?Z.encode(e.payload):e.payload),f=re(e.signature);if(!await km(u,t,f,p))throw new Lr;let g;c?g=re(e.payload):typeof e.payload=="string"?g=Z.encode(e.payload):g=e.payload;let _={payload:g};return e.protected!==void 0&&(_.protectedHeader=i),e.header!==void 0&&(_.unprotectedHeader=e.header),d?{..._,key:t}:_}var ms=I(()=>{Ie();Hm();j();ge();tn();$e();yi();on();Cl();s(an,"flattenedVerify")});async function ys(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:o,length:a}=e.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await an({payload:i,protected:n,signature:o},t,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...u,key:c.key}:u}var ql=I(()=>{ms();j();ge();s(ys,"compactVerify")});async function Fm(e,t,r){if(!Y(e))throw new z("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(Y))throw new z("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await an({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Lr}var qm=I(()=>{ms();j();$e();s(Fm,"generalVerify")});var cn,$l=I(()=>{cn=s(e=>Math.floor(e.getTime()/1e3),"default")});var lI,un,jl=I(()=>{lI=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,un=s(e=>{let t=lI.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[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 $m,dI,ln,gs=I(()=>{j();ge();$l();jl();$e();$m=s(e=>e.toLowerCase().replace(/^application\//,""),"normalizeTyp"),dI=s((e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,"checkAudiencePresence"),ln=s((e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||$m(e.typ)!==$m(n)))throw new be('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ue.decode(t))}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&&!dI(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=un(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,f=cn(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>f+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<=f-d)throw new Xr('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=f-i.iat,g=typeof l=="number"?l:un(l);if(h-d>g)throw new Xr('"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 jm(e,t,r){var n;let i=await ys(e,t,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:ln(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof t=="function"?{...a,key:i.key}:a}var Vm=I(()=>{ql();gs();j();s(jm,"jwtVerify")});async function Gm(e,t,r){let n=await ls(e,t,r),i=ln(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 t=="function"?{...a,key:n.key}:a}var Bm=I(()=>{Ll();gs();j();s(Gm,"jwtDecrypt")});var dn,Vl=I(()=>{hs();dn=class{static{s(this,"CompactEncrypt")}constructor(t){this._flattened=new kt(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var pI,Km,Jm=I(()=>{Hl();Te();as();Fl();pI=s(async(e,t,r)=>{let n=await Ei(e,t,"sign");Dr(e,n);let i=await D.subtle.sign(_i(e,n.algorithm),n,r);return new Uint8Array(i)},"sign"),Km=pI});var ur,bs=I(()=>{Ie();Jm();tn();j();ge();yi();on();ur=class{static{s(this,"FlattenedSign")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Et(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=vt(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');cr(a,t,"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=Se(u,Z.encode("."),c),d=await Km(a,t,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 pn,Gl=I(()=>{bs();pn=class{static{s(this,"CompactSign")}constructor(t){this._flattened=new ur(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,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 Bl,_s,zm=I(()=>{bs();j();Bl=class{static{s(this,"IndividualSignature")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},_s=class{static{s(this,"GeneralSign")}constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new Bl(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new ur(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:o,...a}=await i.sign(n.key,n.options);if(r===0)t.payload=o;else if(t.payload!==o)throw new z("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(a)}return t}}});var lr,Es=I(()=>{$l();$e();jl();lr=class{static{s(this,"ProduceJWT")}constructor(t){if(!Y(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:cn(new Date)+un(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:cn(new Date)+un(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:cn(new Date)}:this._payload={...this._payload,iat:t},this}}});var ws,Wm=I(()=>{Gl();j();ge();Es();ws=class extends lr{static{s(this,"SignJWT")}setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var n;let i=new pn(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(t,r)}}});var vs,Qm=I(()=>{Vl();ge();Es();vs=class extends lr{static{s(this,"EncryptJWT")}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new dn(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(t,r)}}});async function Kl(e,t){if(!Y(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":dr(e.crv,'"crv" (Curve) Parameter'),dr(e.x,'"x" (X Coordinate) Parameter'),dr(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":dr(e.crv,'"crv" (Subtype of Key Pair) Parameter'),dr(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":dr(e.e,'"e" (Exponent) Parameter'),dr(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":dr(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new M('"kty" (Key Type) Parameter missing or unsupported')}let n=Z.encode(JSON.stringify(r));return X(await Jo(t,n))}async function Ym(e,t){t??(t="sha256");let r=await Kl(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}var dr,Zm=I(()=>{dl();Ie();j();ge();$e();dr=s((e,t)=>{if(typeof e!="string"||!e)throw new ai(`${t} missing or invalid`)},"check");s(Kl,"calculateJwkThumbprint");s(Ym,"calculateJwkThumbprintUri")});async function Xm(e,t){let r={...e,...t?.header};if(!Y(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await ar({...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 ey=I(()=>{mi();$e();j();s(Xm,"EmbeddedJWK")});function hI(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new M('Unsupported "alg" value for a JSON Web Key Set')}}function Jl(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(fI)}function fI(e){return Y(e)}function mI(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async function ty(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let i=await ar({...t,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new rr("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function ry(e){let t=new wi(e);return async function(r,n){return t.getKey(r,n)}}var wi,zl=I(()=>{mi();j();$e();s(hI,"getKtyFromAlg");s(Jl,"isJWKSLike");s(fI,"isJWKLike");s(mI,"clone");wi=class{static{s(this,"LocalJWKSet")}constructor(t){if(this._cached=new WeakMap,!Jl(t))throw new rr("JSON Web Key Set malformed");this._jwks=mI(t)}async getKey(t,r){let{alg:n,kid:i}={...t,...r?.header},o=hI(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 Cr;if(u!==1){let l=new ci,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await ty(d,p,n)}catch{continue}},l}return ty(this._cached,c,n)}};s(ty,"importWithAlgCache");s(ry,"createLocalJWKSet")});var yI,ny,iy=I(()=>{j();yI=s(async(e,t,r)=>{let n,i,o=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{o=!0,n.abort()},t));let a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw o?new ui: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"),ny=yI});function gI(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function oy(e,t){let r=new Wl(e,t);return async function(n,i){return r.getKey(n,i)}}var Wl,sy=I(()=>{iy();j();zl();s(gI,"isCloudflareWorkers");Wl=class extends wi{static{s(this,"RemoteJWKSet")}constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.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(t,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(t,r)}catch(n){if(n instanceof Cr&&this.coolingDown()===!1)return await this.reload(),super.getKey(t,r);throw n}}async reload(){this._pendingFetch&&gI()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=ny(this._url,this._timeoutDuration,this._options).then(t=>{if(!Jl(t))throw new rr("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}};s(oy,"createRemoteJWKSet")});var Ts,ay=I(()=>{Ie();ge();j();gs();Es();Ts=class extends lr{static{s(this,"UnsecuredJWT")}encode(){let t=X(JSON.stringify({alg:"none"})),r=X(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new le("Unsecured JWT must be a string");let{0:n,1:i,2:o,length:a}=t.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:ln(c,re(i),r),header:c}}}});var Ql={};ro(Ql,{decode:()=>vi,encode:()=>bI});var bI,vi,Ss=I(()=>{Ie();bI=X,vi=re});function cy(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(ue.decode(vi(t)));if(!Y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var uy=I(()=>{Ss();ge();$e();s(cy,"decodeProtectedHeader")});function ly(e){if(typeof e!="string")throw new le("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.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(!t)throw new le("JWTs must contain a payload");let n;try{n=vi(t)}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 dy=I(()=>{Ss();ge();$e();j();s(ly,"decodeJwt")});async function py(e,t){var r;let n,i,o;switch(e){case"HS256":case"HS384":case"HS512":n=parseInt(e.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(e.slice(-3),10),nr(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(e.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(e.slice(1,4),10),i={name:"AES-GCM",length:n},o=["encrypt","decrypt"];break;default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(i,(r=t?.extractable)!==null&&r!==void 0?r:!1,o)}function Yl(e){var t;let r=(t=e?.modulusLength)!==null&&t!==void 0?t:2048;if(typeof r!="number"||r<2048)throw new M("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function hy(e,t){var r,n,i;let o,a;switch(e){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yl(t)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yl(t)},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(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yl(t)},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=t?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":o={name:c};break;default:throw new M("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=t?.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 M("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new M('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return D.subtle.generateKey(o,(i=t?.extractable)!==null&&i!==void 0?i:!1,a)}var Zl=I(()=>{Te();j();li();s(py,"generateSecret");s(Yl,"getModulusLengthOption");s(hy,"generateKeyPair")});async function fy(e,t){return hy(e,t)}var my=I(()=>{Zl();s(fy,"generateKeyPair")});async function yy(e,t){return py(e,t)}var gy=I(()=>{Zl();s(yy,"generateSecret")});var Is={};ro(Is,{CompactEncrypt:()=>dn,CompactSign:()=>pn,EmbeddedJWK:()=>Xm,EncryptJWT:()=>vs,FlattenedEncrypt:()=>kt,FlattenedSign:()=>ur,GeneralEncrypt:()=>fs,GeneralSign:()=>_s,SignJWT:()=>ws,UnsecuredJWT:()=>Ts,base64url:()=>Ql,calculateJwkThumbprint:()=>Kl,calculateJwkThumbprintUri:()=>Ym,compactDecrypt:()=>ls,compactVerify:()=>ys,createLocalJWKSet:()=>ry,createRemoteJWKSet:()=>oy,decodeJwt:()=>ly,decodeProtectedHeader:()=>cy,errors:()=>fl,exportJWK:()=>ds,exportPKCS8:()=>Um,exportSPKI:()=>Dm,flattenedDecrypt:()=>sn,flattenedVerify:()=>an,generalDecrypt:()=>Nm,generalVerify:()=>Fm,generateKeyPair:()=>fy,generateSecret:()=>yy,importJWK:()=>ar,importPKCS8:()=>Im,importSPKI:()=>Tm,importX509:()=>Sm,jwtDecrypt:()=>Gm,jwtVerify:()=>jm});var Ps=I(()=>{Ll();us();xm();Mm();ql();ms();qm();Vm();Bm();Vl();hs();Gl();bs();zm();Wm();Qm();Zm();ey();zl();sy();ay();Dl();mi();uy();dy();j();my();gy();Ss()});var hn=y(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.fetchRetry=void 0;var _I=O();async function EI(e,t,r){for(let n=0;n<=e.retries;n++){let i=fetch(t,r);if(n===e.retries)return i;let o=await i;if(o.status<500&&o.status!==429)return o;e?.logger?.error("Request failed, retrying",{method:typeof t=="string"?"GET":t.method,url:typeof t=="string"?t:t.url,status:o.status}),await new Promise(a=>setTimeout(a,e.retryDelayMs*Math.pow(2,n)))}throw new _I.ConfigurationError("An unknown error occurred, ensure retries is not negative")}s(EI,"fetchRetry");As.fetchRetry=EI});var fn=y(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.GcpServiceAccount=Ze.fetchToken=Ze.exchangeGgpJwtForIdToken=Ze.exchangeFirebaseJwtForIdToken=Ze.getTokenFromGcpServiceAccount=void 0;var by=(Ps(),no(Is)),wI=O(),vI=hn();async function TI({serviceAccount:e,audience:t,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:o,privateKey:a}=e;return await new by.SignJWT(n).setProtectedHeader({alg:"RS256",kid:o}).setIssuer(i).setSubject(i).setAudience(t).setIssuedAt().setExpirationTime(r).sign(a)}s(TI,"getTokenFromGcpServiceAccount");Ze.getTokenFromGcpServiceAccount=TI;async function SI(e,t,r){return ed(e,{token:t,returnSecureToken:!0},r)}s(SI,"exchangeFirebaseJwtForIdToken");Ze.exchangeFirebaseJwtForIdToken=SI;async function II(e,t,r){return ed(e,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:t},r)}s(II,"exchangeGgpJwtForIdToken");Ze.exchangeGgpJwtForIdToken=II;async function ed(e,t,r){let n=await(0,vI.fetchRetry)(r,e,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(t)});if(n.status!==200){let o;try{let a=await n.text(),c=JSON.parse(a);o={cause:c.error??c}}catch{}throw new wI.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:o})}return await n.json()}s(ed,"fetchToken");Ze.fetchToken=ed;var Xl=class e{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:t,privateKey:r}){this.#t=t,this.#e=r}static async init(t){let r=JSON.parse(t),n=await(0,by.importPKCS8)(r.private_key.trim(),"RS256");return new e({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}};Ze.GcpServiceAccount=Xl});var Os=y(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleLogTransport=Ht.ZuploToGCPMap=Ht.GoogleCloudLoggingPlugin=void 0;var PI=O(),AI=ve(),td=W(),rd=fn(),RI=Ut(),_y=_t(),nd=class extends RI.LogPlugin{static{s(this,"GoogleCloudLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Rs(this.options)}};Ht.GoogleCloudLoggingPlugin=nd;var OI="https://logging.googleapis.com/v2/entries:write?alt=json";Ht.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var Rs=class{static{s(this,"GoogleLogTransport")}constructor(t){this.#r=t.logName,this.#e=t.serviceAccountJson,this.#i=td.Environment.instance.loggingEnvironmentType,this.#o=td.Environment.instance.loggingEnvironmentStage,this.#n=td.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async init(){this.#t=await rd.GcpServiceAccount.init(this.#e)}log(t,r){if(!this.#t)throw new PI.SystemError("Invalid state - Google log transport is not initialized");if(t.messages.length===0)return;let n={allMessages:(0,_y.makeErrorsSerializable)(t.messages)},i=this.#t.projectId??"zuplo-production",o={logName:this.#r,resource:{type:"global"},severity:Ht.ZuploToGCPMap[t.level],timestamp:t.timestamp,trace:`projects/${i}/traces/${t.requestId}`,labels:{requestId:t.requestId,buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};t.rayId&&(o.labels.rayId=t.rayId);let a=(0,_y.extractBestMessage)(n.allMessages);o.jsonPayload={...n,message:a},this.batcher.enqueue(o),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{if(t.length===0)return;this.#t||(this.#t=await rd.GcpServiceAccount.init(this.#e));let r=await(0,rd.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(OI,{method:"POST",body:JSON.stringify({entries:t}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new AI.BatchDispatch("google-log-transport",1,this.dispatchFunction)};Ht.GoogleLogTransport=Rs});var id=y(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.gcpLogFormat=mn.GCP_LOG_FORMAT=void 0;var Ey=_t(),NI=Os();mn.GCP_LOG_FORMAT="gcp";function xI(e){let t={allMessages:(0,Ey.makeErrorsSerializable)(e.messages)},r="zuplo-production",n=(0,Ey.extractBestMessage)(t.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:NI.ZuploToGCPMap[e.level],timestamp:e.timestamp,"logging.googleapis.com/labels":{buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${e.requestId}`,allMessages:t.allMessages};return e.rayId&&(i["logging.googleapis.com/labels"].rayId=e.rayId),i}s(xI,"gcpLogFormat");mn.gcpLogFormat=xI});var vy=y(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.ConsoleTransport=void 0;var wy=id(),od=class{static{s(this,"ConsoleTransport")}constructor(t,r){this.#e=t??console,this.#t=r}#e;#t;log(t){if(this.#t===wy.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,wy.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,level:t.level,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId}])}};Ns.ConsoleTransport=od});var dd=y(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.DataDogTransport=yn.DataDogLoggingPlugin=void 0;var CI=ve(),sd=W(),LI=Ut(),Ty=_t(),ld=class extends LI.LogPlugin{static{s(this,"DataDogLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new xs(this.options)}};yn.DataDogLoggingPlugin=ld;var ad="__ddtags",cd="__ddattr",ud=s(e=>e.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),DI=s(e=>{let t=Object.keys(e),r=[];return t.forEach(n=>{let i=e[n];i==null?r.push(ud(n)):r.push(`${ud(n)}:${ud(i.toString())}`)}),r.join(",")},"formatTags"),xs=class{static{s(this,"DataDogTransport")}constructor(t){this.#e=t.apiKey,this.#t=t.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=sd.Environment.instance.loggingEnvironmentType,this.#i=sd.Environment.instance.loggingEnvironmentStage,this.#r=sd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(t,r){let n={},i=r.custom[ad];i&&typeof i=="object"&&Object.assign(n,i);let o=[...t.messages],a=t.messages.findIndex(h=>h[ad]!==void 0);a>-1&&(Object.assign(n,o[a][ad]),o.splice(a,1));let c={},u=r.custom[cd];u&&typeof u=="object"&&Object.assign(c,u);let l=t.messages.findIndex(h=>h[cd]!==void 0);l>-1&&(Object.assign(c,o[l][cd]),o.splice(l,1));let d=(0,Ty.makeErrorsSerializable)(o),f={message:{...{...t,activityId:t.requestId,trace:t.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Ty.extractBestMessage)(d),service:t.loggingId,ddtags:DI(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(f,c),this.batcher.enqueue(f),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{t.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...t]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new CI.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};yn.DataDogTransport=xs});var Iy=y(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.ProcessTransport=void 0;var Sy=id(),pd=class{static{s(this,"ProcessTransport")}constructor(t,r){this.#e=t,this.#t=r}#e;#t;log(t){if(this.#t===Sy.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,Sy.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId,vectorClock:t.vectorClock}])}};Cs.ProcessTransport=pd});var Ay=y(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.RemoteLogTransport=void 0;var UI=ve(),Py=W(),MI=_t(),kI=s(({url:e,remoteLogToken:t,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(`${e}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(a=>({...a,messages:(0,MI.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":Py.Environment.instance.systemUserAgent,"zp-dn":Py.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Ls,hd=class{static{s(this,"RemoteLogTransport")}constructor(t){Ls||(Ls=new UI.BatchDispatch("remote-log-transport",1,kI(t)))}log(t,r){Ls.enqueue(t),r.waitUntil(Ls.waitUntilFlushed())}};Ds.RemoteLogTransport=hd});var Ry=y(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.unifiedFormatter=Ur.SeverityNumberOpenTelemetryMap=void 0;Ur.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var HI=s((e,t)=>r=>{let n={};return n.deploymentName=e,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:t.BUILD_ID,buildTimestamp:t.TIMESTAMP,gitSHA:t.GIT_SHA,version:t.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:Ur.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Ur.unifiedFormatter=HI});var Ny=y(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.UnifiedLogTransport=void 0;var FI=ve(),Oy=W(),qI=Ry(),$I=s(({url:e,remoteLogToken:t,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let o=(0,qI.unifiedFormatter)(r,n);try{await fetch(`${e}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(o)}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":Oy.Environment.instance.systemUserAgent,"zp-dn":Oy.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Us,fd=class{static{s(this,"UnifiedLogTransport")}constructor(t){Us||(Us=new FI.BatchDispatch("unified-log-transport",1,$I(t)))}async log(t,r){Us.enqueue(t),r.waitUntil(Us.waitUntilFlushed())}};Ms.UnifiedLogTransport=fd});var ky=y(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.LogInitializer=void 0;var jI=Sr(),VI=gt(),xy=el(),Cy=W(),Ly=Uf(),GI=Ut(),BI=Mf(),Dy=kf(),Uy=vy(),KI=dd(),JI=Os(),My=Iy(),zI=Ay(),WI=Ny(),md=(0,jI.debug)("zuplo:logging"),yd=class e{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:t,userCoreLogger:r}){this.systemCoreLogger=t,this.userCoreLogger=r}static async init(t){let r=await e.setupSystemCoreLogger(Cy.Environment.instance,t),n=await e.setupUserCoreLogger(Cy.Environment.instance,t);return new e({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(t,r){let{build:n}=t;md("Gateway.setupSystemCoreLogger");let i=[],o=r.getService(xy.SYSTEM_LOGGER);return o?i.push(new My.ProcessTransport(o.logger,t.logFormat)):t.isDeno&&i.push(new Uy.ConsoleTransport(console,t.logFormat)),t.isCloudflare&&t.deploymentName&&t.remoteLogToken&&i.push(new WI.UnifiedLogTransport({url:t.remoteLogURL,deploymentName:t.deploymentName,remoteLogToken:t.remoteLogToken,build:t.build})),await Promise.all(i.map(async a=>{a.init&&await a.init()})),new Ly.CoreLogger(t.systemLogLevel,"system",t.loggingId,n.BUILD_ID,i)}static async setupUserCoreLogger(t,r){md("Gateway.setupUserCoreLogger");let n=[],{runtime:i,build:o}=t,a=r.getService(xy.SYSTEM_LOGGER);if(a&&a.captureUserLogs===!0?n.push(new My.ProcessTransport(a.logger,t.logFormat)):t.isDeno&&n.push(new Uy.ConsoleTransport(console,t.logFormat)),t.remoteLogToken&&t.loggingId&&n.push(new zI.RemoteLogTransport({loggingId:t.loggingId,url:t.remoteLogURL,remoteLogToken:t.remoteLogToken,sendOnlyErrors:t.isCloudflare})),i.GCP_USER_LOG_NAME&&i.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new JI.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 KI.DataDogTransport({apiKey:i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return VI.plugins.forEach(c=>{c instanceof GI.LogPlugin&&n.push(c.getTransport())}),await Promise.all(n.map(async c=>{c.init&&await c.init()})),new Ly.CoreLogger(t.userLogLevel,"user",t.loggingId,o.BUILD_ID,n)}createRequestLoggers(t,r,n,i,o){md("Gateway.createRequestLoggers");let a=new BI.LoggingContext(n,i,o),c=new Dy.RequestLogger(t,r,this.systemCoreLogger,a);return{userRequestLogger:new Dy.RequestLogger(t,r,this.userCoreLogger,a),systemRequestLogger:c}}};ks.LogInitializer=yd});var bd=y(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.UserRouteConfiguration=void 0;var gd=class{static{s(this,"UserRouteConfiguration")}constructor(t){this.path=t.path,this.methods=t.methods,this.label=t.label,this.key=t.key,this.handler=t.handler,this.corsPolicy=t.corsPolicy,this.custom=t.custom,this.version=t.version,this.policies=t.policies,this.excludeFromOpenApi=t.excludeFromOpenApi,this.pathPattern=t.pathPattern,t.raw?(this.#e=t.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=t.operationId,this.summary=t.summary,this.tags=t.tags,this.parameters=t.parameters,this.responses=t.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};Hs.UserRouteConfiguration=gd});var Ed=y(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.Router=Tt.RouterError=Tt.LookupResult=Tt.RouterEntry=void 0;var Hy=O(),QI=ot(),YI=bd(),Fs=class{static{s(this,"RouterEntry")}constructor(t,r,n,i){this.fullPath=t,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};Tt.RouterEntry=Fs;var Ti=class{static{s(this,"LookupResult")}constructor(t,r,n){this.routeConfiguration=t,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};Tt.LookupResult=Ti;var qs=class extends Error{static{s(this,"RouterError")}constructor(t,r){super(t,r)}};Tt.RouterError=qs;var _d=class{static{s(this,"Router")}constructor(t){this.routeEntries=[],this.versions=t}versions;routeEntries;addRoute(t,r){if(!(t instanceof YI.UserRouteConfiguration||t instanceof QI.SystemRouteConfiguration))throw new Hy.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(o=>o.name===t.version)?.pathPrefix,i;"pathPattern"in t&&t.pathPattern?i=`${n??""}${t.pathPattern}`:i=`${n??""}${t.path}`;try{let o=new URLPattern({pathname:i}),a=new Fs(i,o,t,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(o){throw new qs(`addRoute-error: Invalid path '${i}'. '${o.message}'`,{cause:o})}}lookup(t,r){if(typeof t>"u")throw new Hy.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(t));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 Ti(o.config,o.executableHandler,c.pathname.groups)}}lookupByPathOnly(t){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:t});if(a!==null){let c=new Ti(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};Tt.Router=_d});var Ir=y(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.Gateway=void 0;var ZI=Sr(),Fy=lf(),qy=bf(),XI=_f(),$y=Ef(),jy=Sf(),Ft=ni(),$s=Pr(),Vy=Df(),It=O(),Si=gt(),eP=ky(),tP=Lt(),rP=te(),nP=Zu(),iP=Qt(),oP=Wr(),sP=ke(),aP=Ed(),wd=ot(),Gy=bd(),cP=He(),uP=Mo(),vd=W(),By=xr(),Ky=Cu(),St=(0,ZI.debug)("zuplo:runtime"),lP=s(e=>{let t=e.findIndex(r=>r.name===wd.systemNoVersion.name);return t>-1?[...e.splice(t),wd.systemNoVersion]:[...e,wd.systemNoVersion]},"setupSystemNoVersion"),Td=class e{static{s(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(t,r,n,i){this.routeData=t,this.runtimeSettings=r,this.schemaValidator=i,St("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=n}static async initialize(t,r,n,i,o){if(St("Gateway.initialize"),!e.#e){await(0,Si.initializeRuntime)(o);let a=await eP.LogInitializer.init(n),c=t(),u={...c,corsPolicies:(0,uP.parseCorsPolicies)(c.corsPolicies)},l=new e(u,r,a,i);e.#e=l}return e.#e}static purgeGatewayCache(){St("Gateway.purgeGatewayCache"),e.#e=void 0}static get instance(){if(!e.#e)throw new It.SystemError("Gateway cannot be used before it is initialized");return e.#e}instanceId=crypto.randomUUID();#t;#r;#n=[oP.policyProcessor,nP.corsProcessor,iP.metricsProcessor];#i;setupRoutes=()=>{St("Gateway.setupRoutes");let t=this.routeData,r=lP(t.versions),n=new aP.Router(r);if(t.routes.length===0)return(0,Fy.registerBuildRoute)(n,this),(0,jy.registerPingRoute)(n,this),(0,qy.registerCorsRoute)(n,this),(0,XI.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;i&&((0,Vy.registerDevPortalLegacyRedirectRoute)(n,this),(0,Vy.registerDevPortalV3Route)(n,this)),(0,Fy.registerBuildRoute)(n,this),(0,jy.registerPingRoute)(n,this),(0,qy.registerCorsRoute)(n,this);for(let o of Si.plugins)o instanceof Si.SystemRuntimePlugin&&o.registerRoutes(n,this);return t.routes.forEach(o=>{let a;if(typeof o.handler?.module=="object"&&(a=o.handler?.module[o.handler.export]),typeof a!="function")throw new It.ConfigurationError(`Invalid state - No handler on route for path '${o.path}'`);let c=new tP.Pipeline({processors:this.#n,handler:a,gateway:this}),u=new Gy.UserRouteConfiguration(o);n.addRoute(u,c.execute)}),(0,$y.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let t;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(t=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof t!="function")throw new It.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else t=s((r,n,i)=>this.#o(r,n,i),"errorHandler");return t};errorHandler(t,r,n){try{return this.#i(t,r,n)}catch(i){return St("An error occurred in the user's errorHandler",i),this.#o(t,r,i)}}#o(t,r,n){St("Gateway.internalErrorResponse");let i={};if(vd.Environment.instance.isDeno){if(n instanceof It.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let o=(0,By.serializeError)(n.cause);"stack"in o&&(o.stack=(0,By.cleanStack)(o.stack)),i={cause:o}}}return rP.HttpProblems.internalServerError(t,r,{detail:n.message,...i})}#s(t){let r=new Headers(t.headers);return Ft.DISPATCH_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),vd.Environment.instance.isDeno&&Ft.INTERNAL_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),new Request(t,{headers:r})}async handleRequest(t,r){let n=t.headers.get(Ft.REQUEST_ID_HEADER)??t.headers.get(Ft.LEGACY_REQUEST_ID_HEADER),i=t.headers.get(Ft.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let T=new Headers(t.headers);T.set(Ft.REQUEST_ID_HEADER,n),t=new Request(t,{headers:T})}if(["GET","HEAD"].includes(t.method)&&t.body){let T=new Headers(t.headers);T.set(Ft.BODY_REMOVED_HEADER,"true"),t=new Request(t,{headers:T,body:null})}let o={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,o,t),u=new URL(t.url),l=u.pathname,d=this.#r.lookup(t.method,l);if(!d)throw new It.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new $s.HeaderIncomingRequestProperties(t.headers),f=this.#s(t),h=new sP.ZuploRequest(f,{params:d.params}),g=new $s.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,fetchEvent:r,custom:o,incomingRequestProperties:p}),_=$s.ZuploContextExtensions.initialize(g,h);if(d.routeConfiguration===$y.notFoundRouteConfiguration&&Si.runtimeExtensions.value?.notFoundHandler!==void 0){let T=this.#r.lookupByPathOnly(l);_.pathOnlyMatches=T.map(S=>S.routeConfiguration).filter(S=>S instanceof Gy.UserRouteConfiguration)}try{if(cP.SystemLogMap.addLogger(g,c),vd.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!(0,Ky.isSystemRoute)(u):!u.pathname.startsWith("/__zuplo")){let H=await(0,Si.invokeOnRequestExtensions)(h,g);if(H instanceof Response)return H;{let K=$s.ZuploContextExtensions.getContextExtensions(g);h=H,K.latestRequest=h}}(0,Ky.isSystemRoute)(u)||a.debug(`Request received '${u.pathname}'`,{method:t.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let T=d.executableHandler;dP(T,d,t),St("Gateway.handleRequest - call user handler");let S=await T(h,g);if(St("Gateway.handleRequest - user handler"),!(S instanceof Response))throw new It.RuntimeError(`Invalid Response type from the request handler: ${typeof S}`);if(S.bodyUsed)throw new It.RuntimeError("The response object has already been used. Return a new response instead.");if(S.headers.get(Ft.REQUEST_ID_HEADER)===null&&!S.webSocket){let H=new Headers(S.headers);return H.set(Ft.REQUEST_ID_HEADER,n),new Response(S.body,{status:S.status,statusText:S.statusText,headers:H,cf:S.cf})}else return S}catch(T){return St("Gateway - error executing handler",T),T instanceof It.RuntimeError?(a.error(T),c.warn(T)):c.error(T),await this.#o(h,g,T)}}};js.Gateway=Td;function dP(e,t,r){if(St("Gateway.checkHandler"),!e)throw typeof t.routeConfiguration>"u"?new It.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new It.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${t.routeConfiguration.path}'`)}s(dP,"checkHandler")});var Jy=y(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.invokeInboundPolicy=void 0;var pP=O(),hP=Ir(),fP=Wr(),mP=s(async(e,t,r)=>{let n=hP.Gateway.instance.routeData.policies,i=(0,fP.getInboundPolicyHandlerAndOptions)([e],n);if(i.length===0)throw new pP.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${e}' found.`);let o=i[0];return o.handler(t,r,o.options,e)},"invokeInboundPolicy");Vs.invokeInboundPolicy=mP});var Pr=y(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.SystemZuploContext=Xe.ZuploContextExtensions=Xe.ResponseSentEvent=Xe.ResponseSendingEvent=Xe.HeaderIncomingRequestProperties=void 0;var _e=ni(),yP=O(),gP=Jy(),Sd=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(t){this.#e=t}get asn(){try{let t=this.#e.get(_e.ZP_ASN_HEADER);if(typeof t=="string")return parseInt(t)}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}}};Xe.HeaderIncomingRequestProperties=Sd;var Id=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(t,r){super("responseSending"),this.request=t,this.mutableResponse=r}request;mutableResponse};Xe.ResponseSendingEvent=Id;var Pd=class extends Event{static{s(this,"ResponseSentEvent")}constructor(t,r){super("responseSent"),this.request=t,this.response=r}request;response};Xe.ResponseSentEvent=Pd;var Ii=class e{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(t,r){if(!e.#e.has(t)){let n=new e(r);return e.#e.set(t,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${t.requestId}'`)}static getContextExtensions(t){let r=e.#e.get(t);if(!r)throw new yP.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${t.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(t){this.latestRequest=t,this.#t=[],this.#r=[]}addResponseSendingHook(t){this.#r.push(t)}addResponseSendingFinalHook(t){this.#t.push(t)}onResponseSendingFinal=async(t,r,n)=>{for(let i of this.#t)await i(t,r,n)};onResponseSending=async(t,r,n)=>{let i=t;for(let o of this.#r)i=await o(t,r,n);return i}};Xe.ZuploContextExtensions=Ii;var Ad=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:t,route:r,requestId:n,fetchEvent:i,custom:o,incomingRequestProperties:a}){super(),this.log=Object.freeze(t),this.route=r,this.requestId=n,this.custom=o,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,gP.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Ii.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Ii.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(t,r,n){let i=s(o=>{try{typeof r=="function"?r(o):r.handleEvent(o)}catch(a){throw this.log.error(`Error invoking event ${t}. See following logs for details.`),a}},"wrapped");super.addEventListener(t,i,n)}};Xe.SystemZuploContext=Ad});var Bs=y(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.ContextData=void 0;var Rd=class e{static{s(this,"ContextData")}static#e;#t;constructor(t){this.#t=t}set(t,r){e.set(t,this.#t,r)}get(t){return e.get(t,this.#t)}static set(t,r,n){e.#e||(e.#e=new WeakMap);let i=e.#e.get(t);i||(i=new Map),i.set(r,n),e.#e.set(t,i)}static get(t,r){return e.#e||(e.#e=new WeakMap),e.#e.get(t)?.get(r)}};Gs.ContextData=Rd});var gn=y(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.environment=pr.isZuploReadableEnvVariableName=pr.isRestrictedEnvVariableName=void 0;var bP=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function zy(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!bP.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}s(zy,"isRestrictedEnvVariableName");pr.isRestrictedEnvVariableName=zy;function Wy(e){return!!e.startsWith("ZUPLO_")}s(Wy,"isZuploReadableEnvVariableName");pr.isZuploReadableEnvVariableName=Wy;var _P=new Proxy({},{get(e,t){if(zy(String(t))&&!Wy(String(t)))return;let r=globalThis,n;return r.process?n=r.process.env[t]:n=r[t],n}});pr.environment=_P});var Od=y(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.externalServiceHandler=bn.externalServiceTunnelConfig=void 0;var EP=Sr(),Mr=O(),wP=Nd(),Pi=W(),lt=(0,EP.debug)("zuplo:runtime:external-service");function Yy(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=Pi.Environment.instance.runtime;if(t&&t!=="undefined")try{let r=atob(t);e=JSON.parse(r)}catch{}return e}s(Yy,"getServiceAuth");async function vP(e){let t=Yy();if(!t)throw lt("There is no external service auth configured for this zup."),new Mr.RuntimeError("There are no external services configured for this zup.");if(typeof e!="string")throw lt("Cannot call external service with Request object"),new Mr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(e).hostname,i={};i["CF-Access-Client-Id"]=t.clientId,i["CF-Access-Client-Secret"]=t.clientSecret;let o;if(t.customServiceMapping&&t.customServiceMapping[n])o=`https://${t.customServiceMapping[n]}`;else if(Pi.Environment.instance.useSha256ServiceRouting){lt("Using sha256 service routing");let a=Pi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)o=`https://${await Zy(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw lt("Cannot use sha256 service routing, missing build variables"),new Mr.RuntimeError("Failed to generate fully qualified tunnel url.")}else o=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:o,tunnelHeaders:i}}s(vP,"externalServiceTunnelConfig");bn.externalServiceTunnelConfig=vP;async function TP(e,t){let r=Yy();if(r)if(lt(`Using external service auth. ClientId: ${r.clientId})`),typeof e=="string"){let n=new URL(e),i=n.hostname,o=t??{},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(Pi.Environment.instance.useSha256ServiceRouting){lt("Using sha256 service routing");let d=Pi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await Zy(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw lt("Cannot use sha256 service routing, missing build variables"),new Mr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);lt(`Calling external service: ${u.toString()}`);let l=await(0,wP.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 Mr.RuntimeError("Could not connect to secure tunnel.");return l}else throw lt("Cannot call external service with Request object"),new Mr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw lt("There is no external service auth configured for this zup."),new Mr.RuntimeError("There are no external services configured for this zup.")}s(TP,"externalServiceHandler");bn.externalServiceHandler=TP;async function Zy(e,t,r,n){let i=e.toLowerCase(),o=t.toLowerCase(),a=r.toLowerCase(),c=SP(n);lt(`Hashing service name: ${o}-${i}.${o}-${a}-${c}`);let u=await Qy(`${o}-${i}`),l=await Qy(`${o}-${a}-${c}`);return`${u}.${l}`}s(Zy,"hashServiceName");async function Qy(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Qy,"hashSegment");function SP(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}s(SP,"sanitizeEnvironmentType")});var Nd=y(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.originalFetch=void 0;var IP=Od(),Xy=new Map;Xy.set("service:",IP.externalServiceHandler);_n.originalFetch=globalThis.fetch;globalThis.fetch=function(e,t){let r=PP(t);if(typeof e=="string"){let n=new URL(e),i=Xy.get(n.protocol);return i?i(e,r):(0,_n.originalFetch)(e,r)}else return(0,_n.originalFetch)(e,r)};var PP=s(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let r=e;return r.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit")});var rg=y(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.Handler=En.purgeGatewayCache=void 0;var AP=O(),tg=Ir(),eg=W(),RP=s(()=>{tg.Gateway.purgeGatewayCache()},"purgeGatewayCache");En.purgeGatewayCache=RP;var xd=class{static{s(this,"Handler")}routeLoader;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(t,r,n,i,o,a,c){this.routeLoader=t,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=o,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(t,r)=>{eg.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await tg.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 AP.ConfigurationError&&(o=i.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:o,instance:t.url,trace:{timestamp:Date.now(),rayId:t.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:eg.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(t,r)}};En.Handler=xd});var sg=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 OP(e){for(var t=[],r=0;r<e.length;){var n=e[r];if(n==="*"||n==="+"||n==="?"){t.push({type:"MODIFIER",index:r,value:e[r++]});continue}if(n==="\\"){t.push({type:"ESCAPED_CHAR",index:r++,value:e[r++]});continue}if(n==="{"){t.push({type:"OPEN",index:r,value:e[r++]});continue}if(n==="}"){t.push({type:"CLOSE",index:r,value:e[r++]});continue}if(n===":"){for(var i="",o=r+1;o<e.length;){var a=e.charCodeAt(o);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=e[o++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));t.push({type:"NAME",index:r,value:i}),r=o;continue}if(n==="("){var c=1,u="",o=r+1;if(e[o]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(o));for(;o<e.length;){if(e[o]==="\\"){u+=e[o++]+e[o++];continue}if(e[o]===")"){if(c--,c===0){o++;break}}else if(e[o]==="("&&(c++,e[o+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(o));u+=e[o++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));t.push({type:"PATTERN",index:r,value:u}),r=o;continue}t.push({type:"CHAR",index:r,value:e[r++]})}return t.push({type:"END",index:r,value:""}),t}s(OP,"lexer");function Cd(e,t){t===void 0&&(t={});for(var r=OP(e),n=t.prefixes,i=n===void 0?"./":n,o="[^".concat(wn(t.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 Be=r[u],w=Be.type,k=Be.index;throw new TypeError("Unexpected ".concat(w," at ").concat(k,", expected ").concat(ie))},"mustConsume"),f=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 T=h||"";i.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:g||c++,prefix:T,suffix:"",pattern:_||o,modifier:d("MODIFIER")||""});continue}var S=h||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var H=d("OPEN");if(H){var T=f(),K=d("NAME")||"",L=d("PATTERN")||"",ne=f();p("CLOSE"),a.push({name:K||(L?c++:""),pattern:K&&!L?o:L,prefix:T,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Cd,"parse");Re.parse=Cd;function NP(e,t){return ng(Cd(e,t),t)}s(NP,"compile");Re.compile=NP;function ng(e,t){t===void 0&&(t={});var r=Ld(t),n=t.encode,i=n===void 0?function(u){return u}:n,o=t.validate,a=o===void 0?!0:o,c=e.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<e.length;d++){var p=e[d];if(typeof p=="string"){l+=p;continue}var f=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",g=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!g)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var _=0;_<f.length;_++){var T=i(f[_],p);if(a&&!c[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var T=i(String(f),p);if(a&&!c[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!h){var S=g?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}s(ng,"tokensToFunction");Re.tokensToFunction=ng;function xP(e,t){var r=[],n=Dd(e,r,t);return ig(n,r,t)}s(xP,"match");Re.match=xP;function ig(e,t,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(o){return o}:n;return function(o){var a=e.exec(o);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=s(function(f){if(a[f]===void 0)return"continue";var h=t[f-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[f].split(h.prefix+h.suffix).map(function(g){return i(g,h)}):l[h.name]=i(a[f],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}s(ig,"regexpToFunction");Re.regexpToFunction=ig;function wn(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(wn,"escapeString");function Ld(e){return e&&e.sensitive?"":"i"}s(Ld,"flags");function CP(e,t){if(!t)return e;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(e.source);i;)t.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(e.source);return e}s(CP,"regexpToRegexp");function LP(e,t,r){var n=e.map(function(i){return Dd(i,t,r).source});return new RegExp("(?:".concat(n.join("|"),")"),Ld(r))}s(LP,"arrayToRegexp");function DP(e,t,r){return og(Cd(e,r),t,r)}s(DP,"stringToRegexp");function og(e,t,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(k){return k}:l,p=r.delimiter,f=p===void 0?"/#?":p,h=r.endsWith,g=h===void 0?"":h,_="[".concat(wn(g),"]|$"),T="[".concat(wn(f),"]"),S=a?"^":"",H=0,K=e;H<K.length;H++){var L=K[H];if(typeof L=="string")S+=wn(d(L));else{var ne=wn(d(L.prefix)),ie=wn(d(L.suffix));if(L.pattern)if(t&&t.push(L),ne||ie)if(L.modifier==="+"||L.modifier==="*"){var me=L.modifier==="*"?"?":"";S+="(?:".concat(ne,"((?:").concat(L.pattern,")(?:").concat(ie).concat(ne,"(?:").concat(L.pattern,"))*)").concat(ie,")").concat(me)}else S+="(?:".concat(ne,"(").concat(L.pattern,")").concat(ie,")").concat(L.modifier);else L.modifier==="+"||L.modifier==="*"?S+="((?:".concat(L.pattern,")").concat(L.modifier,")"):S+="(".concat(L.pattern,")").concat(L.modifier);else S+="(?:".concat(ne).concat(ie,")").concat(L.modifier)}}if(u)i||(S+="".concat(T,"?")),S+=r.endsWith?"(?=".concat(_,")"):"$";else{var Be=e[e.length-1],w=typeof Be=="string"?T.indexOf(Be[Be.length-1])>-1:Be===void 0;i||(S+="(?:".concat(T,"(?=").concat(_,"))?")),w||(S+="(?=".concat(T,"|").concat(_,")"))}return new RegExp(S,Ld(r))}s(og,"tokensToRegexp");Re.tokensToRegexp=og;function Dd(e,t,r){return e instanceof RegExp?CP(e,t):Array.isArray(e)?LP(e,t,r):DP(e,t,r)}s(Dd,"pathToRegexp");Re.pathToRegexp=Dd});var Hd=y(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.AwsV4Signer=vn.AwsClient=void 0;var UP=Sr(),lg=O(),MP=(0,UP.debug)("zuplo:runtime"),Md=new TextEncoder,ag={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"},kP=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],kd=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:t,secretAccessKey:r,sessionToken:n,service:i,region:o,cache:a,retries:c,initRetryMs:u}){if(t==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=t,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(t,r){let n=new Ks(Object.assign({url:t},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(t,r){MP("AWS fetch",t);for(let n=0;n<=this.retries;n++){let{url:i,request:o}=await this.sign(t,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 lg.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};vn.AwsClient=kd;var Ks=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:t,url:r,headers:n,body:i,accessKeyId:o,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:f,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=t||(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 T,S;(!u||!l)&&([T,S]=HP(this.url,this.headers)),this.service=u||T||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let H=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"),H.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&H.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>g||!kP.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"&&!H.has("X-Amz-Expires")&&H.set("X-Amz-Expires","86400"),H.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),H.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),H.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=ug(this.encodedPath);let K=new Set;this.encodedSearch=[...this.url.searchParams].filter(([L])=>{if(!L)return!1;if(this.service==="s3"){if(K.has(L))return!1;K.add(L)}return!0}).map(L=>L.map(ne=>ug(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 t=this.datetime.slice(0,8),r=[this.secretAccessKey,t,this.region,this.service].join(),n=this.cache.get(r);if(!n){let i=await Ai("AWS4"+this.secretAccessKey,t),o=await Ai(i,this.region),a=await Ai(o,this.service);n=await Ai(a,"aws4_request"),this.cache.set(r,n)}return Ud(await Ai(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ud(await cg(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(`
|
|
@@ -71,7 +71,7 @@ Signature verification is impossible without access to the original signed mater
|
|
|
71
71
|
`+d}):new kr.StripeSignatureVerificationError(t,e,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
72
72
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
73
73
|
`+l+`
|
|
74
|
-
`+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new kr.StripeSignatureVerificationError(t,e,{message:"Timestamp outside the tolerance zone"});return!0}s(AR,"validateComputedSignature");function RR(e,t){return typeof e!="string"?null:e.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===t&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}s(RR,"parseHeader");function OR(e,t){if(e.length!==t.length)return!1;let r=e.length,n=0;for(let i=0;i<r;++i)n|=e.charCodeAt(i)^t.charCodeAt(i);return n===0}s(OR,"secureCompare");async function Jg(e,t){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(e)),o=new Uint8Array(i),a=new Array(o.length);for(let c=0;c<o.length;c++)a[c]=lp[o[c]];return a.join("")}s(Jg,"computeHMACSignatureAsync");xn.computeHMACSignatureAsync=Jg;var lp=new Array(256);for(let e=0;e<lp.length;e++)lp[e]=e.toString(16).padStart(2,"0")});var qt=y(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.optionValidator=void 0;var Oi=O();function NR(e,t){let r=s((o,a,c)=>{let u=e[o];if(!(c&&u===void 0)){if(u===void 0)throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=s((o,a)=>(r(o,a,!0),{optional:n,required:i}),"optional"),i=s((o,a)=>(r(o,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}s(NR,"optionValidator");ha.optionValidator=NR});var dp=y(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.StripeWebhookVerificationInboundPolicy=void 0;var xR=te(),CR=zg(),LR=qt(),DR=s(async(e,t,r,n)=>{(0,LR.optionValidator)(r,n).required("signingSecret","string").optional("tolerance","number");let i=e.headers.get("stripe-signature");try{let o=await e.clone().text();await(0,CR.constructEventAsync)(o,i,r.signingSecret)}catch(o){return t.log.error("Error validating stripe webhook",o),xR.HttpProblems.badRequest(e,t,{title:"Webhook Error",detail:o.message})}return e},"StripeWebhookVerificationInboundPolicy");fa.StripeWebhookVerificationInboundPolicy=DR});var Qg=y(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.isStripeWebhookEvent=void 0;var Wg=st();function UR(e){return e!==null&&typeof e=="object"&&"id"in e&&(0,Wg.isString)(e.id)&&"type"in e&&(0,Wg.isString)(e.type)}s(UR,"isStripeWebhookEvent");ma.isStripeWebhookEvent=UR});var Yg=y(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.MeteringPlugin=void 0;var MR=gt(),pp=class extends MR.SystemRuntimePlugin{static{s(this,"MeteringPlugin")}};ya.MeteringPlugin=pp});var Xg=y(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var Zg=O(),kR={getSubscription:async({subscriptionId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let o="Error retrieving subscription from Stripe API.";throw r.error(o,i),new Zg.RuntimeError(o)}return i},getCustomer:async({customerId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let o="Error retrieving customer from Stripe API.";throw r.error(o,i),new Zg.RuntimeError(o)}}};hp.default=kR});var nb=y(Ni=>{"use strict";var HR=Ni&&Ni.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ni,"__esModule",{value:!0});var yr=O(),fp=te(),eb=He(),tb=W(),rb=hn(),FR=HR(Xg()),qR=st();async function $R(e,t,r,n){let i=r.data?.object?.subscription;if(!i)throw new yr.RuntimeError("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");let o=r.data?.object?.client_reference_id,a=r.data?.object?.customer_email;if(!o)throw new yr.RuntimeError("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!a)throw new yr.RuntimeError("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");let c=await FR.default.getSubscription({logger:t.log,stripeSecretKey:n.stripeSecretKey,subscriptionId:i}),u=c.id,l=c.customer,d=c.items?.data.find(_=>_.object==="subscription_item");if(!d||!d.id)throw new yr.RuntimeError("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let p=d.plan;if(!p||!p.product)throw new yr.RuntimeError("Invalid Stripe API result. Expected subscription_item to have a plan.");let f=p.product,h=await jR({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:f,stripeSubscriptionId:u,stripeCustomerId:l,managerEmail:a,managerSub:o,context:t});if(!h)return fp.HttpProblems.internalServerError(e,t,{detail:"No consumer was created, skipping creation of subscription"});let g="routes.oas.json";try{await VR({context:t,stripeProductId:f,stripeSubscriptionId:u,customerKey:h,productKey:g,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:l})}catch(_){return fp.HttpProblems.internalServerError(e,t,{detail:_.message})}return fp.HttpProblems.ok(e,t)}s($R,"onCheckoutSessionCompleted");Ni.default=$R;async function jR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:o,context:a}){let{authApiJWT:c}=tb.Environment.instance,u="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${e}/consumers`,u);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[{sub:o,email:i}]},f=await(0,rb.fetchRetry)({retryDelayMs:5,retries:2,logger:eb.SystemLogMap.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(p)}),h=await f.json();if(f.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,h),new yr.RuntimeError(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:t,stripeProductId:r}),d}s(jR,"createConsumer");async function VR({context:e,stripeSubscriptionId:t,stripeProductId:r,customerKey:n,productKey:i,meteringBucketId:o,meteringBucketRegion:a,customerExternalId:c}){let u={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:t,planExternalIds:[r],customerKey:n,productKey:i,customerExternalId:c},{authApiJWT:l,meteringServiceUrl:d}=tb.Environment.instance;if(!(0,qR.isNonEmptyString)(l))throw new yr.SystemError("No Zuplo JWT token set.");let p=await(0,rb.fetchRetry)({retryDelayMs:5,retries:2,logger:eb.SystemLogMap.getLogger(e)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"POST",body:JSON.stringify(u)});if(!p.ok){let f="Error creating metering subscription.",h;try{h=await p.json()}catch{h={status:p.status,statusText:p.statusText}}throw e.log.error(f,h),new yr.RuntimeError(f)}e.log.info("Successfully created/updated metering subscription.",u)}s(VR,"saveSubscription")});var ab=y(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var mp=O(),ib=te(),ob=He(),GR=W(),sb=hn(),BR=st();async function KR(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:o}=GR.Environment.instance;if(!(0,BR.isNonEmptyString)(i))throw new mp.SystemError("No Zuplo JWT token set.");let a=r.data.object.id,c=await(0,sb.fetchRetry)({retryDelayMs:5,retries:2,logger:ob.SystemLogMap.getLogger(t)},`${o}/internal/v1/metering/${n.meteringBucketId}/subscriptions`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!c.ok){let p="Error querying for metering subscription.",f;try{f=await c.json()}catch{f={status:c.status,statusText:c.statusText}}throw t.log.error(p,f),new mp.RuntimeError(p)}let l=(await c.json()).data.filter(p=>p.subscriptionExternalId&&p.subscriptionExternalId===a);if(l.length===0)return ib.HttpProblems.ok(e,t,{detail:"Subscription was not found and the event was ignored by Stripe metering plugin webhook."});let d=await(0,sb.fetchRetry)({retryDelayMs:5,retries:2,logger:ob.SystemLogMap.getLogger(t)},`${o}/internal/v1/metering/${n.meteringBucketId}/subscriptions/${l[0].id}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify({status:"canceled"})});if(!d.ok){let p="Error canceling metering subscription.",f;try{f=await d.json()}catch{f={status:d.status,statusText:d.statusText}}throw t.log.error(p,f),new mp.RuntimeError(p)}return t.log.info("Successfully canceled metering subscription."),ib.HttpProblems.ok(e,t)}s(KR,"onCustomerSubscriptionDeleted");yp.default=KR});var lb=y(Cn=>{"use strict";var ub=Cn&&Cn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.StripeMeteringPlugin=void 0;var ga=gn(),ba=O(),JR=Lt(),zR=dp(),cb=te(),WR=Qt(),QR=Wr(),YR=qu(),ZR=ot(),XR=W(),e0=Qg(),t0=Yg(),r0=ub(nb()),n0=ub(ab()),gp=class extends t0.MeteringPlugin{static{s(this,"StripeMeteringPlugin")}options;constructor(t){super(),this.options=t}registerRoutes(t,r){let n=s(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(ga.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=ga.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new ba.ConfigurationError("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!d)if(ga.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=ga.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new ba.ConfigurationError("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!XR.Environment.instance.build.ACCOUNT_NAME)throw new ba.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!i0(p))throw new ba.ConfigurationError(`StripeMeteringPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,e0.isStripeWebhookEvent)(f))return cb.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"checkout.session.completed":return await(0,r0.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,n0.default)(c,u,f,{meteringBucketId:l});default:return cb.HttpProblems.ok(c,u,{detail:"Event was ignored by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=(0,QR.createInternalPolicyProcessor)({inboundPolicies:[{handler:zR.StripeWebhookVerificationInboundPolicy,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),o=new JR.Pipeline({processors:[WR.metricsProcessor,i],handler:n,gateway:r}),a=new ZR.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:YR.SystemRouteName.StripePlugin});t.addRoute(a,o.execute)}};Cn.StripeMeteringPlugin=gp;function i0(e){return e!==null&&typeof e=="string"&&["us-central1","europe-west4"].includes(e)}s(i0,"isMetricsRegion")});var mb=y(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.AmberfloMeteringInboundPolicy=Ln.AmberfloMeteringPolicy=void 0;var db=O(),o0=ve(),pb=si(),fb=new WeakMap,hb={},bp=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){fb.set(t,r)}};Ln.AmberfloMeteringPolicy=bp;async function s0(e,t,r,n){if(!r.statusCodes)throw new db.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,pb.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async o=>{if(i.includes(o.status)){let a=fb.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new db.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,pb.getValueFromRequestUser)(e.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=hb[r.apiKey];if(!f){let h=r.apiKey,g=e.headers.get("zm-test-id")??"";f=new o0.BatchDispatch("amberflo-ingest-meter",10,async _=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(_),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":g}});S.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),hb[h]=f}f.enqueue(p),t.waitUntil(f.waitUntilFlushed())}}),e}s(s0,"AmberfloMeteringInboundPolicy");Ln.AmberfloMeteringInboundPolicy=s0});var _p=y(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.sha256=void 0;async function a0(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest({name:"SHA-256"},t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}s(a0,"sha256");_a.sha256=a0});var $t=y(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.getPolicyCacheName=void 0;var c0=_p(),yb=new Map;async function u0(e,t){let r,n=yb.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,c0.sha256)(JSON.stringify({policyName:e,options:t}))}`,yb.set(e,r)),r}s(u0,"getPolicyCacheName");Ea.getPolicyCacheName=u0});var vp=y(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.ApiKeyInboundPolicy=void 0;var l0=$t(),d0=Kt(),gb=gn(),Ep=O(),p0=Dt(),bb=He(),wp=W(),h0=hn(),_b="key-metadata-cache-type";function f0(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}s(f0,"getKeyValue");async function m0(e,t,r,n){if(!r.bucketName)if(gb.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=gb.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Ep.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Ep.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let o=s(T=>i.allowUnauthenticatedRequests?e:p0.HttpProblems.unauthorized(e,t,{detail:T}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return o("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return o("Invalid Authorization Scheme");let c=f0(a,i);if(!c||c==="")return o("No key present");let u=await y0(c),l=await(0,l0.getPolicyCacheName)(n,i),d=new d0.MemoryZoneReadThroughCache(l,t),p=await d.get(u);if(p&&p.isValid===!0)return e.user=p.user,e;if(p&&!p.isValid)return p.typeId!==_b&&bb.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),o("Authorization Failed");let f={key:c},h=await(0,h0.fetchRetry)({retryDelayMs:5,retries:2,logger:bb.SystemLogMap.getLogger(t)},`${wp.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":wp.Environment.instance.deploymentName??"unknown","User-Agent":wp.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),o("Authorization Failed");if(h.status!==200){try{let T=await h.text(),S=JSON.parse(T);t.log.error("Unexpected response from key service",S)}catch{t.log.error("Invalid response from key service")}throw new Ep.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let g=await h.json(),_={isValid:!0,typeId:_b,user:{sub:g.name,data:g.metadata}};return e.user=_.user,d.put(u,_,i.cacheTtlSeconds),e}s(m0,"ApiKeyInboundPolicy");wa.ApiKeyInboundPolicy=m0;async function y0(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(y0,"hashValue")});var Eb=y(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.ApiAuthKeyInboundPolicy=void 0;var g0=vp();va.ApiAuthKeyInboundPolicy=g0.ApiKeyInboundPolicy});var jt=y(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.OpenIdJwtInboundPolicy=void 0;var Sp=(Ps(),no(Is)),Ip=O(),b0=te(),Tp={},_0=s(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new Ip.ConfigurationError("Invalid State - jwkUrl not set");Tp[t.jwkUrl]||(Tp[t.jwkUrl]=(0,Sp.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,Sp.jwtVerify)(e,Tp[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),E0=s(async(e,t)=>{let r;if(t.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof t.secret=="string"){let o=new TextEncoder().encode(t.secret);r=new Uint8Array(o)}else r=t.secret;let{payload:n}=await(0,Sp.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),w0=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),o="bearer ",a=s(f=>b0.HttpProblems.unauthorized(e,t,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Ip.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Ip.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?_0:E0,l=await s(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(o)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(o.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let g=new URL(e.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${g.pathname} `,h):t.log.warn(`Invalid token on: ${e.method} ${g.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?e:l;let d=r.subPropertyName??"sub",p=l[d];return p?(e.user={sub:p,data:l},e):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");Ta.OpenIdJwtInboundPolicy=w0});var wb=y(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.Auth0JwtInboundPolicy=void 0;var v0=jt(),T0=s(async(e,t,r,n)=>(0,v0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");Sa.Auth0JwtInboundPolicy=T0});var vb=y(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.BasicAuthInboundPolicy=void 0;var S0=te(),I0=s(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",o=s(l=>S0.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await s(async()=>{if(!n)return await o("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await o("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await o("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await o("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),g=r.accounts.find(_=>_.username===f&&_.password===h);return g||await o("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?e:c;let u=c.username;return e.user={sub:u,data:c.data},e},"BasicAuthInboundPolicy");Ia.BasicAuthInboundPolicy=I0});var Tb=y(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.CachingInboundPolicy=void 0;var P0=$t(),A0=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function R0(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(R0,"digestMessage");var O0=s(async(e,t)=>{let r=[...t.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...t.headers??[]],n=[];for(let[d,p]of e.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await R0(JSON.stringify(n)),o=new URL(e.url),a=new URLSearchParams(o.searchParams);a.set("_z-hdr-dgst",i);let c=t.cacheHttpMethods?.includes(e.method.toUpperCase())&&e.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",e.method);let u=`${o.origin}${o.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function N0(e,t,r,n){let i=await(0,P0.getPolicyCacheName)(n,r),o=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await O0(e,r),u=await o.match(c);return u||(t.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(e.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);A0.forEach(g=>h.headers.delete(g)),h.headers.set("cache-control",`s-maxage=${f}`),t.waitUntil(o.put(c,h))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}s(N0,"CachingInboundPolicy");Pa.CachingInboundPolicy=N0});var Sb=y(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.ChangeMethodInboundPolicy=void 0;var x0=O(),C0=ke(),L0=s(async(e,t,r,n)=>{if(!r.method)throw new x0.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new C0.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");Aa.ChangeMethodInboundPolicy=L0});var Ib=y(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.ClearHeadersInboundPolicy=void 0;var D0=ke(),U0=s(async(e,t,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=e.headers.get(a);c&&i.set(a,c)}),new D0.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");Ra.ClearHeadersInboundPolicy=U0});var Pb=y(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.ClearHeadersOutboundPolicy=void 0;var M0=s(async(e,t,r,n)=>{let i=[...n.exclude??[]],o=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&o.set(c,u)}),new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");Oa.ClearHeadersOutboundPolicy=M0});var Ab=y(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.ClerkJwtInboundPolicy=void 0;var k0=jt(),H0=s(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),o=new URL(i);return o.pathname="/.well-known/jwks.json",(0,k0.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:o.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");Na.ClerkJwtInboundPolicy=H0});var Ob=y(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.CognitoJwtInboundPolicy=void 0;var Rb=O(),F0=jt(),q0=s(async(e,t,r,n)=>{if(!r.userPoolId)throw new Rb.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new Rb.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,F0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");xa.CognitoJwtInboundPolicy=q0});var xb=y(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.CompositeInboundPolicy=void 0;var $0=O(),j0=Ir(),Nb=Wr(),V0=s(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new $0.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=j0.Gateway.instance,o=(0,Nb.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Nb.toStackedInboundHandler)(o)(e,t)},"CompositeInboundPolicy");Ca.CompositeInboundPolicy=V0});var Lb=y(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.CreditsMeteringInboundPolicy=void 0;var xi=te(),Cb=W(),G0=s(async(e,t,r)=>{let n=e.user;if(!n)return xi.HttpProblems.unauthorized(e,t,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:i}=n;if(!r.bucketId)return xi.HttpProblems.unauthorized(e,t,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let o=r.bucketId,a=await B0(o,i,t);if(!a)return xi.HttpProblems.unauthorized(e,t,{title:"No valid, active subscription found"});if(!a.quotas)return xi.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});for(let c of Object.keys(a.quotas))if(a.quotas[c]<=0)return xi.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});return t.custom.subscription=a,t.addResponseSendingFinalHook(async()=>{let c=t.custom.meters,u={};for(let l of Object.keys(c))u[l]=c[l];await K0(o,a.id,u,t)}),e},"CreditsMeteringInboundPolicy");La.CreditsMeteringInboundPolicy=G0;async function B0(e,t,r){let{authApiJWT:n,meteringServiceUrl:i}=Cb.Environment.instance,o=new URL(`${i}/internal/v1/metering/${e}/subscriptions`);o.search=new URLSearchParams({customerKey:t,status:"active"}).toString();let a=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${n}`,"zp-rid":r.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let c=await a.json();if(c.data.length!==0)return c.data.length>1&&r.log.warn(`Found more than one active subscription for customer ${t} -- using the first one.`),c.data[0]}s(B0,"getSubscription");async function K0(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:o}=Cb.Environment.instance,a=new URL(`${o}/internal/v1/metering/${e}/subscriptions/${t}/quotas/consume`),c=await fetch(a,{method:"POST",body:JSON.stringify({meters:r}),headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId}});c.ok||n.log.error(`Error consuming subscription quotas for credits metering ': ${c.status} - ${await c.text()}`)}s(K0,"consumeSubscription")});var Db=y(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.CurityPhantomTokenInboundPolicy=void 0;var J0=$t(),z0=Kt(),Da=te(),W0=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return Da.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let o=Q0(i);if(!o)return Da.HttpProblems.unauthorized(e,t,{detail:"Failed to parse token from Authorization header"});let a=await(0,J0.getPolicyCacheName)(n,r),c=new z0.MemoryZoneReadThroughCache(a,t),u=await c.get(o);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+o+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(o,u,r.cacheDurationSeconds??600);else return l.status>=500?(t.log.error(`Error introspecting token - ${l.status}: '${d}'`),Da.HttpProblems.internalServerError(e,t,{detail:"Problem encountered authorizing the HTTP request"})):Da.HttpProblems.unauthorized(e,t)}return e.headers.set("Authorization",`Bearer ${u}`),e},"CurityPhantomTokenInboundPolicy");Ua.CurityPhantomTokenInboundPolicy=W0;function Q0(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}s(Q0,"getToken")});var Ub=y(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.FirebaseJwtInboundPolicy=void 0;var Y0=qt(),Z0=jt(),X0=s(async(e,t,r,n)=>((0,Y0.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,Z0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");Ma.FirebaseJwtInboundPolicy=X0});var Mb=y(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.FormDataToJsonInboundPolicy=void 0;var eO=ke(),tO=s(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",o=e.headers.get("content-type")?.toLowerCase();if(!o||![i,n].includes(o))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):e;let a=await e.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(e.headers);return u.set("content-type","application/json"),u.delete("content-length"),new eO.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");ka.FormDataToJsonInboundPolicy=tO});var kb=y(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.GeoFilterInboundPolicy=void 0;var rO=O(),nO=te(),Dn="__unknown__",iO=s(async(e,t,r,n)=>{let i={allow:{countries:Mn(r.allow?.countries,"allow.countries",n),regionCodes:Mn(r.allow?.regionCodes,"allow.regionCode",n),asns:Mn(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Mn(r.block?.countries,"block.countries",n),regionCodes:Mn(r.block?.regionCodes,"block.regionCode",n),asns:Mn(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},o=t.incomingRequestProperties.country?.toLowerCase()??Dn,a=t.incomingRequestProperties.regionCode?.toLowerCase()??Dn,c=t.incomingRequestProperties.asn?.toString()??Dn,u=i.ignoreUnknown&&o===Dn,l=i.ignoreUnknown&&a===Dn,d=i.ignoreUnknown&&c===Dn,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(o)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Un(e,t,n,o,a,c);let g=i.block.countries,_=i.block.regionCodes,T=i.block.asns;return g.length>0&&g.includes(o)&&!u||_.length>0&&_.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Un(e,t,n,o,a,c):e},"GeoFilterInboundPolicy");Ha.GeoFilterInboundPolicy=iO;function Un(e,t,r,n,i,o){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${o}')`),nO.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:o}})}s(Un,"blockedResponse");function Mn(e,t,r){if(typeof e=="string")return e.split(",").map(n=>n.trim().toLowerCase());if(typeof e>"u")return[];if(Array.isArray(e))return e.map(n=>n.trim().toLowerCase());throw new rO.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}s(Mn,"toLowerStringArray")});var Hb=y(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.JWTScopeValidationInboundPolicy=void 0;var oO=s(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!s((o,a)=>a.every(c=>o.includes(c)),"scopeChecker")(n,r.scopes)){let o={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(o),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");Fa.JWTScopeValidationInboundPolicy=oO});var qb=y(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.MockApiInboundPolicy=void 0;var sO=te(),aO=s(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return Pp(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let o=Object.keys(i),a=[];if(o.length===0)return Pp(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(o.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return Fb(a[c])}else return a.length>0?Fb(a[0]):Pp(n,e,t,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");qa.MockApiInboundPolicy=aO;function Fb(e){let t=JSON.stringify(e.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",e.contentName),e.responseName){case"1XX":return new Response(t,{status:100,headers:r});case"2XX":return new Response(t,{status:200,headers:r});case"3XX":return new Response(t,{status:300,headers:r});case"4XX":return new Response(t,{status:400,headers:r});case"5XX":case"default":return new Response(t,{status:500,headers:r});default:return new Response(t,{status:Number(e.responseName),headers:r})}}s(Fb,"generateResponse");var Pp=s((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return sO.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var Bb=y(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.MoesifInboundPolicy=kn.setMoesifContext=void 0;var cO=O(),uO=ve(),lO="Incoming",dO={logRequestBody:!0,logResponseBody:!0};function $b(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}s($b,"headersToObject");function jb(){return new Date().toISOString()}s(jb,"timestamp");var Ap=new WeakMap,pO={};function hO(e,t){let r=Ap.get(e);r||(r=pO);let n=Object.assign({...r},t);Ap.set(e,n)}s(hO,"setMoesifContext");kn.setMoesifContext=hO;async function Vb(e,t){let r=e.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await e.clone().json()}catch(i){t.log.error(i)}let n=await e.clone().text();return t.log.debug({textBody:n}),n}s(Vb,"readBody");var fO={},Rp;function Gb(){if(!Rp)throw new cO.RuntimeError("Invalid State - no _lastLogger");return Rp}s(Gb,"getLastLogger");function mO(e){let t=fO[e];return t||(t=new uO.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);Gb().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":e},body:n});i.ok||Gb().error({status:i.status,body:await i.text()})})),t}s(mO,"getDispatcher");async function yO(e,t,r,n){Rp=t.log;let i=jb(),o=Object.assign(dO,r);if(!o.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=o.logRequestBody?await Vb(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=mO(o.applicationId),d=e.headers.get("true-client-ip"),p=Ap.get(t)??{},f={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:$b(e.headers)},h=o.logResponseBody?await Vb(c,t):void 0,g={time:jb(),status:c.status,headers:$b(c.headers),body:h},_={request:f,response:g,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:lO};l.enqueue(_),t.waitUntil(l.waitUntilFlushed())}),e}s(yO,"MoesifInboundPolicy");kn.MoesifInboundPolicy=yO});var Kb=y($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.OktaJwtInboundPolicy=void 0;var gO=jt(),bO=s(async(e,t,r,n)=>(0,gO.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");$a.OktaJwtInboundPolicy=bO});var Jb=y(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.PropelAuthJwtInboundPolicy=void 0;var _O=(Ps(),no(Is)),EO=jt(),Op,wO=s(async(e,t,r,n)=>{if(!Op)try{Op=await(0,_O.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,EO.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:Op,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");ja.PropelAuthJwtInboundPolicy=wO});var zb=y(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.throwIfStateNotObject=V.throwIfStateNotNumber=V.throwIfStateNotString=V.throwIfStateUndefinedOrNull=V.throwIfStateUndefined=V.throwIfOptionNotObject=V.throwIfOptionNotNumber=V.throwIfOptionNotString=V.throwIfOptionUndefinedOrNull=V.throwIfOptionUndefined=V.OptionTypeError=V.OptionUndefinedError=V.throwIfNotNumber=V.throwIfNotString=V.throwIfUndefinedOrNull=V.throwIfUndefined=V.ArgumentTypeError=V.ArgumentUndefinedError=V.ValidationError=void 0;var je=st(),et=class extends Error{static{s(this,"ValidationError")}constructor(t){super(t)}};V.ValidationError=et;var Ci=class extends et{static{s(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};V.ArgumentUndefinedError=Ci;var Li=class extends et{static{s(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};V.ArgumentTypeError=Li;function vO(e,t){if((0,je.isUndefined)(e))throw new Ci(t)}s(vO,"throwIfUndefined");V.throwIfUndefined=vO;function Np(e,t){if((0,je.isUndefinedOrNull)(e))throw new Ci(t)}s(Np,"throwIfUndefinedOrNull");V.throwIfUndefinedOrNull=Np;function TO(e,t){if(Np(e,t),!(0,je.isString)(e))throw new Li(t,"string")}s(TO,"throwIfNotString");V.throwIfNotString=TO;function SO(e,t){if(Np(e,t),!(0,je.isNumber)(e))throw new Li(t,"number")}s(SO,"throwIfNotNumber");V.throwIfNotNumber=SO;var Di=class extends et{static{s(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};V.OptionUndefinedError=Di;var Hn=class extends et{static{s(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};V.OptionTypeError=Hn;function IO(e,t,r,n){if((0,je.isUndefined)(n))throw new Di(e,t,r)}s(IO,"throwIfOptionUndefined");V.throwIfOptionUndefined=IO;function Va(e,t,r,n){if((0,je.isUndefinedOrNull)(n))throw new Di(e,t,r)}s(Va,"throwIfOptionUndefinedOrNull");V.throwIfOptionUndefinedOrNull=Va;function PO(e,t,r,n){if(Va(e,t,r,n),!(0,je.isString)(n))throw new Hn(e,t,r,"string")}s(PO,"throwIfOptionNotString");V.throwIfOptionNotString=PO;function AO(e,t,r,n){if(Va(e,t,r,n),!(0,je.isNumber)(n))throw new Hn(e,t,r,"number")}s(AO,"throwIfOptionNotNumber");V.throwIfOptionNotNumber=AO;function RO(e,t,r,n){if(Va(e,t,r,n),!(0,je.isObject)(n))throw new Hn(e,t,r,"object")}s(RO,"throwIfOptionNotObject");V.throwIfOptionNotObject=RO;function OO(e,t){if((0,je.isUndefined)(e))throw new et(t)}s(OO,"throwIfStateUndefined");V.throwIfStateUndefined=OO;function Ga(e,t){if((0,je.isUndefinedOrNull)(e))throw new et(t)}s(Ga,"throwIfStateUndefinedOrNull");V.throwIfStateUndefinedOrNull=Ga;function NO(e,t){if(Ga(e,t),!(0,je.isString)(e))throw new et(t);return!0}s(NO,"throwIfStateNotString");V.throwIfStateNotString=NO;function xO(e,t){if(Ga(e,t),!(0,je.isNumber)(e))throw new et(t);return!0}s(xO,"throwIfStateNotNumber");V.throwIfStateNotNumber=xO;function CO(e,t){if(Ga(e,t),!(0,je.isObject)(e))throw new et(t);return!0}s(CO,"throwIfStateNotObject");V.throwIfStateNotObject=CO});var Wb=y(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.InMemoryRedisClient=Fn.StandardRedisClient=void 0;var xp=O(),Ba=zb(),Cp=class e{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(t,r,n,i){this.redisClientUrl=t,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(t,r,n,i){return(0,Ba.throwIfNotString)(t,"redisClientUrl"),(0,Ba.throwIfNotString)(r,"clientAuthToken"),e.instance||(e.instance=new e(t,r,n,i)),e.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:t,body:r,method:n,requestId:i}){(0,Ba.throwIfNotString)(t,"url");let o=await fetch(`${this.redisClientUrl}${t}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=o.headers.get("Content-Type")?.includes("application/json")?await o.json():await o.text();if(o.ok)return a;throw o.status===401?new xp.SystemError("Redis client failed with 401: Unauthorized"):new xp.SystemError(`Redis client failed with (${o.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Fn.StandardRedisClient=Cp;var Lp=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,Ba.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:o,key:a}=JSON.parse(r),c=Date.now()+o*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new xp.SystemError("The in-memory redis client only supports /rate-limit calls")}};Fn.InMemoryRedisClient=Lp});var e_=y(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.RateLimitInboundPolicy=void 0;var LO=Sr(),DO=$t(),UO=ri(),At=O(),MO=te(),Qb=He(),Ui=W(),Yb=Wb(),Zb=st(),Ka=(0,LO.debug)("zuplo:policies:RateLimitInboundPolicy"),kO="strict",HO=s(e=>{let t=e.headers.get("cf-connecting-ip")??e.headers.get("true-client-ip");if(t)return t;let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),FO=s(async e=>({key:`ip-${HO(e)}`}),"getIP"),qO=s(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),$O=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Ja;function jO(e,t){let r;if(Ja)return Ja;if(Ui.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new Yb.InMemoryRedisClient,Ja=r,r;let{authApiJWT:n,redisURL:i}=Ui.Environment.instance;if(!(0,Zb.isString)(i))throw new At.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,Zb.isString)(n))throw new At.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=Yb.StandardRedisClient.initialize(i,n,Ui.Environment.instance.deploymentName??"unknown",Ui.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new At.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Ja=r,r}s(jO,"getRedisClient");async function Xb(e,t,r,n,i){let o=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:i})}s(Xb,"getCountAndUpdateExpiry");function VO(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=e.identifier.module[e.identifier.export],!r||typeof r!="function")throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,o,a)=>{let c=await r(i,o,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw o.log.error(u),new At.RuntimeError(u)}return c},"outerFunction")}s(VO,"wrapUserFunction");var GO="Retry-After",BO=s(async(e,t,r,n)=>{let i=Date.now(),o=Qb.SystemLogMap.getLogger(t),a=s((u,l)=>{if(r.throwOnFailure)throw new At.SystemError(u,{cause:l});o.error(u,l)},"throwOrLog"),c=s((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[GO]=l.toString()),MO.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:VO(r,n),user:qO,ip:FO,all:$O}[r.rateLimitBy],d=await l(e,t,n),p=d.key,f=d.requestsAllowed??r.requestsAllowed,h=d.timeWindowMinutes??r.timeWindowMinutes,g=r.headerMode??"retry-after",_=jO(n,o),S=`bucket/${Ui.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??kO)==="async"){let L=await(0,DO.getPolicyCacheName)(n,r),ne=new UO.ZoneCache(L,{logger:Qb.SystemLogMap.getLogger(t)}),ie=Xb(S,h,_,o,t.requestId),me=await ne.get(S);if(me!==void 0&&me<=Date.now()){Ka(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let Be=Math.round((me-Date.now())/1e3);return c(g,Be)}return t.addEventListener("responseSending",Be=>{try{let w=Be,k=w.mutableResponse;w.mutableResponse=(async()=>{let Ce=await ie;if(Ce.count>f){let uu=Date.now()+Ce.ttlSeconds*1e3,jE=ne.put(S,uu,Ce.ttlSeconds).catch(wh=>{throw o.error(new At.SystemError("Error caching rate limit result.",{cause:wh})),wh});return t.waitUntil(jE),Ka(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(g,Ce.ttlSeconds)}return k})()}catch(w){o.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,w)}}),e}let K=await Xb(S,h,_,o,t.requestId);return K.count>f?(Ka(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(g,K.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;Ka(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");za.RateLimitInboundPolicy=BO});var i_=y(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.ReadmeMetricsInboundPolicy=void 0;var KO=ve(),Dp=W(),t_=si(),Up;function r_(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}s(r_,"headersToNameValuePairs");function JO(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}s(JO,"queryToNameValueParis");function zO(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}s(zO,"parseIntOrUndefined");var n_={};async function WO(e,t,r,n){let i=new Date,o=Date.now();return Up||(Up={name:"zuplo",version:Dp.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Dp.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,t_.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,t_.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Dp.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:Up,entries:[{startedDateTime:i.toISOString(),time:Date.now()-o,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:r_(e.headers),queryString:JO(e.query)},response:{status:a.status,statusText:a.statusText,headers:r_(a.headers),content:{size:zO(e.headers.get("content-length"))}}}]}}},d=n_[r.apiKey];if(!d){let p=r.apiKey;d=new KO.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",g=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});g.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${g.status}: '${await g.text()}'`)}catch(h){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),n_[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}s(WO,"ReadmeMetricsInboundPolicy");Wa.ReadmeMetricsInboundPolicy=WO});var o_=y(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.RemoveHeadersInboundPolicy=void 0;var QO=O(),YO=ke(),ZO=s(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new QO.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let o=new Headers(e.headers);return i.forEach(c=>{o.delete(c)}),new YO.ZuploRequest(e,{headers:o})},"RemoveHeadersInboundPolicy");Qa.RemoveHeadersInboundPolicy=ZO});var s_=y(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.RemoveHeadersOutboundPolicy=void 0;var XO=O(),eN=s(async(e,t,r,n,i)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new XO.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return o.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Ya.RemoveHeadersOutboundPolicy=eN});var a_=y(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.RemoveQueryParamsInboundPolicy=void 0;var tN=O(),rN=ke(),nN=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new tN.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let o=new URL(e.url);return i.forEach(c=>{o.searchParams.delete(c)}),new rN.ZuploRequest(o.toString(),e)},"RemoveQueryParamsInboundPolicy");Za.RemoveQueryParamsInboundPolicy=nN});var c_=y(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.ReplaceStringOutboundPolicy=void 0;var iN=s(async(e,t,r,n)=>{let i=await e.text(),o=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(o,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Xa.ReplaceStringOutboundPolicy=iN});var l_=y(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.RequestSizeLimitInboundPolicy=void 0;var u_=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),oN=s(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),o=i!==null?parseInt(i):void 0;return o&&!isNaN(o)&&o>r.maxSizeInBytes?u_():o&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?u_():e},"RequestSizeLimitInboundPolicy");ec.RequestSizeLimitInboundPolicy=oN});var tc=y(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function sN(e,t,r){return`_${Hr(e+"_"+t+"_"+r)}`}s(sN,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=sN;function aN(e,t,r,n){return`_${Hr(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}s(aN,"getIdForParameterSchema");tt.getIdForParameterSchema=aN;function cN(e,t,r){return`_${Hr(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${Hr(r.toLowerCase())}`}s(cN,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=cN;function uN(e,t){return`_${Hr(e)}__${Hr(t)}`}s(uN,"getIdForRefSchema");tt.getIdForRefSchema=uN;function Hr(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?t.push(e.charAt(r)):t.push("_")}return t.join("")}s(Hr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Hr});var Mi=y(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.getErrorsFromValidator=Le.shouldReject=Le.shouldLog=Le.logErrors=Le.validateParameters=Le.getParametersForOperation=void 0;var lN=Ir(),dN=tc(),pN=s(e=>{let t=e.route.raw();return t.parameters?t.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");Le.getParametersForOperation=pN;var hN=s((e,t,r,n,i)=>{let o=[],a=!0,c=[];return e.forEach(u=>{let l=u.required||i==="path";if(l&&!t[u.name])a=!1,o.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!t[u.name])){let d=(0,dN.getIdForParameterSchema)(r,n,i,u.name),p=lN.Gateway.instance.schemaValidator[d],f=p(t[u.name]),h=(0,Le.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),o.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:o}},"validateParameters");Le.validateParameters=hN;var fN=s((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");Le.logErrors=fN;var mN=s(e=>e==="log-only"||e==="reject-and-log","shouldLog");Le.shouldLog=mN;var yN=s(e=>e==="reject-only"||e==="reject-and-log","shouldReject");Le.shouldReject=yN;var gN=s(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");Le.getErrorsFromValidator=gN});var d_=y(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.handleBodyValidation=void 0;var bN=Ir(),rc=te(),_N=tc(),Je=Mi();async function EN(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(h){let g=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,_=rc.HttpProblems.badRequest(t,e,{detail:`${g}, see errors property for more details`,errors:`${h}`});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",g,[n],h),(0,Je.shouldReject)(r.validateBody))return _}if(!t.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,g=rc.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?g:void 0}let i=t.headers.get("Content-Type"),o=i.indexOf(";");o>-1&&(i=i.substring(0,o));let a=(0,_N.getIdForRequestBodySchema)(e.route.path,t.method,i),c=bN.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,g=rc.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?g:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Je.getErrorsFromValidator)(l),f=rc.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",d,[n],p),(0,Je.shouldReject)(r.validateBody))return f}s(EN,"handleBodyValidation");nc.handleBodyValidation=EN});var p_=y(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.handleHeadersValidation=void 0;var wN=te(),ki=Mi();function vN(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,ki.getParametersForOperation)(e),o=(0,ki.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!o.isValid){let a="Header validation failed",c=wN.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:o.errors});if((0,ki.shouldLog)(r.validateHeaders)&&(0,ki.logErrors)(e,r.logLevel??"info",a,o.invalidValues,o.errors),(0,ki.shouldReject)(r.validateHeaders))return c}}s(vN,"handleHeadersValidation");ic.handleHeadersValidation=vN});var h_=y(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.handlePathParameterValidation=void 0;var TN=te(),Hi=Mi();function SN(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,Hi.getParametersForOperation)(e),i=(0,Hi.validateParameters)(n.filter(o=>o.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let o="Path parameters validation failed",a=TN.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,Hi.shouldLog)(r.validatePathParameters)&&(0,Hi.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,Hi.shouldReject)(r.validatePathParameters))return a}}s(SN,"handlePathParameterValidation");oc.handlePathParameterValidation=SN});var f_=y(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.handleQueryParameterValidation=void 0;var IN=te(),Fi=Mi();function PN(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,Fi.getParametersForOperation)(e),i=(0,Fi.validateParameters)(n.filter(o=>o.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let o="Query parameters validation failed",a=IN.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,Fi.shouldLog)(r.validateQueryParameters)&&(0,Fi.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,Fi.shouldReject)(r.validateQueryParameters))return a}}s(PN,"handleQueryParameterValidation");sc.handleQueryParameterValidation=PN});var m_=y(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.SchemaBasedRequestValidation=Fr.RequestValidationInboundPolicy=void 0;var AN=d_(),RN=p_(),ON=h_(),NN=f_(),xN=s(async(e,t,r)=>{let n=(0,NN.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,ON.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,RN.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,AN.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");Fr.RequestValidationInboundPolicy=xN;Fr.SchemaBasedRequestValidation=Fr.RequestValidationInboundPolicy});var y_=y(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.RequireOriginInboundPolicy=void 0;var CN=O(),LN=te(),DN=s(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new CN.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let o=e.headers.get("origin");if(!o||!i.includes(o)){let a=r.failureDetail??"Forbidden";return LN.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");ac.RequireOriginInboundPolicy=DN});var g_=y(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.SetBodyInboundPolicy=void 0;var UN=ke(),MN=s(async(e,t,r)=>new UN.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");cc.SetBodyInboundPolicy=MN});var __=y(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.SetHeadersInboundPolicy=void 0;var b_=O(),kN=ke(),HN=s(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new b_.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let o=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new b_.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.has(c.name)||u)&&o.set(c.name,c.value)}),new kN.ZuploRequest(e,{headers:o})},"SetHeadersInboundPolicy");uc.SetHeadersInboundPolicy=HN});var w_=y(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.SetHeadersOutboundPolicy=void 0;var E_=O(),FN=s(async(e,t,r,n,i)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new E_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new E_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"SetHeadersOutboundPolicy");lc.SetHeadersOutboundPolicy=FN});var T_=y(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.SetQueryParamsInboundPolicy=void 0;var v_=O(),qN=ke(),$N=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new v_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let o=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new v_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.searchParams.has(c.name)||u)&&o.searchParams.set(c.name,c.value)}),new qN.ZuploRequest(o.toString(),e)},"SetQueryParamsInboundPolicy");dc.SetQueryParamsInboundPolicy=$N});var S_=y(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.SetStatusOutboundPolicy=void 0;var jN=s(async(e,t,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(e.body,{headers:e.headers,status:n.status,statusText:n.statusText??e.statusText})},"SetStatusOutboundPolicy");pc.SetStatusOutboundPolicy=jN});var I_=y(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.SleepInboundPolicy=void 0;var VN=O(),GN=s(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),BN=s(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new VN.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await GN(r.sleepInMs),e},"SleepInboundPolicy");hc.SleepInboundPolicy=BN});var A_=y(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.SupabaseJwtInboundPolicy=void 0;var P_=O(),KN=te(),JN=ke(),zN=qt(),WN=jt(),QN=s(async(e,t,r,n)=>{(0,zN.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},o=await(0,WN.OpenIdJwtInboundPolicy)(e,t,i,n);if(o instanceof Response)return o;if(!(o instanceof JN.ZuploRequest))throw new P_.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return o;let c=e.user?.data.app_metadata;if(!c)throw new P_.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?KN.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):o},"SupabaseJwtInboundPolicy");fc.SupabaseJwtInboundPolicy=QN});var O_=y(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var YN=$t(),ZN=Kt(),R_=O(),XN=hn(),ex=qt(),tx=s(async(e,t,r,n)=>{(0,ex.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,YN.getPolicyCacheName)(n,r),o=new ZN.MemoryZoneReadThroughCache(i,t),a=await o.get(n);if(!a){let c=await rx(r,t);o.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");mc.UpstreamAzureAdServiceAuthInboundPolicy=tx;async function rx(e,t){let r=new URLSearchParams({client_id:e.activeDirectoryClientId,scope:`${e.activeDirectoryClientId}/.default`,client_secret:e.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,XN.fetchRetry)({retries:e.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${e.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let o=await n.text();t.log.error("Could not get token from Azure AD",o)}catch{}throw new R_.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new R_.RuntimeError("Response returned from Azure AD is not in the expected format.")}s(rx,"getAccessToken")});var x_=y(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var nx=$t(),ix=Kt(),ox=O(),Mp=fn(),sx=qt(),N_="https://accounts.google.com/o/oauth2/token",kp,ax=s(async(e,t,r,n)=>{(0,sx.optionValidator)(r,n).required("serviceAccountJson","string"),kp||(kp=await Mp.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},o=await(0,nx.getPolicyCacheName)(n,r),a=new ix.MemoryZoneReadThroughCache(o,t),c=await a.get(n);if(!c){let u=await(0,Mp.getTokenFromGcpServiceAccount)({serviceAccount:kp,audience:N_,payload:i}),l=await(0,Mp.exchangeGgpJwtForIdToken)(N_,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new ox.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamFirebaseAdminAuthInboundPolicy");yc.UpstreamFirebaseAdminAuthInboundPolicy=ax});var C_=y(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var cx=$t(),ux=Kt(),qn=O(),lx=_p(),Hp=fn(),dx=si(),px=qt(),hx="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",fx=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Fp,mx=s(async(e,t,r,n)=>{if((0,px.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new qn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(fx.indexOf(p)!==-1)throw new qn.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Fp||(Fp=await Hp.GcpServiceAccount.init(r.serviceAccountJson));let o=r.userId;if(!o&&!r.userIdPropertyPath){if(!e.user)throw new qn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");o=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new qn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);o=(0,dx.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!o)throw new qn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,cx.getPolicyCacheName)(n,r),c=new ux.MemoryZoneReadThroughCache(a,t),u={uid:o,claims:i},l=await(0,lx.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Hp.getTokenFromGcpServiceAccount)({serviceAccount:Fp,audience:hx,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Hp.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new qn.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");gc.UpstreamFirebaseUserAuthInboundPolicy=mx});var D_=y(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.UpstreamGcpJwtInboundPolicy=void 0;var L_=fn(),yx=qt(),qp,gx=s(async(e,t,r,n)=>{(0,yx.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),qp||(qp=await L_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,L_.getTokenFromGcpServiceAccount)({serviceAccount:qp,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");bc.UpstreamGcpJwtInboundPolicy=gx});var M_=y(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.UpstreamGcpServiceAuthInboundPolicy=void 0;var bx=$t(),_x=yu(),Ex=Kt(),wx=O(),$p=fn(),vx=qt(),U_="https://www.googleapis.com/oauth2/v4/token",jp,Tx=s(async(e,t,r,n)=>{(0,vx.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),jp||(jp=await $p.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,bx.getPolicyCacheName)(n,r),o;r.useMemoryCacheOnly?o=new _x.MemoryCache(i):o=new Ex.MemoryZoneReadThroughCache(i,t);let a=await o.get(n);if(!a){let c=await(0,$p.getTokenFromGcpServiceAccount)({serviceAccount:jp,audience:U_,payload:{target_audience:`${r.audience}`}}),{id_token:u}=await(0,$p.exchangeGgpJwtForIdToken)(U_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u)throw new wx.RuntimeError("Invalid token response from GCP");a=u,o.put(n,a,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamGcpServiceAuthInboundPolicy");_c.UpstreamGcpServiceAuthInboundPolicy=Tx});var H_=y(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.ValidateJsonSchemaInbound=void 0;var Sx=O(),k_=te(),Ix=s(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return k_.HttpProblems.badRequest(e,t,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return e;let{errors:a}=r.validator;if(!a)throw new Sx.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return k_.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");Ec.ValidateJsonSchemaInbound=Ix});var $_=y(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.MeteringInboundPolicy=void 0;var F_=Bs(),q_=gn(),wc=O(),Px=te(),Ax=He(),Rx=W(),Ox=s(async(e,t,r,n)=>{let i=Ax.SystemLogMap.getLogger(t);t.addResponseSendingFinalHook(async(d,p,f)=>{let h=F_.ContextData.get(f,"subscription");if((r.allowRequestsWithoutSubscription??!1)&&!h)return;if(!r.bucketId)if(q_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=q_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new wc.ConfigurationError(`MeteringInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:_,meteringServiceUrl:T}=Rx.Environment.instance;if(d.ok&&h&&r.meters)try{let S=await fetch(`${T}/internal/v1/metering/${r.bucketId}/subscriptions/${h.id}/quotas/consume`,{headers:{Authorization:`Bearer ${_}`,"zp-rid":f.requestId},method:"POST",body:JSON.stringify({meters:r.meters})});S.ok||(f.log.error(`MeteringInboundPolicy '${n}' -error in serviceResponse: ${S.status} - ${S.statusText}`),i.error(`MeteringInboundPolicy '${n}' -error in serviceResponse: ${S.status} - ${S.statusText}`))}catch(S){f.log.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`),i.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`,S)}});let o=F_.ContextData.get(t,"subscription"),a=r.allowRequestsWithoutSubscription??!1,c=r.allowRequestsOverQuota??!1;if(!o){if(a)return e;throw new wc.ConfigurationError("Subscription is not available for user")}if(o&&Object.keys(o.quotas).length===0)throw new wc.ConfigurationError("Quota is not set up for the user's subscription");let l=Object.keys(r.meters).filter(d=>!Object.keys(o.quotas).includes(d));if(l.length>0)throw new wc.ConfigurationError(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(o.quotas))if(o.quotas[d]<=0&&!c)return Px.HttpProblems.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return e},"MeteringInboundPolicy");vc.MeteringInboundPolicy=Ox});var G_=y(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.LoadSubscriptionInboundPolicy=void 0;var Nx=ri(),xx=Bs(),j_=gn(),Cx=O(),Vp=te(),V_=He(),Lx=W(),Dx=s(async(e,t,r,n)=>{let i=V_.SystemLogMap.getLogger(t),o=r.allowRequestsWithoutSubscription??!1,a=e.user;if(!a)return o?e:Vp.HttpProblems.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!r.bucketId)if(j_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=j_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Cx.ConfigurationError(`LoadSubscriptionInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:c,meteringServiceUrl:u}=Lx.Environment.instance,{sub:l}=a,d;try{let f=`${r.bucketId}-${l}`,h=new Nx.ZoneCache(f,{logger:V_.SystemLogMap.getLogger(t)}),g=await h.get(f);if(g)d=g;else{let _=await fetch(`${u}/internal/v1/metering/${r.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${c}`,"zp-rid":t.requestId},method:"GET"});if(!_.ok)return t.log.error(await _.text()),Vp.HttpProblems.forbidden(e,t);d=await _.json(),h.put(f,d,15).catch(T=>{throw i.error(T),T})}}catch(f){i.error(`LoadSubscriptionInboundPolicy '${n}' -error in serviceResponse`,f)}if((!d||!d.data||d.data.length===0)&&!o)return Vp.HttpProblems.unauthorized(e,t,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&o)return e;let p=d&&d.data?d.data[0]:void 0;return xx.ContextData.set(t,"subscription",p),e},"LoadSubscriptionInboundPolicy");Tc.LoadSubscriptionInboundPolicy=Dx});var B_=y(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.ServiceProviderImpl=void 0;var Ux=O(),Gp=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(t,r){if(this.services.get(t))throw new Ux.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};Sc.ServiceProviderImpl=Gp});var rE=y(m=>{"use strict";var Mx=m&&m.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Bp=m&&m.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Mx(t,e,r)},kx=m&&m.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(m,"__esModule",{value:!0});m.RateLimitInboundPolicy=m.BasicRateLimitInboundPolicy=m.PropelAuthJwtInboundPolicy=m.OpenIdJwtInboundPolicy=m.OktaJwtInboundPolicy=m.setMoesifContext=m.MoesifInboundPolicy=m.MockApiInboundPolicy=m.JWTScopeValidationInboundPolicy=m.GeoFilterInboundPolicy=m.FormDataToJsonInboundPolicy=m.FirebaseJwtInboundPolicy=m.CurityPhantomTokenInboundPolicy=m.CreditsMeteringInboundPolicy=m.CompositeInboundPolicy=m.CognitoJwtInboundPolicy=m.ClerkJwtInboundPolicy=m.ClearHeadersOutboundPolicy=m.ClearHeadersInboundPolicy=m.ChangeMethodInboundPolicy=m.CachingInboundPolicy=m.BasicAuthInboundPolicy=m.Auth0JwtInboundPolicy=m.ApiKeyInboundPolicy=m.ApiAuthKeyInboundPolicy=m.AmberfloMeteringPolicy=m.AmberfloMeteringInboundPolicy=m.AuditLogPlugin=m.AuditLogDataStaxProvider=m.HttpStatusCode=m.webSocketPipelineHandler=m.webSocketHandler=m.urlRewriteHandler=m.urlForwardHandler=m.redirectHandler=m.openApiSpecHandler=m.awsLambdaHandler=m.AwsLambdaHandlerExtensions=m.purgeGatewayCache=m.Handler=m.originalFetch=m.ConfigurationError=m.isZuploReadableEnvVariableName=m.isRestrictedEnvVariableName=m.environment=m.ContextData=m.ResponseSentEvent=m.ResponseSendingEvent=m.ZoneCache=m.MemoryZoneReadThroughCache=void 0;m.sanitizedIdentifierName=m.getRawOperationDataIdentifierName=m.getIdForRequestBodySchema=m.getIdForRefSchema=m.getIdForParameterSchema=m.SystemLogMap=m.httpStatuses=m.SYSTEM_LOGGER=m.API_KEY=m.ServiceProviderImpl=m.serialize=m.ContentTypes=m.Router=m.LookupResult=m.SystemRouteName=m.ZuploRequest=m.ProblemResponseFormatter=m.HttpProblems=m.LoadSubscriptionInboundPolicy=m.MeteringInboundPolicy=m.ValidateJsonSchemaInbound=m.UpstreamGcpServiceAuthInboundPolicy=m.UpstreamGcpJwtInboundPolicy=m.UpstreamFirebaseUserAuthInboundPolicy=m.UpstreamFirebaseAdminAuthInboundPolicy=m.UpstreamAzureAdServiceAuthInboundPolicy=m.SupabaseJwtInboundPolicy=m.StripeWebhookVerificationInboundPolicy=m.SleepInboundPolicy=m.SetStatusOutboundPolicy=m.SetQueryParamsInboundPolicy=m.SetHeadersOutboundPolicy=m.SetHeadersInboundPolicy=m.SetBodyInboundPolicy=m.RequireOriginInboundPolicy=m.SchemaBasedRequestValidation=m.RequestValidationInboundPolicy=m.RequestSizeLimitInboundPolicy=m.ReplaceStringOutboundPolicy=m.RemoveQueryParamsInboundPolicy=m.RemoveHeadersOutboundPolicy=m.RemoveHeadersInboundPolicy=m.ReadmeMetricsInboundPolicy=void 0;Ah();var Hx=Kt();Object.defineProperty(m,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return Hx.MemoryZoneReadThroughCache}});var Fx=ri();Object.defineProperty(m,"ZoneCache",{enumerable:!0,get:function(){return Fx.ZoneCache}});var K_=Pr();Object.defineProperty(m,"ResponseSendingEvent",{enumerable:!0,get:function(){return K_.ResponseSendingEvent}});Object.defineProperty(m,"ResponseSentEvent",{enumerable:!0,get:function(){return K_.ResponseSentEvent}});var qx=Bs();Object.defineProperty(m,"ContextData",{enumerable:!0,get:function(){return qx.ContextData}});var Kp=gn();Object.defineProperty(m,"environment",{enumerable:!0,get:function(){return Kp.environment}});Object.defineProperty(m,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return Kp.isRestrictedEnvVariableName}});Object.defineProperty(m,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return Kp.isZuploReadableEnvVariableName}});var $x=O();Object.defineProperty(m,"ConfigurationError",{enumerable:!0,get:function(){return $x.ConfigurationError}});var jx=Nd();Object.defineProperty(m,"originalFetch",{enumerable:!0,get:function(){return jx.originalFetch}});var J_=rg();Object.defineProperty(m,"Handler",{enumerable:!0,get:function(){return J_.Handler}});Object.defineProperty(m,"purgeGatewayCache",{enumerable:!0,get:function(){return J_.purgeGatewayCache}});var z_=_g();Object.defineProperty(m,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return z_.AwsLambdaHandlerExtensions}});Object.defineProperty(m,"awsLambdaHandler",{enumerable:!0,get:function(){return z_.awsLambdaHandler}});var Vx=wg();Object.defineProperty(m,"openApiSpecHandler",{enumerable:!0,get:function(){return Vx.openApiSpecHandler}});var Gx=vg();Object.defineProperty(m,"redirectHandler",{enumerable:!0,get:function(){return Gx.redirectHandler}});var Bx=Sg();Object.defineProperty(m,"urlForwardHandler",{enumerable:!0,get:function(){return Bx.urlForwardHandler}});var Kx=Pg();Object.defineProperty(m,"urlRewriteHandler",{enumerable:!0,get:function(){return Kx.urlRewriteHandler}});var Jx=Rg();Object.defineProperty(m,"webSocketHandler",{enumerable:!0,get:function(){return Jx.webSocketHandler}});var zx=xg();Object.defineProperty(m,"webSocketPipelineHandler",{enumerable:!0,get:function(){return zx.webSocketPipelineHandler}});var Wx=$u();Object.defineProperty(m,"HttpStatusCode",{enumerable:!0,get:function(){return Wx.HttpStatusCode}});Bp(Fg(),m);Bp(jg(),m);var Qx=Vg();Object.defineProperty(m,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return Qx.AuditLogDataStaxProvider}});var Yx=Bg();Object.defineProperty(m,"AuditLogPlugin",{enumerable:!0,get:function(){return Yx.AuditLogPlugin}});Bp(lb(),m);var W_=mb();Object.defineProperty(m,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return W_.AmberfloMeteringInboundPolicy}});Object.defineProperty(m,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return W_.AmberfloMeteringPolicy}});var Zx=Eb();Object.defineProperty(m,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return Zx.ApiAuthKeyInboundPolicy}});var Xx=vp();Object.defineProperty(m,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return Xx.ApiKeyInboundPolicy}});var eC=wb();Object.defineProperty(m,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return eC.Auth0JwtInboundPolicy}});var tC=vb();Object.defineProperty(m,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return tC.BasicAuthInboundPolicy}});var rC=Tb();Object.defineProperty(m,"CachingInboundPolicy",{enumerable:!0,get:function(){return rC.CachingInboundPolicy}});var nC=Sb();Object.defineProperty(m,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return nC.ChangeMethodInboundPolicy}});var iC=Ib();Object.defineProperty(m,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return iC.ClearHeadersInboundPolicy}});var oC=Pb();Object.defineProperty(m,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return oC.ClearHeadersOutboundPolicy}});var sC=Ab();Object.defineProperty(m,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return sC.ClerkJwtInboundPolicy}});var aC=Ob();Object.defineProperty(m,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return aC.CognitoJwtInboundPolicy}});var cC=xb();Object.defineProperty(m,"CompositeInboundPolicy",{enumerable:!0,get:function(){return cC.CompositeInboundPolicy}});var uC=Lb();Object.defineProperty(m,"CreditsMeteringInboundPolicy",{enumerable:!0,get:function(){return uC.CreditsMeteringInboundPolicy}});var lC=Db();Object.defineProperty(m,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return lC.CurityPhantomTokenInboundPolicy}});var dC=Ub();Object.defineProperty(m,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return dC.FirebaseJwtInboundPolicy}});var pC=Mb();Object.defineProperty(m,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return pC.FormDataToJsonInboundPolicy}});var hC=kb();Object.defineProperty(m,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return hC.GeoFilterInboundPolicy}});var fC=Hb();Object.defineProperty(m,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return fC.JWTScopeValidationInboundPolicy}});var mC=qb();Object.defineProperty(m,"MockApiInboundPolicy",{enumerable:!0,get:function(){return mC.MockApiInboundPolicy}});var Q_=Bb();Object.defineProperty(m,"MoesifInboundPolicy",{enumerable:!0,get:function(){return Q_.MoesifInboundPolicy}});Object.defineProperty(m,"setMoesifContext",{enumerable:!0,get:function(){return Q_.setMoesifContext}});var yC=Kb();Object.defineProperty(m,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return yC.OktaJwtInboundPolicy}});var gC=jt();Object.defineProperty(m,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return gC.OpenIdJwtInboundPolicy}});var bC=Jb();Object.defineProperty(m,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return bC.PropelAuthJwtInboundPolicy}});var Y_=e_();Object.defineProperty(m,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return Y_.RateLimitInboundPolicy}});Object.defineProperty(m,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return Y_.RateLimitInboundPolicy}});var _C=i_();Object.defineProperty(m,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return _C.ReadmeMetricsInboundPolicy}});var EC=o_();Object.defineProperty(m,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return EC.RemoveHeadersInboundPolicy}});var wC=s_();Object.defineProperty(m,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return wC.RemoveHeadersOutboundPolicy}});var vC=a_();Object.defineProperty(m,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return vC.RemoveQueryParamsInboundPolicy}});var TC=c_();Object.defineProperty(m,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return TC.ReplaceStringOutboundPolicy}});var SC=l_();Object.defineProperty(m,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return SC.RequestSizeLimitInboundPolicy}});var Z_=m_();Object.defineProperty(m,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return Z_.RequestValidationInboundPolicy}});Object.defineProperty(m,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return Z_.SchemaBasedRequestValidation}});var IC=y_();Object.defineProperty(m,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return IC.RequireOriginInboundPolicy}});var PC=g_();Object.defineProperty(m,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return PC.SetBodyInboundPolicy}});var AC=__();Object.defineProperty(m,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return AC.SetHeadersInboundPolicy}});var RC=w_();Object.defineProperty(m,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return RC.SetHeadersOutboundPolicy}});var OC=T_();Object.defineProperty(m,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return OC.SetQueryParamsInboundPolicy}});var NC=S_();Object.defineProperty(m,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return NC.SetStatusOutboundPolicy}});var xC=I_();Object.defineProperty(m,"SleepInboundPolicy",{enumerable:!0,get:function(){return xC.SleepInboundPolicy}});var CC=dp();Object.defineProperty(m,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return CC.StripeWebhookVerificationInboundPolicy}});var LC=A_();Object.defineProperty(m,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return LC.SupabaseJwtInboundPolicy}});var DC=O_();Object.defineProperty(m,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return DC.UpstreamAzureAdServiceAuthInboundPolicy}});var UC=x_();Object.defineProperty(m,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return UC.UpstreamFirebaseAdminAuthInboundPolicy}});var MC=C_();Object.defineProperty(m,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return MC.UpstreamFirebaseUserAuthInboundPolicy}});var kC=D_();Object.defineProperty(m,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return kC.UpstreamGcpJwtInboundPolicy}});var HC=M_();Object.defineProperty(m,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return HC.UpstreamGcpServiceAuthInboundPolicy}});var FC=H_();Object.defineProperty(m,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return FC.ValidateJsonSchemaInbound}});var qC=$_();Object.defineProperty(m,"MeteringInboundPolicy",{enumerable:!0,get:function(){return qC.MeteringInboundPolicy}});var $C=G_();Object.defineProperty(m,"LoadSubscriptionInboundPolicy",{enumerable:!0,get:function(){return $C.LoadSubscriptionInboundPolicy}});var jC=te();Object.defineProperty(m,"HttpProblems",{enumerable:!0,get:function(){return jC.HttpProblems}});var VC=go();Object.defineProperty(m,"ProblemResponseFormatter",{enumerable:!0,get:function(){return VC.ProblemResponseFormatter}});var GC=ke();Object.defineProperty(m,"ZuploRequest",{enumerable:!0,get:function(){return GC.ZuploRequest}});var BC=Rr();Object.defineProperty(m,"SystemRouteName",{enumerable:!0,get:function(){return BC.SystemRouteName}});var X_=Ed();Object.defineProperty(m,"LookupResult",{enumerable:!0,get:function(){return X_.LookupResult}});Object.defineProperty(m,"Router",{enumerable:!0,get:function(){return X_.Router}});var eE=xu();Object.defineProperty(m,"ContentTypes",{enumerable:!0,get:function(){return eE.ContentTypes}});Object.defineProperty(m,"serialize",{enumerable:!0,get:function(){return eE.serialize}});var KC=B_();Object.defineProperty(m,"ServiceProviderImpl",{enumerable:!0,get:function(){return KC.ServiceProviderImpl}});var tE=el();Object.defineProperty(m,"API_KEY",{enumerable:!0,get:function(){return tE.API_KEY}});Object.defineProperty(m,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return tE.SYSTEM_LOGGER}});var JC=Vu();Object.defineProperty(m,"httpStatuses",{enumerable:!0,get:function(){return kx(JC).default}});var zC=He();Object.defineProperty(m,"SystemLogMap",{enumerable:!0,get:function(){return zC.SystemLogMap}});var qi=tc();Object.defineProperty(m,"getIdForParameterSchema",{enumerable:!0,get:function(){return qi.getIdForParameterSchema}});Object.defineProperty(m,"getIdForRefSchema",{enumerable:!0,get:function(){return qi.getIdForRefSchema}});Object.defineProperty(m,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return qi.getIdForRequestBodySchema}});Object.defineProperty(m,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return qi.getRawOperationDataIdentifierName}});Object.defineProperty(m,"sanitizedIdentifierName",{enumerable:!0,get:function(){return qi.sanitizedIdentifierName}})});var nE=y($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.BaseCryptoBeta=$n.supportedDigests=void 0;$n.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var Jp=class{static{s(this,"BaseCryptoBeta")}};$n.BaseCryptoBeta=Jp});var iE=y(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.WorkerCryptoBeta=void 0;var zp=nE(),WC=O(),Wp=class extends zp.BaseCryptoBeta{static{s(this,"WorkerCryptoBeta")}async digest(t,r){if(!zp.supportedDigests.includes(t.toLowerCase()))throw new WC.RuntimeError(`Algorithm ${t} is not supported. Try using ${zp.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};Ic.WorkerCryptoBeta=Wp});var oE=y(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.BaseKeyValueStore=void 0;var Qp=class{static{s(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};Pc.BaseKeyValueStore=Qp});var aE=y(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.WorkerKeyValueStore=void 0;var sE=O(),QC=oE(),Yp=class extends QC.BaseKeyValueStore{static{s(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new sE.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new sE.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};Ac.WorkerKeyValueStore=Yp});var Dt=y(dt=>{"use strict";var YC=dt&&dt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),ZC=dt&&dt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&YC(t,e,r)};Object.defineProperty(dt,"__esModule",{value:!0});dt.KeyValueStore=dt.CryptoBeta=void 0;ZC(rE(),dt);var XC=iE();Object.defineProperty(dt,"CryptoBeta",{enumerable:!0,get:function(){return XC.WorkerCryptoBeta}});var eL=aE();Object.defineProperty(dt,"KeyValueStore",{enumerable:!0,get:function(){return eL.WorkerKeyValueStore}})});var aD={};ro(aD,{GraphQLComplexityLimitInboundPolicy:()=>FE,GraphQLDisableIntrospectionInboundPolicy:()=>$E});module.exports=no(aD);var Xn=Th(Dt());function G(e,t){if(!!!e)throw new Error(t)}s(G,"devAssert");function Ee(e){return typeof e=="object"&&e!==null}s(Ee,"isObjectLike");function Rt(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}s(Rt,"invariant");var tL=/\r\n|[\n\r]/g;function jn(e,t){let r=0,n=1;for(let i of e.body.matchAll(tL)){if(typeof i.index=="number"||Rt(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}s(jn,"getLocation");function Zp(e){return Rc(e.source,jn(e.source,e.start))}s(Zp,"printLocation");function Rc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,o=e.locationOffset.line-1,a=t.line+o,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
|
|
74
|
+
`+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new kr.StripeSignatureVerificationError(t,e,{message:"Timestamp outside the tolerance zone"});return!0}s(AR,"validateComputedSignature");function RR(e,t){return typeof e!="string"?null:e.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===t&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}s(RR,"parseHeader");function OR(e,t){if(e.length!==t.length)return!1;let r=e.length,n=0;for(let i=0;i<r;++i)n|=e.charCodeAt(i)^t.charCodeAt(i);return n===0}s(OR,"secureCompare");async function Jg(e,t){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(e)),o=new Uint8Array(i),a=new Array(o.length);for(let c=0;c<o.length;c++)a[c]=lp[o[c]];return a.join("")}s(Jg,"computeHMACSignatureAsync");xn.computeHMACSignatureAsync=Jg;var lp=new Array(256);for(let e=0;e<lp.length;e++)lp[e]=e.toString(16).padStart(2,"0")});var qt=y(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.optionValidator=void 0;var Oi=O();function NR(e,t){let r=s((o,a,c)=>{let u=e[o];if(!(c&&u===void 0)){if(u===void 0)throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new Oi.ConfigurationError(`Value of '${String(o)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=s((o,a)=>(r(o,a,!0),{optional:n,required:i}),"optional"),i=s((o,a)=>(r(o,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}s(NR,"optionValidator");ha.optionValidator=NR});var dp=y(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.StripeWebhookVerificationInboundPolicy=void 0;var xR=te(),CR=zg(),LR=qt(),DR=s(async(e,t,r,n)=>{(0,LR.optionValidator)(r,n).required("signingSecret","string").optional("tolerance","number");let i=e.headers.get("stripe-signature");try{let o=await e.clone().text();await(0,CR.constructEventAsync)(o,i,r.signingSecret)}catch(o){return t.log.error("Error validating stripe webhook",o),xR.HttpProblems.badRequest(e,t,{title:"Webhook Error",detail:o.message})}return e},"StripeWebhookVerificationInboundPolicy");fa.StripeWebhookVerificationInboundPolicy=DR});var Qg=y(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.isStripeWebhookEvent=void 0;var Wg=st();function UR(e){return e!==null&&typeof e=="object"&&"id"in e&&(0,Wg.isString)(e.id)&&"type"in e&&(0,Wg.isString)(e.type)}s(UR,"isStripeWebhookEvent");ma.isStripeWebhookEvent=UR});var Yg=y(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.MeteringPlugin=void 0;var MR=gt(),pp=class extends MR.SystemRuntimePlugin{static{s(this,"MeteringPlugin")}};ya.MeteringPlugin=pp});var Xg=y(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var Zg=O(),kR={getSubscription:async({subscriptionId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let o="Error retrieving subscription from Stripe API.";throw r.error(o,i),new Zg.RuntimeError(o)}return i},getCustomer:async({customerId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let o="Error retrieving customer from Stripe API.";throw r.error(o,i),new Zg.RuntimeError(o)}}};hp.default=kR});var nb=y(Ni=>{"use strict";var HR=Ni&&Ni.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ni,"__esModule",{value:!0});var yr=O(),fp=te(),eb=He(),tb=W(),rb=hn(),FR=HR(Xg()),qR=st();async function $R(e,t,r,n){let i=r.data?.object?.subscription;if(!i)throw new yr.RuntimeError("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");let o=r.data?.object?.client_reference_id,a=r.data?.object?.customer_email;if(!o)throw new yr.RuntimeError("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!a)throw new yr.RuntimeError("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");let c=await FR.default.getSubscription({logger:t.log,stripeSecretKey:n.stripeSecretKey,subscriptionId:i}),u=c.id,l=c.customer,d=c.items?.data.find(_=>_.object==="subscription_item");if(!d||!d.id)throw new yr.RuntimeError("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let p=d.plan;if(!p||!p.product)throw new yr.RuntimeError("Invalid Stripe API result. Expected subscription_item to have a plan.");let f=p.product,h=await jR({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:f,stripeSubscriptionId:u,stripeCustomerId:l,managerEmail:a,managerSub:o,context:t});if(!h)return fp.HttpProblems.internalServerError(e,t,{detail:"No consumer was created, skipping creation of subscription"});let g="routes.oas.json";try{await VR({context:t,stripeProductId:f,stripeSubscriptionId:u,customerKey:h,productKey:g,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:l})}catch(_){return fp.HttpProblems.internalServerError(e,t,{detail:_.message})}return fp.HttpProblems.ok(e,t)}s($R,"onCheckoutSessionCompleted");Ni.default=$R;async function jR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:o,context:a}){let{authApiJWT:c}=tb.Environment.instance,u="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l=new URL(`/v1/buckets/${e}/consumers`,u);l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[{sub:o,email:i}]},f=await(0,rb.fetchRetry)({retryDelayMs:5,retries:2,logger:eb.SystemLogMap.getLogger(a)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(p)}),h=await f.json();if(f.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,h),new yr.RuntimeError(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:t,stripeProductId:r}),d}s(jR,"createConsumer");async function VR({context:e,stripeSubscriptionId:t,stripeProductId:r,customerKey:n,productKey:i,meteringBucketId:o,meteringBucketRegion:a,customerExternalId:c}){let u={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,subscriptionExternalId:t,planExternalIds:[r],customerKey:n,productKey:i,customerExternalId:c},{authApiJWT:l,meteringServiceUrl:d}=tb.Environment.instance;if(!(0,qR.isNonEmptyString)(l))throw new yr.SystemError("No Zuplo JWT token set.");let p=await(0,rb.fetchRetry)({retryDelayMs:5,retries:2,logger:eb.SystemLogMap.getLogger(e)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"POST",body:JSON.stringify(u)});if(!p.ok){let f="Error creating metering subscription.",h;try{h=await p.json()}catch{h={status:p.status,statusText:p.statusText}}throw e.log.error(f,h),new yr.RuntimeError(f)}e.log.info("Successfully created/updated metering subscription.",u)}s(VR,"saveSubscription")});var ab=y(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var mp=O(),ib=te(),ob=He(),GR=W(),sb=hn(),BR=st();async function KR(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:o}=GR.Environment.instance;if(!(0,BR.isNonEmptyString)(i))throw new mp.SystemError("No Zuplo JWT token set.");let a=r.data.object.id,c=await(0,sb.fetchRetry)({retryDelayMs:5,retries:2,logger:ob.SystemLogMap.getLogger(t)},`${o}/internal/v1/metering/${n.meteringBucketId}/subscriptions?subscriptionExternalId=${a}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!c.ok){let p="Error querying for metering subscription.",f;try{f=await c.json()}catch{f={status:c.status,statusText:c.statusText}}throw t.log.error(p,f),new mp.RuntimeError(p)}let l=(await c.json()).data.filter(p=>p.subscriptionExternalId&&p.subscriptionExternalId===a);if(l.length===0)return ib.HttpProblems.ok(e,t,{detail:"Subscription was not found and the event was ignored by Stripe metering plugin webhook."});let d=await(0,sb.fetchRetry)({retryDelayMs:5,retries:2,logger:ob.SystemLogMap.getLogger(t)},`${o}/internal/v1/metering/${n.meteringBucketId}/subscriptions/${l[0].id}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify({status:"canceled"})});if(!d.ok){let p="Error canceling metering subscription.",f;try{f=await d.json()}catch{f={status:d.status,statusText:d.statusText}}throw t.log.error(p,f),new mp.RuntimeError(p)}return t.log.info("Successfully canceled metering subscription."),ib.HttpProblems.ok(e,t)}s(KR,"onCustomerSubscriptionDeleted");yp.default=KR});var lb=y(Cn=>{"use strict";var ub=Cn&&Cn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.StripeMeteringPlugin=void 0;var ga=gn(),ba=O(),JR=Lt(),zR=dp(),cb=te(),WR=Qt(),QR=Wr(),YR=qu(),ZR=ot(),XR=W(),e0=Qg(),t0=Yg(),r0=ub(nb()),n0=ub(ab()),gp=class extends t0.MeteringPlugin{static{s(this,"StripeMeteringPlugin")}options;constructor(t){super(),this.options=t}registerRoutes(t,r){let n=s(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(ga.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=ga.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new ba.ConfigurationError("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!d)if(ga.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=ga.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new ba.ConfigurationError("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!XR.Environment.instance.build.ACCOUNT_NAME)throw new ba.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!i0(p))throw new ba.ConfigurationError(`StripeMeteringPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,e0.isStripeWebhookEvent)(f))return cb.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"checkout.session.completed":return await(0,r0.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,n0.default)(c,u,f,{meteringBucketId:l});default:return cb.HttpProblems.ok(c,u,{detail:"Event was ignored by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=(0,QR.createInternalPolicyProcessor)({inboundPolicies:[{handler:zR.StripeWebhookVerificationInboundPolicy,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),o=new JR.Pipeline({processors:[WR.metricsProcessor,i],handler:n,gateway:r}),a=new ZR.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:YR.SystemRouteName.StripePlugin});t.addRoute(a,o.execute)}};Cn.StripeMeteringPlugin=gp;function i0(e){return e!==null&&typeof e=="string"&&["us-central1","europe-west4"].includes(e)}s(i0,"isMetricsRegion")});var mb=y(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.AmberfloMeteringInboundPolicy=Ln.AmberfloMeteringPolicy=void 0;var db=O(),o0=ve(),pb=si(),fb=new WeakMap,hb={},bp=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){fb.set(t,r)}};Ln.AmberfloMeteringPolicy=bp;async function s0(e,t,r,n){if(!r.statusCodes)throw new db.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,pb.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async o=>{if(i.includes(o.status)){let a=fb.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new db.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,pb.getValueFromRequestUser)(e.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=hb[r.apiKey];if(!f){let h=r.apiKey,g=e.headers.get("zm-test-id")??"";f=new o0.BatchDispatch("amberflo-ingest-meter",10,async _=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(_),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":g}});S.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),hb[h]=f}f.enqueue(p),t.waitUntil(f.waitUntilFlushed())}}),e}s(s0,"AmberfloMeteringInboundPolicy");Ln.AmberfloMeteringInboundPolicy=s0});var _p=y(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.sha256=void 0;async function a0(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest({name:"SHA-256"},t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}s(a0,"sha256");_a.sha256=a0});var $t=y(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.getPolicyCacheName=void 0;var c0=_p(),yb=new Map;async function u0(e,t){let r,n=yb.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,c0.sha256)(JSON.stringify({policyName:e,options:t}))}`,yb.set(e,r)),r}s(u0,"getPolicyCacheName");Ea.getPolicyCacheName=u0});var vp=y(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.ApiKeyInboundPolicy=void 0;var l0=$t(),d0=Kt(),gb=gn(),Ep=O(),p0=Dt(),bb=He(),wp=W(),h0=hn(),_b="key-metadata-cache-type";function f0(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}s(f0,"getKeyValue");async function m0(e,t,r,n){if(!r.bucketName)if(gb.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=gb.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Ep.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Ep.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let o=s(T=>i.allowUnauthenticatedRequests?e:p0.HttpProblems.unauthorized(e,t,{detail:T}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return o("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return o("Invalid Authorization Scheme");let c=f0(a,i);if(!c||c==="")return o("No key present");let u=await y0(c),l=await(0,l0.getPolicyCacheName)(n,i),d=new d0.MemoryZoneReadThroughCache(l,t),p=await d.get(u);if(p&&p.isValid===!0)return e.user=p.user,e;if(p&&!p.isValid)return p.typeId!==_b&&bb.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),o("Authorization Failed");let f={key:c},h=await(0,h0.fetchRetry)({retryDelayMs:5,retries:2,logger:bb.SystemLogMap.getLogger(t)},`${wp.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":wp.Environment.instance.deploymentName??"unknown","User-Agent":wp.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),o("Authorization Failed");if(h.status!==200){try{let T=await h.text(),S=JSON.parse(T);t.log.error("Unexpected response from key service",S)}catch{t.log.error("Invalid response from key service")}throw new Ep.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let g=await h.json(),_={isValid:!0,typeId:_b,user:{sub:g.name,data:g.metadata}};return e.user=_.user,d.put(u,_,i.cacheTtlSeconds),e}s(m0,"ApiKeyInboundPolicy");wa.ApiKeyInboundPolicy=m0;async function y0(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(y0,"hashValue")});var Eb=y(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.ApiAuthKeyInboundPolicy=void 0;var g0=vp();va.ApiAuthKeyInboundPolicy=g0.ApiKeyInboundPolicy});var jt=y(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.OpenIdJwtInboundPolicy=void 0;var Sp=(Ps(),no(Is)),Ip=O(),b0=te(),Tp={},_0=s(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new Ip.ConfigurationError("Invalid State - jwkUrl not set");Tp[t.jwkUrl]||(Tp[t.jwkUrl]=(0,Sp.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,Sp.jwtVerify)(e,Tp[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),E0=s(async(e,t)=>{let r;if(t.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof t.secret=="string"){let o=new TextEncoder().encode(t.secret);r=new Uint8Array(o)}else r=t.secret;let{payload:n}=await(0,Sp.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),w0=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),o="bearer ",a=s(f=>b0.HttpProblems.unauthorized(e,t,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Ip.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Ip.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?_0:E0,l=await s(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(o)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(o.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let g=new URL(e.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${g.pathname} `,h):t.log.warn(`Invalid token on: ${e.method} ${g.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?e:l;let d=r.subPropertyName??"sub",p=l[d];return p?(e.user={sub:p,data:l},e):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");Ta.OpenIdJwtInboundPolicy=w0});var wb=y(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.Auth0JwtInboundPolicy=void 0;var v0=jt(),T0=s(async(e,t,r,n)=>(0,v0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");Sa.Auth0JwtInboundPolicy=T0});var vb=y(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.BasicAuthInboundPolicy=void 0;var S0=te(),I0=s(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",o=s(l=>S0.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await s(async()=>{if(!n)return await o("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await o("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await o("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await o("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),g=r.accounts.find(_=>_.username===f&&_.password===h);return g||await o("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?e:c;let u=c.username;return e.user={sub:u,data:c.data},e},"BasicAuthInboundPolicy");Ia.BasicAuthInboundPolicy=I0});var Tb=y(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.CachingInboundPolicy=void 0;var P0=$t(),A0=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function R0(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}s(R0,"digestMessage");var O0=s(async(e,t)=>{let r=[...t.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...t.headers??[]],n=[];for(let[d,p]of e.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await R0(JSON.stringify(n)),o=new URL(e.url),a=new URLSearchParams(o.searchParams);a.set("_z-hdr-dgst",i);let c=t.cacheHttpMethods?.includes(e.method.toUpperCase())&&e.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",e.method);let u=`${o.origin}${o.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function N0(e,t,r,n){let i=await(0,P0.getPolicyCacheName)(n,r),o=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await O0(e,r),u=await o.match(c);return u||(t.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(e.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);A0.forEach(g=>h.headers.delete(g)),h.headers.set("cache-control",`s-maxage=${f}`),t.waitUntil(o.put(c,h))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}s(N0,"CachingInboundPolicy");Pa.CachingInboundPolicy=N0});var Sb=y(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.ChangeMethodInboundPolicy=void 0;var x0=O(),C0=ke(),L0=s(async(e,t,r,n)=>{if(!r.method)throw new x0.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new C0.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");Aa.ChangeMethodInboundPolicy=L0});var Ib=y(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.ClearHeadersInboundPolicy=void 0;var D0=ke(),U0=s(async(e,t,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=e.headers.get(a);c&&i.set(a,c)}),new D0.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");Ra.ClearHeadersInboundPolicy=U0});var Pb=y(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.ClearHeadersOutboundPolicy=void 0;var M0=s(async(e,t,r,n)=>{let i=[...n.exclude??[]],o=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&o.set(c,u)}),new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");Oa.ClearHeadersOutboundPolicy=M0});var Ab=y(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.ClerkJwtInboundPolicy=void 0;var k0=jt(),H0=s(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),o=new URL(i);return o.pathname="/.well-known/jwks.json",(0,k0.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:o.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");Na.ClerkJwtInboundPolicy=H0});var Ob=y(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.CognitoJwtInboundPolicy=void 0;var Rb=O(),F0=jt(),q0=s(async(e,t,r,n)=>{if(!r.userPoolId)throw new Rb.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new Rb.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,F0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");xa.CognitoJwtInboundPolicy=q0});var xb=y(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.CompositeInboundPolicy=void 0;var $0=O(),j0=Ir(),Nb=Wr(),V0=s(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new $0.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=j0.Gateway.instance,o=(0,Nb.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Nb.toStackedInboundHandler)(o)(e,t)},"CompositeInboundPolicy");Ca.CompositeInboundPolicy=V0});var Lb=y(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.CreditsMeteringInboundPolicy=void 0;var xi=te(),Cb=W(),G0=s(async(e,t,r)=>{let n=e.user;if(!n)return xi.HttpProblems.unauthorized(e,t,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:i}=n;if(!r.bucketId)return xi.HttpProblems.unauthorized(e,t,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let o=r.bucketId,a=await B0(o,i,t);if(!a)return xi.HttpProblems.unauthorized(e,t,{title:"No valid, active subscription found"});if(!a.quotas)return xi.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});for(let c of Object.keys(a.quotas))if(a.quotas[c]<=0)return xi.HttpProblems.forbidden(e,t,{title:"Insufficient credits"});return t.custom.subscription=a,t.addResponseSendingFinalHook(async()=>{let c=t.custom.meters,u={};for(let l of Object.keys(c))u[l]=c[l];await K0(o,a.id,u,t)}),e},"CreditsMeteringInboundPolicy");La.CreditsMeteringInboundPolicy=G0;async function B0(e,t,r){let{authApiJWT:n,meteringServiceUrl:i}=Cb.Environment.instance,o=new URL(`${i}/internal/v1/metering/${e}/subscriptions`);o.search=new URLSearchParams({customerKey:t,status:"active"}).toString();let a=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${n}`,"zp-rid":r.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let c=await a.json();if(c.data.length!==0)return c.data.length>1&&r.log.warn(`Found more than one active subscription for customer ${t} -- using the first one.`),c.data[0]}s(B0,"getSubscription");async function K0(e,t,r,n){let{authApiJWT:i,meteringServiceUrl:o}=Cb.Environment.instance,a=new URL(`${o}/internal/v1/metering/${e}/subscriptions/${t}/quotas/consume`),c=await fetch(a,{method:"POST",body:JSON.stringify({meters:r}),headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId}});c.ok||n.log.error(`Error consuming subscription quotas for credits metering ': ${c.status} - ${await c.text()}`)}s(K0,"consumeSubscription")});var Db=y(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.CurityPhantomTokenInboundPolicy=void 0;var J0=$t(),z0=Kt(),Da=te(),W0=s(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return Da.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let o=Q0(i);if(!o)return Da.HttpProblems.unauthorized(e,t,{detail:"Failed to parse token from Authorization header"});let a=await(0,J0.getPolicyCacheName)(n,r),c=new z0.MemoryZoneReadThroughCache(a,t),u=await c.get(o);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+o+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(o,u,r.cacheDurationSeconds??600);else return l.status>=500?(t.log.error(`Error introspecting token - ${l.status}: '${d}'`),Da.HttpProblems.internalServerError(e,t,{detail:"Problem encountered authorizing the HTTP request"})):Da.HttpProblems.unauthorized(e,t)}return e.headers.set("Authorization",`Bearer ${u}`),e},"CurityPhantomTokenInboundPolicy");Ua.CurityPhantomTokenInboundPolicy=W0;function Q0(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}s(Q0,"getToken")});var Ub=y(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.FirebaseJwtInboundPolicy=void 0;var Y0=qt(),Z0=jt(),X0=s(async(e,t,r,n)=>((0,Y0.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,Z0.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");Ma.FirebaseJwtInboundPolicy=X0});var Mb=y(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.FormDataToJsonInboundPolicy=void 0;var eO=ke(),tO=s(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",o=e.headers.get("content-type")?.toLowerCase();if(!o||![i,n].includes(o))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):e;let a=await e.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(e.headers);return u.set("content-type","application/json"),u.delete("content-length"),new eO.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");ka.FormDataToJsonInboundPolicy=tO});var kb=y(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.GeoFilterInboundPolicy=void 0;var rO=O(),nO=te(),Dn="__unknown__",iO=s(async(e,t,r,n)=>{let i={allow:{countries:Mn(r.allow?.countries,"allow.countries",n),regionCodes:Mn(r.allow?.regionCodes,"allow.regionCode",n),asns:Mn(r.allow?.asns,"allow.asOrganization",n)},block:{countries:Mn(r.block?.countries,"block.countries",n),regionCodes:Mn(r.block?.regionCodes,"block.regionCode",n),asns:Mn(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},o=t.incomingRequestProperties.country?.toLowerCase()??Dn,a=t.incomingRequestProperties.regionCode?.toLowerCase()??Dn,c=t.incomingRequestProperties.asn?.toString()??Dn,u=i.ignoreUnknown&&o===Dn,l=i.ignoreUnknown&&a===Dn,d=i.ignoreUnknown&&c===Dn,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(o)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Un(e,t,n,o,a,c);let g=i.block.countries,_=i.block.regionCodes,T=i.block.asns;return g.length>0&&g.includes(o)&&!u||_.length>0&&_.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Un(e,t,n,o,a,c):e},"GeoFilterInboundPolicy");Ha.GeoFilterInboundPolicy=iO;function Un(e,t,r,n,i,o){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${o}')`),nO.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:o}})}s(Un,"blockedResponse");function Mn(e,t,r){if(typeof e=="string")return e.split(",").map(n=>n.trim().toLowerCase());if(typeof e>"u")return[];if(Array.isArray(e))return e.map(n=>n.trim().toLowerCase());throw new rO.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}s(Mn,"toLowerStringArray")});var Hb=y(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.JWTScopeValidationInboundPolicy=void 0;var oO=s(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!s((o,a)=>a.every(c=>o.includes(c)),"scopeChecker")(n,r.scopes)){let o={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(o),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");Fa.JWTScopeValidationInboundPolicy=oO});var qb=y(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.MockApiInboundPolicy=void 0;var sO=te(),aO=s(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return Pp(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let o=Object.keys(i),a=[];if(o.length===0)return Pp(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(o.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return Fb(a[c])}else return a.length>0?Fb(a[0]):Pp(n,e,t,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");qa.MockApiInboundPolicy=aO;function Fb(e){let t=JSON.stringify(e.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",e.contentName),e.responseName){case"1XX":return new Response(t,{status:100,headers:r});case"2XX":return new Response(t,{status:200,headers:r});case"3XX":return new Response(t,{status:300,headers:r});case"4XX":return new Response(t,{status:400,headers:r});case"5XX":case"default":return new Response(t,{status:500,headers:r});default:return new Response(t,{status:Number(e.responseName),headers:r})}}s(Fb,"generateResponse");var Pp=s((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return sO.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var Bb=y(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.MoesifInboundPolicy=kn.setMoesifContext=void 0;var cO=O(),uO=ve(),lO="Incoming",dO={logRequestBody:!0,logResponseBody:!0};function $b(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}s($b,"headersToObject");function jb(){return new Date().toISOString()}s(jb,"timestamp");var Ap=new WeakMap,pO={};function hO(e,t){let r=Ap.get(e);r||(r=pO);let n=Object.assign({...r},t);Ap.set(e,n)}s(hO,"setMoesifContext");kn.setMoesifContext=hO;async function Vb(e,t){let r=e.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await e.clone().json()}catch(i){t.log.error(i)}let n=await e.clone().text();return t.log.debug({textBody:n}),n}s(Vb,"readBody");var fO={},Rp;function Gb(){if(!Rp)throw new cO.RuntimeError("Invalid State - no _lastLogger");return Rp}s(Gb,"getLastLogger");function mO(e){let t=fO[e];return t||(t=new uO.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);Gb().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":e},body:n});i.ok||Gb().error({status:i.status,body:await i.text()})})),t}s(mO,"getDispatcher");async function yO(e,t,r,n){Rp=t.log;let i=jb(),o=Object.assign(dO,r);if(!o.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=o.logRequestBody?await Vb(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=mO(o.applicationId),d=e.headers.get("true-client-ip"),p=Ap.get(t)??{},f={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:$b(e.headers)},h=o.logResponseBody?await Vb(c,t):void 0,g={time:jb(),status:c.status,headers:$b(c.headers),body:h},_={request:f,response:g,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:lO};l.enqueue(_),t.waitUntil(l.waitUntilFlushed())}),e}s(yO,"MoesifInboundPolicy");kn.MoesifInboundPolicy=yO});var Kb=y($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.OktaJwtInboundPolicy=void 0;var gO=jt(),bO=s(async(e,t,r,n)=>(0,gO.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");$a.OktaJwtInboundPolicy=bO});var Jb=y(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.PropelAuthJwtInboundPolicy=void 0;var _O=(Ps(),no(Is)),EO=jt(),Op,wO=s(async(e,t,r,n)=>{if(!Op)try{Op=await(0,_O.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,EO.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:Op,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");ja.PropelAuthJwtInboundPolicy=wO});var zb=y(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.throwIfStateNotObject=V.throwIfStateNotNumber=V.throwIfStateNotString=V.throwIfStateUndefinedOrNull=V.throwIfStateUndefined=V.throwIfOptionNotObject=V.throwIfOptionNotNumber=V.throwIfOptionNotString=V.throwIfOptionUndefinedOrNull=V.throwIfOptionUndefined=V.OptionTypeError=V.OptionUndefinedError=V.throwIfNotNumber=V.throwIfNotString=V.throwIfUndefinedOrNull=V.throwIfUndefined=V.ArgumentTypeError=V.ArgumentUndefinedError=V.ValidationError=void 0;var je=st(),et=class extends Error{static{s(this,"ValidationError")}constructor(t){super(t)}};V.ValidationError=et;var Ci=class extends et{static{s(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};V.ArgumentUndefinedError=Ci;var Li=class extends et{static{s(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};V.ArgumentTypeError=Li;function vO(e,t){if((0,je.isUndefined)(e))throw new Ci(t)}s(vO,"throwIfUndefined");V.throwIfUndefined=vO;function Np(e,t){if((0,je.isUndefinedOrNull)(e))throw new Ci(t)}s(Np,"throwIfUndefinedOrNull");V.throwIfUndefinedOrNull=Np;function TO(e,t){if(Np(e,t),!(0,je.isString)(e))throw new Li(t,"string")}s(TO,"throwIfNotString");V.throwIfNotString=TO;function SO(e,t){if(Np(e,t),!(0,je.isNumber)(e))throw new Li(t,"number")}s(SO,"throwIfNotNumber");V.throwIfNotNumber=SO;var Di=class extends et{static{s(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};V.OptionUndefinedError=Di;var Hn=class extends et{static{s(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};V.OptionTypeError=Hn;function IO(e,t,r,n){if((0,je.isUndefined)(n))throw new Di(e,t,r)}s(IO,"throwIfOptionUndefined");V.throwIfOptionUndefined=IO;function Va(e,t,r,n){if((0,je.isUndefinedOrNull)(n))throw new Di(e,t,r)}s(Va,"throwIfOptionUndefinedOrNull");V.throwIfOptionUndefinedOrNull=Va;function PO(e,t,r,n){if(Va(e,t,r,n),!(0,je.isString)(n))throw new Hn(e,t,r,"string")}s(PO,"throwIfOptionNotString");V.throwIfOptionNotString=PO;function AO(e,t,r,n){if(Va(e,t,r,n),!(0,je.isNumber)(n))throw new Hn(e,t,r,"number")}s(AO,"throwIfOptionNotNumber");V.throwIfOptionNotNumber=AO;function RO(e,t,r,n){if(Va(e,t,r,n),!(0,je.isObject)(n))throw new Hn(e,t,r,"object")}s(RO,"throwIfOptionNotObject");V.throwIfOptionNotObject=RO;function OO(e,t){if((0,je.isUndefined)(e))throw new et(t)}s(OO,"throwIfStateUndefined");V.throwIfStateUndefined=OO;function Ga(e,t){if((0,je.isUndefinedOrNull)(e))throw new et(t)}s(Ga,"throwIfStateUndefinedOrNull");V.throwIfStateUndefinedOrNull=Ga;function NO(e,t){if(Ga(e,t),!(0,je.isString)(e))throw new et(t);return!0}s(NO,"throwIfStateNotString");V.throwIfStateNotString=NO;function xO(e,t){if(Ga(e,t),!(0,je.isNumber)(e))throw new et(t);return!0}s(xO,"throwIfStateNotNumber");V.throwIfStateNotNumber=xO;function CO(e,t){if(Ga(e,t),!(0,je.isObject)(e))throw new et(t);return!0}s(CO,"throwIfStateNotObject");V.throwIfStateNotObject=CO});var Wb=y(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.InMemoryRedisClient=Fn.StandardRedisClient=void 0;var xp=O(),Ba=zb(),Cp=class e{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(t,r,n,i){this.redisClientUrl=t,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(t,r,n,i){return(0,Ba.throwIfNotString)(t,"redisClientUrl"),(0,Ba.throwIfNotString)(r,"clientAuthToken"),e.instance||(e.instance=new e(t,r,n,i)),e.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:t,body:r,method:n,requestId:i}){(0,Ba.throwIfNotString)(t,"url");let o=await fetch(`${this.redisClientUrl}${t}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=o.headers.get("Content-Type")?.includes("application/json")?await o.json():await o.text();if(o.ok)return a;throw o.status===401?new xp.SystemError("Redis client failed with 401: Unauthorized"):new xp.SystemError(`Redis client failed with (${o.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Fn.StandardRedisClient=Cp;var Lp=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,Ba.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:o,key:a}=JSON.parse(r),c=Date.now()+o*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new xp.SystemError("The in-memory redis client only supports /rate-limit calls")}};Fn.InMemoryRedisClient=Lp});var e_=y(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.RateLimitInboundPolicy=void 0;var LO=Sr(),DO=$t(),UO=ri(),At=O(),MO=te(),Qb=He(),Ui=W(),Yb=Wb(),Zb=st(),Ka=(0,LO.debug)("zuplo:policies:RateLimitInboundPolicy"),kO="strict",HO=s(e=>{let t=e.headers.get("cf-connecting-ip")??e.headers.get("true-client-ip");if(t)return t;let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),FO=s(async e=>({key:`ip-${HO(e)}`}),"getIP"),qO=s(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),$O=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Ja;function jO(e,t){let r;if(Ja)return Ja;if(Ui.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new Yb.InMemoryRedisClient,Ja=r,r;let{authApiJWT:n,redisURL:i}=Ui.Environment.instance;if(!(0,Zb.isString)(i))throw new At.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,Zb.isString)(n))throw new At.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=Yb.StandardRedisClient.initialize(i,n,Ui.Environment.instance.deploymentName??"unknown",Ui.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new At.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Ja=r,r}s(jO,"getRedisClient");async function Xb(e,t,r,n,i){let o=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:i})}s(Xb,"getCountAndUpdateExpiry");function VO(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=e.identifier.module[e.identifier.export],!r||typeof r!="function")throw new At.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,o,a)=>{let c=await r(i,o,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw o.log.error(u),new At.RuntimeError(u)}return c},"outerFunction")}s(VO,"wrapUserFunction");var GO="Retry-After",BO=s(async(e,t,r,n)=>{let i=Date.now(),o=Qb.SystemLogMap.getLogger(t),a=s((u,l)=>{if(r.throwOnFailure)throw new At.SystemError(u,{cause:l});o.error(u,l)},"throwOrLog"),c=s((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[GO]=l.toString()),MO.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:VO(r,n),user:qO,ip:FO,all:$O}[r.rateLimitBy],d=await l(e,t,n),p=d.key,f=d.requestsAllowed??r.requestsAllowed,h=d.timeWindowMinutes??r.timeWindowMinutes,g=r.headerMode??"retry-after",_=jO(n,o),S=`bucket/${Ui.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??kO)==="async"){let L=await(0,DO.getPolicyCacheName)(n,r),ne=new UO.ZoneCache(L,{logger:Qb.SystemLogMap.getLogger(t)}),ie=Xb(S,h,_,o,t.requestId),me=await ne.get(S);if(me!==void 0&&me<=Date.now()){Ka(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let Be=Math.round((me-Date.now())/1e3);return c(g,Be)}return t.addEventListener("responseSending",Be=>{try{let w=Be,k=w.mutableResponse;w.mutableResponse=(async()=>{let Ce=await ie;if(Ce.count>f){let uu=Date.now()+Ce.ttlSeconds*1e3,jE=ne.put(S,uu,Ce.ttlSeconds).catch(wh=>{throw o.error(new At.SystemError("Error caching rate limit result.",{cause:wh})),wh});return t.waitUntil(jE),Ka(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(g,Ce.ttlSeconds)}return k})()}catch(w){o.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,w)}}),e}let K=await Xb(S,h,_,o,t.requestId);return K.count>f?(Ka(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(g,K.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;Ka(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");za.RateLimitInboundPolicy=BO});var i_=y(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.ReadmeMetricsInboundPolicy=void 0;var KO=ve(),Dp=W(),t_=si(),Up;function r_(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}s(r_,"headersToNameValuePairs");function JO(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}s(JO,"queryToNameValueParis");function zO(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}s(zO,"parseIntOrUndefined");var n_={};async function WO(e,t,r,n){let i=new Date,o=Date.now();return Up||(Up={name:"zuplo",version:Dp.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Dp.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,t_.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,t_.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Dp.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:Up,entries:[{startedDateTime:i.toISOString(),time:Date.now()-o,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:r_(e.headers),queryString:JO(e.query)},response:{status:a.status,statusText:a.statusText,headers:r_(a.headers),content:{size:zO(e.headers.get("content-length"))}}}]}}},d=n_[r.apiKey];if(!d){let p=r.apiKey;d=new KO.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",g=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});g.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${g.status}: '${await g.text()}'`)}catch(h){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),n_[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}s(WO,"ReadmeMetricsInboundPolicy");Wa.ReadmeMetricsInboundPolicy=WO});var o_=y(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.RemoveHeadersInboundPolicy=void 0;var QO=O(),YO=ke(),ZO=s(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new QO.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let o=new Headers(e.headers);return i.forEach(c=>{o.delete(c)}),new YO.ZuploRequest(e,{headers:o})},"RemoveHeadersInboundPolicy");Qa.RemoveHeadersInboundPolicy=ZO});var s_=y(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.RemoveHeadersOutboundPolicy=void 0;var XO=O(),eN=s(async(e,t,r,n,i)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new XO.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return o.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Ya.RemoveHeadersOutboundPolicy=eN});var a_=y(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.RemoveQueryParamsInboundPolicy=void 0;var tN=O(),rN=ke(),nN=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new tN.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let o=new URL(e.url);return i.forEach(c=>{o.searchParams.delete(c)}),new rN.ZuploRequest(o.toString(),e)},"RemoveQueryParamsInboundPolicy");Za.RemoveQueryParamsInboundPolicy=nN});var c_=y(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.ReplaceStringOutboundPolicy=void 0;var iN=s(async(e,t,r,n)=>{let i=await e.text(),o=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(o,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Xa.ReplaceStringOutboundPolicy=iN});var l_=y(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.RequestSizeLimitInboundPolicy=void 0;var u_=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),oN=s(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),o=i!==null?parseInt(i):void 0;return o&&!isNaN(o)&&o>r.maxSizeInBytes?u_():o&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?u_():e},"RequestSizeLimitInboundPolicy");ec.RequestSizeLimitInboundPolicy=oN});var tc=y(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function sN(e,t,r){return`_${Hr(e+"_"+t+"_"+r)}`}s(sN,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=sN;function aN(e,t,r,n){return`_${Hr(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}s(aN,"getIdForParameterSchema");tt.getIdForParameterSchema=aN;function cN(e,t,r){return`_${Hr(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${Hr(r.toLowerCase())}`}s(cN,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=cN;function uN(e,t){return`_${Hr(e)}__${Hr(t)}`}s(uN,"getIdForRefSchema");tt.getIdForRefSchema=uN;function Hr(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?t.push(e.charAt(r)):t.push("_")}return t.join("")}s(Hr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Hr});var Mi=y(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.getErrorsFromValidator=Le.shouldReject=Le.shouldLog=Le.logErrors=Le.validateParameters=Le.getParametersForOperation=void 0;var lN=Ir(),dN=tc(),pN=s(e=>{let t=e.route.raw();return t.parameters?t.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");Le.getParametersForOperation=pN;var hN=s((e,t,r,n,i)=>{let o=[],a=!0,c=[];return e.forEach(u=>{let l=u.required||i==="path";if(l&&!t[u.name])a=!1,o.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!t[u.name])){let d=(0,dN.getIdForParameterSchema)(r,n,i,u.name),p=lN.Gateway.instance.schemaValidator[d],f=p(t[u.name]),h=(0,Le.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),o.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:o}},"validateParameters");Le.validateParameters=hN;var fN=s((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");Le.logErrors=fN;var mN=s(e=>e==="log-only"||e==="reject-and-log","shouldLog");Le.shouldLog=mN;var yN=s(e=>e==="reject-only"||e==="reject-and-log","shouldReject");Le.shouldReject=yN;var gN=s(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");Le.getErrorsFromValidator=gN});var d_=y(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.handleBodyValidation=void 0;var bN=Ir(),rc=te(),_N=tc(),Je=Mi();async function EN(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(h){let g=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,_=rc.HttpProblems.badRequest(t,e,{detail:`${g}, see errors property for more details`,errors:`${h}`});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",g,[n],h),(0,Je.shouldReject)(r.validateBody))return _}if(!t.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,g=rc.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?g:void 0}let i=t.headers.get("Content-Type"),o=i.indexOf(";");o>-1&&(i=i.substring(0,o));let a=(0,_N.getIdForRequestBodySchema)(e.route.path,t.method,i),c=bN.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,g=rc.HttpProblems.badRequest(t,e,{detail:h});return(0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",h,[n],[h]),(0,Je.shouldReject)(r.validateBody)?g:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Je.getErrorsFromValidator)(l),f=rc.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,Je.shouldLog)(r.validateBody)&&(0,Je.logErrors)(e,r.logLevel??"info",d,[n],p),(0,Je.shouldReject)(r.validateBody))return f}s(EN,"handleBodyValidation");nc.handleBodyValidation=EN});var p_=y(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.handleHeadersValidation=void 0;var wN=te(),ki=Mi();function vN(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,ki.getParametersForOperation)(e),o=(0,ki.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!o.isValid){let a="Header validation failed",c=wN.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:o.errors});if((0,ki.shouldLog)(r.validateHeaders)&&(0,ki.logErrors)(e,r.logLevel??"info",a,o.invalidValues,o.errors),(0,ki.shouldReject)(r.validateHeaders))return c}}s(vN,"handleHeadersValidation");ic.handleHeadersValidation=vN});var h_=y(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.handlePathParameterValidation=void 0;var TN=te(),Hi=Mi();function SN(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,Hi.getParametersForOperation)(e),i=(0,Hi.validateParameters)(n.filter(o=>o.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let o="Path parameters validation failed",a=TN.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,Hi.shouldLog)(r.validatePathParameters)&&(0,Hi.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,Hi.shouldReject)(r.validatePathParameters))return a}}s(SN,"handlePathParameterValidation");oc.handlePathParameterValidation=SN});var f_=y(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.handleQueryParameterValidation=void 0;var IN=te(),Fi=Mi();function PN(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,Fi.getParametersForOperation)(e),i=(0,Fi.validateParameters)(n.filter(o=>o.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let o="Query parameters validation failed",a=IN.HttpProblems.badRequest(t,e,{detail:`${o}, see errors property for more details`,errors:i.errors});if((0,Fi.shouldLog)(r.validateQueryParameters)&&(0,Fi.logErrors)(e,r.logLevel??"info",o,i.invalidValues,i.errors),(0,Fi.shouldReject)(r.validateQueryParameters))return a}}s(PN,"handleQueryParameterValidation");sc.handleQueryParameterValidation=PN});var m_=y(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.SchemaBasedRequestValidation=Fr.RequestValidationInboundPolicy=void 0;var AN=d_(),RN=p_(),ON=h_(),NN=f_(),xN=s(async(e,t,r)=>{let n=(0,NN.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,ON.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,RN.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,AN.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");Fr.RequestValidationInboundPolicy=xN;Fr.SchemaBasedRequestValidation=Fr.RequestValidationInboundPolicy});var y_=y(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.RequireOriginInboundPolicy=void 0;var CN=O(),LN=te(),DN=s(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new CN.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let o=e.headers.get("origin");if(!o||!i.includes(o)){let a=r.failureDetail??"Forbidden";return LN.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");ac.RequireOriginInboundPolicy=DN});var g_=y(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.SetBodyInboundPolicy=void 0;var UN=ke(),MN=s(async(e,t,r)=>new UN.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");cc.SetBodyInboundPolicy=MN});var __=y(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.SetHeadersInboundPolicy=void 0;var b_=O(),kN=ke(),HN=s(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new b_.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let o=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new b_.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.has(c.name)||u)&&o.set(c.name,c.value)}),new kN.ZuploRequest(e,{headers:o})},"SetHeadersInboundPolicy");uc.SetHeadersInboundPolicy=HN});var w_=y(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.SetHeadersOutboundPolicy=void 0;var E_=O(),FN=s(async(e,t,r,n,i)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new E_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new E_.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"SetHeadersOutboundPolicy");lc.SetHeadersOutboundPolicy=FN});var T_=y(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.SetQueryParamsInboundPolicy=void 0;var v_=O(),qN=ke(),$N=s(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new v_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let o=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new v_.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!o.searchParams.has(c.name)||u)&&o.searchParams.set(c.name,c.value)}),new qN.ZuploRequest(o.toString(),e)},"SetQueryParamsInboundPolicy");dc.SetQueryParamsInboundPolicy=$N});var S_=y(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.SetStatusOutboundPolicy=void 0;var jN=s(async(e,t,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(e.body,{headers:e.headers,status:n.status,statusText:n.statusText??e.statusText})},"SetStatusOutboundPolicy");pc.SetStatusOutboundPolicy=jN});var I_=y(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.SleepInboundPolicy=void 0;var VN=O(),GN=s(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),BN=s(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new VN.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await GN(r.sleepInMs),e},"SleepInboundPolicy");hc.SleepInboundPolicy=BN});var A_=y(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.SupabaseJwtInboundPolicy=void 0;var P_=O(),KN=te(),JN=ke(),zN=qt(),WN=jt(),QN=s(async(e,t,r,n)=>{(0,zN.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},o=await(0,WN.OpenIdJwtInboundPolicy)(e,t,i,n);if(o instanceof Response)return o;if(!(o instanceof JN.ZuploRequest))throw new P_.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return o;let c=e.user?.data.app_metadata;if(!c)throw new P_.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?KN.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):o},"SupabaseJwtInboundPolicy");fc.SupabaseJwtInboundPolicy=QN});var O_=y(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var YN=$t(),ZN=Kt(),R_=O(),XN=hn(),ex=qt(),tx=s(async(e,t,r,n)=>{(0,ex.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,YN.getPolicyCacheName)(n,r),o=new ZN.MemoryZoneReadThroughCache(i,t),a=await o.get(n);if(!a){let c=await rx(r,t);o.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");mc.UpstreamAzureAdServiceAuthInboundPolicy=tx;async function rx(e,t){let r=new URLSearchParams({client_id:e.activeDirectoryClientId,scope:`${e.activeDirectoryClientId}/.default`,client_secret:e.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,XN.fetchRetry)({retries:e.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${e.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let o=await n.text();t.log.error("Could not get token from Azure AD",o)}catch{}throw new R_.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new R_.RuntimeError("Response returned from Azure AD is not in the expected format.")}s(rx,"getAccessToken")});var x_=y(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var nx=$t(),ix=Kt(),ox=O(),Mp=fn(),sx=qt(),N_="https://accounts.google.com/o/oauth2/token",kp,ax=s(async(e,t,r,n)=>{(0,sx.optionValidator)(r,n).required("serviceAccountJson","string"),kp||(kp=await Mp.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},o=await(0,nx.getPolicyCacheName)(n,r),a=new ix.MemoryZoneReadThroughCache(o,t),c=await a.get(n);if(!c){let u=await(0,Mp.getTokenFromGcpServiceAccount)({serviceAccount:kp,audience:N_,payload:i}),l=await(0,Mp.exchangeGgpJwtForIdToken)(N_,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new ox.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamFirebaseAdminAuthInboundPolicy");yc.UpstreamFirebaseAdminAuthInboundPolicy=ax});var C_=y(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var cx=$t(),ux=Kt(),qn=O(),lx=_p(),Hp=fn(),dx=si(),px=qt(),hx="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",fx=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Fp,mx=s(async(e,t,r,n)=>{if((0,px.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new qn.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(fx.indexOf(p)!==-1)throw new qn.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Fp||(Fp=await Hp.GcpServiceAccount.init(r.serviceAccountJson));let o=r.userId;if(!o&&!r.userIdPropertyPath){if(!e.user)throw new qn.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");o=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new qn.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);o=(0,dx.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!o)throw new qn.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,cx.getPolicyCacheName)(n,r),c=new ux.MemoryZoneReadThroughCache(a,t),u={uid:o,claims:i},l=await(0,lx.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Hp.getTokenFromGcpServiceAccount)({serviceAccount:Fp,audience:hx,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Hp.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new qn.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");gc.UpstreamFirebaseUserAuthInboundPolicy=mx});var D_=y(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.UpstreamGcpJwtInboundPolicy=void 0;var L_=fn(),yx=qt(),qp,gx=s(async(e,t,r,n)=>{(0,yx.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),qp||(qp=await L_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,L_.getTokenFromGcpServiceAccount)({serviceAccount:qp,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");bc.UpstreamGcpJwtInboundPolicy=gx});var M_=y(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.UpstreamGcpServiceAuthInboundPolicy=void 0;var bx=$t(),_x=yu(),Ex=Kt(),wx=O(),$p=fn(),vx=qt(),U_="https://www.googleapis.com/oauth2/v4/token",jp,Tx=s(async(e,t,r,n)=>{(0,vx.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),jp||(jp=await $p.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,bx.getPolicyCacheName)(n,r),o;r.useMemoryCacheOnly?o=new _x.MemoryCache(i):o=new Ex.MemoryZoneReadThroughCache(i,t);let a=await o.get(n);if(!a){let c=await(0,$p.getTokenFromGcpServiceAccount)({serviceAccount:jp,audience:U_,payload:{target_audience:`${r.audience}`}}),{id_token:u}=await(0,$p.exchangeGgpJwtForIdToken)(U_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u)throw new wx.RuntimeError("Invalid token response from GCP");a=u,o.put(n,a,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamGcpServiceAuthInboundPolicy");_c.UpstreamGcpServiceAuthInboundPolicy=Tx});var H_=y(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.ValidateJsonSchemaInbound=void 0;var Sx=O(),k_=te(),Ix=s(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return k_.HttpProblems.badRequest(e,t,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return e;let{errors:a}=r.validator;if(!a)throw new Sx.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return k_.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");Ec.ValidateJsonSchemaInbound=Ix});var $_=y(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.MeteringInboundPolicy=void 0;var F_=Bs(),q_=gn(),wc=O(),Px=te(),Ax=He(),Rx=W(),Ox=s(async(e,t,r,n)=>{let i=Ax.SystemLogMap.getLogger(t);t.addResponseSendingFinalHook(async(d,p,f)=>{let h=F_.ContextData.get(f,"subscription");if((r.allowRequestsWithoutSubscription??!1)&&!h)return;if(!r.bucketId)if(q_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=q_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new wc.ConfigurationError(`MeteringInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:_,meteringServiceUrl:T}=Rx.Environment.instance;if(d.ok&&h&&r.meters)try{let S=await fetch(`${T}/internal/v1/metering/${r.bucketId}/subscriptions/${h.id}/quotas/consume`,{headers:{Authorization:`Bearer ${_}`,"zp-rid":f.requestId},method:"POST",body:JSON.stringify({meters:r.meters})});S.ok||(f.log.error(`MeteringInboundPolicy '${n}' -error in serviceResponse: ${S.status} - ${S.statusText}`),i.error(`MeteringInboundPolicy '${n}' -error in serviceResponse: ${S.status} - ${S.statusText}`))}catch(S){f.log.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`),i.error(`MeteringInboundPolicy '${n}' -error in serviceResponse`,S)}});let o=F_.ContextData.get(t,"subscription"),a=r.allowRequestsWithoutSubscription??!1,c=r.allowRequestsOverQuota??!1;if(!o){if(a)return e;throw new wc.ConfigurationError("Subscription is not available for user")}if(o&&Object.keys(o.quotas).length===0)throw new wc.ConfigurationError("Quota is not set up for the user's subscription");let l=Object.keys(r.meters).filter(d=>!Object.keys(o.quotas).includes(d));if(l.length>0)throw new wc.ConfigurationError(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(o.quotas))if(o.quotas[d]<=0&&!c)return Px.HttpProblems.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return e},"MeteringInboundPolicy");vc.MeteringInboundPolicy=Ox});var G_=y(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.LoadSubscriptionInboundPolicy=void 0;var Nx=ri(),xx=Bs(),j_=gn(),Cx=O(),Vp=te(),V_=He(),Lx=W(),Dx=s(async(e,t,r,n)=>{let i=V_.SystemLogMap.getLogger(t),o=r.allowRequestsWithoutSubscription??!1,a=e.user;if(!a)return o?e:Vp.HttpProblems.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!r.bucketId)if(j_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)r.bucketId=j_.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Cx.ConfigurationError(`LoadSubscriptionInboundPolicy '${n}' - no bucketId property provided`);let{authApiJWT:c,meteringServiceUrl:u}=Lx.Environment.instance,{sub:l}=a,d;try{let f=`${r.bucketId}-${l}`,h=new Nx.ZoneCache(f,{logger:V_.SystemLogMap.getLogger(t)}),g=await h.get(f);if(g)d=g;else{let _=await fetch(`${u}/internal/v1/metering/${r.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${c}`,"zp-rid":t.requestId},method:"GET"});if(!_.ok)return t.log.error(await _.text()),Vp.HttpProblems.forbidden(e,t);d=await _.json(),h.put(f,d,15).catch(T=>{throw i.error(T),T})}}catch(f){i.error(`LoadSubscriptionInboundPolicy '${n}' -error in serviceResponse`,f)}if((!d||!d.data||d.data.length===0)&&!o)return Vp.HttpProblems.unauthorized(e,t,{detail:"No valid, active subscription found"});if((!d||!d.data||d.data.length===0)&&o)return e;let p=d&&d.data?d.data[0]:void 0;return xx.ContextData.set(t,"subscription",p),e},"LoadSubscriptionInboundPolicy");Tc.LoadSubscriptionInboundPolicy=Dx});var B_=y(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.ServiceProviderImpl=void 0;var Ux=O(),Gp=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(t,r){if(this.services.get(t))throw new Ux.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};Sc.ServiceProviderImpl=Gp});var rE=y(m=>{"use strict";var Mx=m&&m.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Bp=m&&m.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Mx(t,e,r)},kx=m&&m.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(m,"__esModule",{value:!0});m.RateLimitInboundPolicy=m.BasicRateLimitInboundPolicy=m.PropelAuthJwtInboundPolicy=m.OpenIdJwtInboundPolicy=m.OktaJwtInboundPolicy=m.setMoesifContext=m.MoesifInboundPolicy=m.MockApiInboundPolicy=m.JWTScopeValidationInboundPolicy=m.GeoFilterInboundPolicy=m.FormDataToJsonInboundPolicy=m.FirebaseJwtInboundPolicy=m.CurityPhantomTokenInboundPolicy=m.CreditsMeteringInboundPolicy=m.CompositeInboundPolicy=m.CognitoJwtInboundPolicy=m.ClerkJwtInboundPolicy=m.ClearHeadersOutboundPolicy=m.ClearHeadersInboundPolicy=m.ChangeMethodInboundPolicy=m.CachingInboundPolicy=m.BasicAuthInboundPolicy=m.Auth0JwtInboundPolicy=m.ApiKeyInboundPolicy=m.ApiAuthKeyInboundPolicy=m.AmberfloMeteringPolicy=m.AmberfloMeteringInboundPolicy=m.AuditLogPlugin=m.AuditLogDataStaxProvider=m.HttpStatusCode=m.webSocketPipelineHandler=m.webSocketHandler=m.urlRewriteHandler=m.urlForwardHandler=m.redirectHandler=m.openApiSpecHandler=m.awsLambdaHandler=m.AwsLambdaHandlerExtensions=m.purgeGatewayCache=m.Handler=m.originalFetch=m.ConfigurationError=m.isZuploReadableEnvVariableName=m.isRestrictedEnvVariableName=m.environment=m.ContextData=m.ResponseSentEvent=m.ResponseSendingEvent=m.ZoneCache=m.MemoryZoneReadThroughCache=void 0;m.sanitizedIdentifierName=m.getRawOperationDataIdentifierName=m.getIdForRequestBodySchema=m.getIdForRefSchema=m.getIdForParameterSchema=m.SystemLogMap=m.httpStatuses=m.SYSTEM_LOGGER=m.API_KEY=m.ServiceProviderImpl=m.serialize=m.ContentTypes=m.Router=m.LookupResult=m.SystemRouteName=m.ZuploRequest=m.ProblemResponseFormatter=m.HttpProblems=m.LoadSubscriptionInboundPolicy=m.MeteringInboundPolicy=m.ValidateJsonSchemaInbound=m.UpstreamGcpServiceAuthInboundPolicy=m.UpstreamGcpJwtInboundPolicy=m.UpstreamFirebaseUserAuthInboundPolicy=m.UpstreamFirebaseAdminAuthInboundPolicy=m.UpstreamAzureAdServiceAuthInboundPolicy=m.SupabaseJwtInboundPolicy=m.StripeWebhookVerificationInboundPolicy=m.SleepInboundPolicy=m.SetStatusOutboundPolicy=m.SetQueryParamsInboundPolicy=m.SetHeadersOutboundPolicy=m.SetHeadersInboundPolicy=m.SetBodyInboundPolicy=m.RequireOriginInboundPolicy=m.SchemaBasedRequestValidation=m.RequestValidationInboundPolicy=m.RequestSizeLimitInboundPolicy=m.ReplaceStringOutboundPolicy=m.RemoveQueryParamsInboundPolicy=m.RemoveHeadersOutboundPolicy=m.RemoveHeadersInboundPolicy=m.ReadmeMetricsInboundPolicy=void 0;Ah();var Hx=Kt();Object.defineProperty(m,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return Hx.MemoryZoneReadThroughCache}});var Fx=ri();Object.defineProperty(m,"ZoneCache",{enumerable:!0,get:function(){return Fx.ZoneCache}});var K_=Pr();Object.defineProperty(m,"ResponseSendingEvent",{enumerable:!0,get:function(){return K_.ResponseSendingEvent}});Object.defineProperty(m,"ResponseSentEvent",{enumerable:!0,get:function(){return K_.ResponseSentEvent}});var qx=Bs();Object.defineProperty(m,"ContextData",{enumerable:!0,get:function(){return qx.ContextData}});var Kp=gn();Object.defineProperty(m,"environment",{enumerable:!0,get:function(){return Kp.environment}});Object.defineProperty(m,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return Kp.isRestrictedEnvVariableName}});Object.defineProperty(m,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return Kp.isZuploReadableEnvVariableName}});var $x=O();Object.defineProperty(m,"ConfigurationError",{enumerable:!0,get:function(){return $x.ConfigurationError}});var jx=Nd();Object.defineProperty(m,"originalFetch",{enumerable:!0,get:function(){return jx.originalFetch}});var J_=rg();Object.defineProperty(m,"Handler",{enumerable:!0,get:function(){return J_.Handler}});Object.defineProperty(m,"purgeGatewayCache",{enumerable:!0,get:function(){return J_.purgeGatewayCache}});var z_=_g();Object.defineProperty(m,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return z_.AwsLambdaHandlerExtensions}});Object.defineProperty(m,"awsLambdaHandler",{enumerable:!0,get:function(){return z_.awsLambdaHandler}});var Vx=wg();Object.defineProperty(m,"openApiSpecHandler",{enumerable:!0,get:function(){return Vx.openApiSpecHandler}});var Gx=vg();Object.defineProperty(m,"redirectHandler",{enumerable:!0,get:function(){return Gx.redirectHandler}});var Bx=Sg();Object.defineProperty(m,"urlForwardHandler",{enumerable:!0,get:function(){return Bx.urlForwardHandler}});var Kx=Pg();Object.defineProperty(m,"urlRewriteHandler",{enumerable:!0,get:function(){return Kx.urlRewriteHandler}});var Jx=Rg();Object.defineProperty(m,"webSocketHandler",{enumerable:!0,get:function(){return Jx.webSocketHandler}});var zx=xg();Object.defineProperty(m,"webSocketPipelineHandler",{enumerable:!0,get:function(){return zx.webSocketPipelineHandler}});var Wx=$u();Object.defineProperty(m,"HttpStatusCode",{enumerable:!0,get:function(){return Wx.HttpStatusCode}});Bp(Fg(),m);Bp(jg(),m);var Qx=Vg();Object.defineProperty(m,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return Qx.AuditLogDataStaxProvider}});var Yx=Bg();Object.defineProperty(m,"AuditLogPlugin",{enumerable:!0,get:function(){return Yx.AuditLogPlugin}});Bp(lb(),m);var W_=mb();Object.defineProperty(m,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return W_.AmberfloMeteringInboundPolicy}});Object.defineProperty(m,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return W_.AmberfloMeteringPolicy}});var Zx=Eb();Object.defineProperty(m,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return Zx.ApiAuthKeyInboundPolicy}});var Xx=vp();Object.defineProperty(m,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return Xx.ApiKeyInboundPolicy}});var eC=wb();Object.defineProperty(m,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return eC.Auth0JwtInboundPolicy}});var tC=vb();Object.defineProperty(m,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return tC.BasicAuthInboundPolicy}});var rC=Tb();Object.defineProperty(m,"CachingInboundPolicy",{enumerable:!0,get:function(){return rC.CachingInboundPolicy}});var nC=Sb();Object.defineProperty(m,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return nC.ChangeMethodInboundPolicy}});var iC=Ib();Object.defineProperty(m,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return iC.ClearHeadersInboundPolicy}});var oC=Pb();Object.defineProperty(m,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return oC.ClearHeadersOutboundPolicy}});var sC=Ab();Object.defineProperty(m,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return sC.ClerkJwtInboundPolicy}});var aC=Ob();Object.defineProperty(m,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return aC.CognitoJwtInboundPolicy}});var cC=xb();Object.defineProperty(m,"CompositeInboundPolicy",{enumerable:!0,get:function(){return cC.CompositeInboundPolicy}});var uC=Lb();Object.defineProperty(m,"CreditsMeteringInboundPolicy",{enumerable:!0,get:function(){return uC.CreditsMeteringInboundPolicy}});var lC=Db();Object.defineProperty(m,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return lC.CurityPhantomTokenInboundPolicy}});var dC=Ub();Object.defineProperty(m,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return dC.FirebaseJwtInboundPolicy}});var pC=Mb();Object.defineProperty(m,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return pC.FormDataToJsonInboundPolicy}});var hC=kb();Object.defineProperty(m,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return hC.GeoFilterInboundPolicy}});var fC=Hb();Object.defineProperty(m,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return fC.JWTScopeValidationInboundPolicy}});var mC=qb();Object.defineProperty(m,"MockApiInboundPolicy",{enumerable:!0,get:function(){return mC.MockApiInboundPolicy}});var Q_=Bb();Object.defineProperty(m,"MoesifInboundPolicy",{enumerable:!0,get:function(){return Q_.MoesifInboundPolicy}});Object.defineProperty(m,"setMoesifContext",{enumerable:!0,get:function(){return Q_.setMoesifContext}});var yC=Kb();Object.defineProperty(m,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return yC.OktaJwtInboundPolicy}});var gC=jt();Object.defineProperty(m,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return gC.OpenIdJwtInboundPolicy}});var bC=Jb();Object.defineProperty(m,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return bC.PropelAuthJwtInboundPolicy}});var Y_=e_();Object.defineProperty(m,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return Y_.RateLimitInboundPolicy}});Object.defineProperty(m,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return Y_.RateLimitInboundPolicy}});var _C=i_();Object.defineProperty(m,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return _C.ReadmeMetricsInboundPolicy}});var EC=o_();Object.defineProperty(m,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return EC.RemoveHeadersInboundPolicy}});var wC=s_();Object.defineProperty(m,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return wC.RemoveHeadersOutboundPolicy}});var vC=a_();Object.defineProperty(m,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return vC.RemoveQueryParamsInboundPolicy}});var TC=c_();Object.defineProperty(m,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return TC.ReplaceStringOutboundPolicy}});var SC=l_();Object.defineProperty(m,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return SC.RequestSizeLimitInboundPolicy}});var Z_=m_();Object.defineProperty(m,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return Z_.RequestValidationInboundPolicy}});Object.defineProperty(m,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return Z_.SchemaBasedRequestValidation}});var IC=y_();Object.defineProperty(m,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return IC.RequireOriginInboundPolicy}});var PC=g_();Object.defineProperty(m,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return PC.SetBodyInboundPolicy}});var AC=__();Object.defineProperty(m,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return AC.SetHeadersInboundPolicy}});var RC=w_();Object.defineProperty(m,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return RC.SetHeadersOutboundPolicy}});var OC=T_();Object.defineProperty(m,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return OC.SetQueryParamsInboundPolicy}});var NC=S_();Object.defineProperty(m,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return NC.SetStatusOutboundPolicy}});var xC=I_();Object.defineProperty(m,"SleepInboundPolicy",{enumerable:!0,get:function(){return xC.SleepInboundPolicy}});var CC=dp();Object.defineProperty(m,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return CC.StripeWebhookVerificationInboundPolicy}});var LC=A_();Object.defineProperty(m,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return LC.SupabaseJwtInboundPolicy}});var DC=O_();Object.defineProperty(m,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return DC.UpstreamAzureAdServiceAuthInboundPolicy}});var UC=x_();Object.defineProperty(m,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return UC.UpstreamFirebaseAdminAuthInboundPolicy}});var MC=C_();Object.defineProperty(m,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return MC.UpstreamFirebaseUserAuthInboundPolicy}});var kC=D_();Object.defineProperty(m,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return kC.UpstreamGcpJwtInboundPolicy}});var HC=M_();Object.defineProperty(m,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return HC.UpstreamGcpServiceAuthInboundPolicy}});var FC=H_();Object.defineProperty(m,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return FC.ValidateJsonSchemaInbound}});var qC=$_();Object.defineProperty(m,"MeteringInboundPolicy",{enumerable:!0,get:function(){return qC.MeteringInboundPolicy}});var $C=G_();Object.defineProperty(m,"LoadSubscriptionInboundPolicy",{enumerable:!0,get:function(){return $C.LoadSubscriptionInboundPolicy}});var jC=te();Object.defineProperty(m,"HttpProblems",{enumerable:!0,get:function(){return jC.HttpProblems}});var VC=go();Object.defineProperty(m,"ProblemResponseFormatter",{enumerable:!0,get:function(){return VC.ProblemResponseFormatter}});var GC=ke();Object.defineProperty(m,"ZuploRequest",{enumerable:!0,get:function(){return GC.ZuploRequest}});var BC=Rr();Object.defineProperty(m,"SystemRouteName",{enumerable:!0,get:function(){return BC.SystemRouteName}});var X_=Ed();Object.defineProperty(m,"LookupResult",{enumerable:!0,get:function(){return X_.LookupResult}});Object.defineProperty(m,"Router",{enumerable:!0,get:function(){return X_.Router}});var eE=xu();Object.defineProperty(m,"ContentTypes",{enumerable:!0,get:function(){return eE.ContentTypes}});Object.defineProperty(m,"serialize",{enumerable:!0,get:function(){return eE.serialize}});var KC=B_();Object.defineProperty(m,"ServiceProviderImpl",{enumerable:!0,get:function(){return KC.ServiceProviderImpl}});var tE=el();Object.defineProperty(m,"API_KEY",{enumerable:!0,get:function(){return tE.API_KEY}});Object.defineProperty(m,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return tE.SYSTEM_LOGGER}});var JC=Vu();Object.defineProperty(m,"httpStatuses",{enumerable:!0,get:function(){return kx(JC).default}});var zC=He();Object.defineProperty(m,"SystemLogMap",{enumerable:!0,get:function(){return zC.SystemLogMap}});var qi=tc();Object.defineProperty(m,"getIdForParameterSchema",{enumerable:!0,get:function(){return qi.getIdForParameterSchema}});Object.defineProperty(m,"getIdForRefSchema",{enumerable:!0,get:function(){return qi.getIdForRefSchema}});Object.defineProperty(m,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return qi.getIdForRequestBodySchema}});Object.defineProperty(m,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return qi.getRawOperationDataIdentifierName}});Object.defineProperty(m,"sanitizedIdentifierName",{enumerable:!0,get:function(){return qi.sanitizedIdentifierName}})});var nE=y($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.BaseCryptoBeta=$n.supportedDigests=void 0;$n.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var Jp=class{static{s(this,"BaseCryptoBeta")}};$n.BaseCryptoBeta=Jp});var iE=y(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.WorkerCryptoBeta=void 0;var zp=nE(),WC=O(),Wp=class extends zp.BaseCryptoBeta{static{s(this,"WorkerCryptoBeta")}async digest(t,r){if(!zp.supportedDigests.includes(t.toLowerCase()))throw new WC.RuntimeError(`Algorithm ${t} is not supported. Try using ${zp.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};Ic.WorkerCryptoBeta=Wp});var oE=y(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.BaseKeyValueStore=void 0;var Qp=class{static{s(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};Pc.BaseKeyValueStore=Qp});var aE=y(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.WorkerKeyValueStore=void 0;var sE=O(),QC=oE(),Yp=class extends QC.BaseKeyValueStore{static{s(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new sE.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new sE.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};Ac.WorkerKeyValueStore=Yp});var Dt=y(dt=>{"use strict";var YC=dt&&dt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),ZC=dt&&dt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&YC(t,e,r)};Object.defineProperty(dt,"__esModule",{value:!0});dt.KeyValueStore=dt.CryptoBeta=void 0;ZC(rE(),dt);var XC=iE();Object.defineProperty(dt,"CryptoBeta",{enumerable:!0,get:function(){return XC.WorkerCryptoBeta}});var eL=aE();Object.defineProperty(dt,"KeyValueStore",{enumerable:!0,get:function(){return eL.WorkerKeyValueStore}})});var aD={};ro(aD,{GraphQLComplexityLimitInboundPolicy:()=>FE,GraphQLDisableIntrospectionInboundPolicy:()=>$E});module.exports=no(aD);var Xn=Th(Dt());function G(e,t){if(!!!e)throw new Error(t)}s(G,"devAssert");function Ee(e){return typeof e=="object"&&e!==null}s(Ee,"isObjectLike");function Rt(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}s(Rt,"invariant");var tL=/\r\n|[\n\r]/g;function jn(e,t){let r=0,n=1;for(let i of e.body.matchAll(tL)){if(typeof i.index=="number"||Rt(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}s(jn,"getLocation");function Zp(e){return Rc(e.source,jn(e.source,e.start))}s(Zp,"printLocation");function Rc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,o=e.locationOffset.line-1,a=t.line+o,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
|
|
75
75
|
`,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let f=Math.floor(u/80),h=u%80,g=[];for(let _=0;_<p.length;_+=80)g.push(p.slice(_,_+80));return l+cE([[`${a} |`,g[0]],...g.slice(1,f+1).map(_=>["|",_]),["|","^".padStart(h)],["|",g[f+1]]])}return l+cE([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}s(Rc,"printSourceLocation");function cE(e){let t=e.filter(([n,i])=>i!==void 0),r=Math.max(...t.map(([n])=>n.length));return t.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
|
|
76
76
|
`)}s(cE,"printPrefixedLines");function rL(e){let t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}s(rL,"toNormalizedOptions");var C=class e extends Error{static{s(this,"GraphQLError")}constructor(t,...r){var n,i,o;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=rL(r);super(t),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=uE(Array.isArray(a)?a:a?[a]:void 0);let f=uE((n=this.nodes)===null||n===void 0?void 0:n.map(g=>g.loc).filter(g=>g!=null));this.source=c??(f==null||(i=f[0])===null||i===void 0?void 0:i.source),this.positions=u??f?.map(g=>g.start),this.locations=u&&c?u.map(g=>jn(c,g)):f?.map(g=>jn(g.source,g.start));let h=Ee(d?.extensions)?d?.extensions:void 0;this.extensions=(o=p??h)!==null&&o!==void 0?o:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let t=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(t+=`
|
|
77
77
|
|