@zuplo/graphql 5.1811.0 → 5.1813.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 +1 -1
- package/package.json +1 -1
package/index.minified.js
CHANGED
|
@@ -71,7 +71,7 @@ Signature verification is impossible without access to the original signed mater
|
|
|
71
71
|
`+d}):new Wr.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 Wr.StripeSignatureVerificationError(t,e,{message:"Timestamp outside the tolerance zone"});return!0}o(wR,"validateComputedSignature");function vR(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:[]})}o(vR,"parseHeader");function TR(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}o(TR,"secureCompare");async function Vb(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)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=Gp[s[c]];return a.join("")}o(Vb,"computeHMACSignatureAsync");Wn.computeHMACSignatureAsync=Vb;var Gp=new Array(256);for(let e=0;e<Gp.length;e++)Gp[e]=e.toString(16).padStart(2,"0")});var Mt=b(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.optionValidator=void 0;var Qn=k(),SR=st();function IR(e,t){if(!(0,SR.isObject)(e))throw new Qn.ConfigurationError(`Options on policy '${t}' is expected to be an object. Received the type '${typeof e}'.`);let r=o((s,a,c)=>{let u=e[s];if(!(c&&u===void 0)){if(u===void 0)throw new Qn.ConfigurationError(`Value of '${String(s)}' 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 Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Qn.ConfigurationError(`Value of '${String(s)}' 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 Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(IR,"optionValidator");ka.optionValidator=IR});var Kp=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.StripeWebhookVerificationInboundPolicy=void 0;var PR=Pi(),AR=pe(),RR=Gb(),OR=Mt(),Bp=class extends PR.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(t,r){(0,OR.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=t.headers.get("stripe-signature");try{let i=await t.clone().text();await(0,RR.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){return r.log.error("Error validating stripe webhook",i),AR.HttpProblems.badRequest(t,r,{title:"Webhook Error",detail:i.message})}return t}};Fa.StripeWebhookVerificationInboundPolicy=Bp});var Kb=b(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.isStripeWebhookEvent=void 0;var Bb=st();function NR(e){return e!==null&&typeof e=="object"&&"id"in e&&(0,Bb.isString)(e.id)&&"type"in e&&(0,Bb.isString)(e.type)}o(NR,"isStripeWebhookEvent");Ha.isStripeWebhookEvent=NR});var Jb=b(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.MeteringPlugin=void 0;var xR=It(),Jp=class extends xR.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};qa.MeteringPlugin=Jp});var Qp=b(Wp=>{"use strict";Object.defineProperty(Wp,"__esModule",{value:!0});var zp=k(),CR={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 s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new zp.RuntimeError(s)}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 s="Error retrieving customer from Stripe API.";throw r.error(s,i),new zp.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new zp.RuntimeError(s)}return i}};Wp.default=CR});var zb=b(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.deleteConsumer=Ir.createConsumerInvite=Ir.createConsumer=void 0;var Yp=k(),Zp=Ze(),Xp=oe(),eh=Cn(),th="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function DR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=Xp.Environment.instance,u=new URL(`/v1/buckets/${e}/consumers`,th);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,eh.fetchRetry)({retryDelayMs:5,retries:2,logger:Zp.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let f="Error creating API Key Consumer";throw a.log.error(f,h),new Yp.RuntimeError(f)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:t,stripeProductId:r}),l}o(DR,"createConsumer");Ir.createConsumer=DR;async function LR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=Xp.Environment.instance,c=new URL(`/v1/buckets/${e}/consumers`,th);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,eh.fetchRetry)({retryDelayMs:5,retries:2,logger:Zp.SystemLogMap.getLogger(s)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new Yp.RuntimeError(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:t,stripeProductId:r}),u}o(LR,"createConsumerInvite");Ir.createConsumerInvite=LR;async function MR({apiKeyBucketName:e,consumerId:t,context:r}){let{authApiJWT:n}=Xp.Environment.instance,i=new URL(`/v1/buckets/${e}/consumers/${t}`,th);i.searchParams.set("with-api-key","true");let s=await(0,eh.fetchRetry)({retryDelayMs:5,retries:2,logger:Zp.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error deleting API Key Consumer";throw r.log.error(c,a),new Yp.RuntimeError(c)}return r.log.info(`Successfully deleted API Key Consumer '${t}`),t}o(MR,"deleteConsumer");Ir.deleteConsumer=MR});var $a=b(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.getSubscription=Ar.updateSubscription=Ar.createSubscription=void 0;var Pr=k(),rh=Ze(),nh=oe(),ih=Cn(),oh=st();async function UR({context:e,stripeSubscriptionId:t,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c}){let u={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:t,planExternalIds:[r],customerKey:n,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=nh.Environment.instance;if(!(0,oh.isNonEmptyString)(l))throw new Pr.SystemError("No Zuplo JWT token set.");let p=await(0,ih.fetchRetry)({retryDelayMs:5,retries:2,logger:rh.SystemLogMap.getLogger(e)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"POST",body:JSON.stringify(u)});if(!p.ok){let h="Error creating metering subscription.",f;try{f=await p.json()}catch{f={status:p.status,statusText:p.statusText}}throw e.log.error(h,f),new Pr.RuntimeError(h)}e.log.info("Successfully created/updated metering subscription.",u)}o(UR,"createSubscription");Ar.createSubscription=UR;async function kR({context:e,meteringSubscriptionId:t,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=nh.Environment.instance;if(!(0,oh.isNonEmptyString)(i))throw new Pr.SystemError("No Zuplo JWT token set.");let a=await(0,ih.fetchRetry)({retryDelayMs:5,retries:2,logger:rh.SystemLogMap.getLogger(e)},`${s}/internal/v1/metering/${r}/subscriptions/${t}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating metering subscription to '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw e.log.error(c,u),new Pr.RuntimeError(c)}e.log.info(`Successfully update metering subscription to '${JSON.stringify(n)}'.`)}o(kR,"updateSubscription");Ar.updateSubscription=kR;async function FR({context:e,stripeSubscriptionId:t,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=nh.Environment.instance;if(!(0,oh.isNonEmptyString)(i))throw new Pr.SystemError("No Zuplo JWT token set.");let a=await(0,ih.fetchRetry)({retryDelayMs:5,retries:2,logger:rh.SystemLogMap.getLogger(e)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${t}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":e.requestId},method:"GET"});if(!a.ok){let u="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw e.log.error(u,l),new Pr.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw e.log.error(u),new Pr.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw e.log.error(u),new Pr.RuntimeError(u)}return c.data[0]}o(FR,"getSubscription");Ar.getSubscription=FR});var sh=b(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.stripeStatusToMeteringStatus=void 0;function HR(e){return e.replaceAll("_","-")}o(HR,"stripeStatusToMeteringStatus");ja.stripeStatusToMeteringStatus=HR});var Wb=b(Qi=>{"use strict";var qR=Qi&&Qi.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qi,"__esModule",{value:!0});var Qr=pe(),$R=qR(Qp()),ah=zb(),jR=$a(),VR=sh();async function GR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return t.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)u=await(0,ah.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:r.data.object.metadata.zuplo_created_by_email,managerSub:r.data.object.metadata.zuplo_created_by_sub,context:t});else{let l=await $R.default.getCustomer({logger:t.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!l.email)return t.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,ah.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l.email,context:t})}if(!u)return Qr.HttpProblems.internalServerError(e,t,{detail:"No consumer was created, skipping creation of subscription"});try{let l=(0,VR.stripeStatusToMeteringStatus)(r.data.object.status);await(0,jR.createSubscription)({context:t,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await(0,ah.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:t}),Qr.HttpProblems.internalServerError(e,t,{detail:l.message})}return Qr.HttpProblems.ok(e,t)}o(GR,"onCustomerSubscriptionCreated");Qi.default=GR});var Yb=b(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var ch=pe(),Qb=$a();async function BR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),ch.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),ch.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,Qb.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,Qb.updateSubscription)({context:t,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),ch.HttpProblems.ok(e,t)}o(BR,"onCustomerSubscriptionDeleted");uh.default=BR});var Zb=b(Zi=>{"use strict";var KR=Zi&&Zi.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Zi,"__esModule",{value:!0});var Yi=pe(),JR=KR(Qp()),Va=$a(),zR=sh();async function WR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),Yi.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Yi.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){t.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,Va.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,zR.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,Va.updateSubscription)({context:t,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),Yi.HttpProblems.ok(e,t)}if(a.plan&&a.plan.product!==r.data.object.plan.product){t.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,Va.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,d=(await JR.default.getUpcomingInvoice({customerId:s,logger:t.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===u),p=0;return d.length===0?t.log.warn(`Not able to calculate proration details on plan change for subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,Va.updateSubscription)({context:t,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),Yi.HttpProblems.ok(e,t)}}return t.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),Yi.HttpProblems.badRequest(e,t,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(WR,"onCustomerSubscriptionUpdated");Zi.default=WR});var e_=b(Yn=>{"use strict";var dh=Yn&&Yn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yn,"__esModule",{value:!0});Yn.StripeMeteringPlugin=void 0;var Ga=Ki(),Ba=k(),QR=jt(),YR=Kp(),Xb=pe(),ZR=ir(),XR=mn(),eO=hl(),tO=ft(),rO=oe(),nO=Kb(),iO=Jb(),oO=dh(Wb()),sO=dh(Yb()),aO=dh(Zb()),lh=class extends iO.MeteringPlugin{static{o(this,"StripeMeteringPlugin")}options;constructor(t){super(),this.options=t}registerRoutes(t,r){let n=o(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(!rO.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(!cO(p))throw new Ba.ConfigurationError(`StripeMeteringPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let h=await c.json();if(!(0,nO.isStripeWebhookEvent)(h))return Xb.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await(0,oO.default)(c,u,h,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,aO.default)(c,u,h,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,sO.default)(c,u,h,{meteringBucketId:l});default:return Xb.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=(0,XR.createInternalPolicyProcessor)({inboundPolicies:[new YR.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),s=new QR.Pipeline({processors:[ZR.metricsProcessor,i],handler:n,gateway:r}),a=new tO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:eO.SystemRouteName.StripePlugin});t.addRoute(a,s.execute)}};Yn.StripeMeteringPlugin=lh;function cO(e){return e!==null&&typeof e=="string"&&["us-central1","europe-west4"].includes(e)}o(cO,"isMetricsRegion")});var o_=b(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.AmberfloMeteringInboundPolicy=Zn.AmberfloMeteringPolicy=void 0;var t_=k(),uO=Oe(),r_=sr(),i_=new WeakMap,n_={},ph=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){i_.set(t,r)}};Zn.AmberfloMeteringPolicy=ph;async function lO(e,t,r,n){if(!r.statusCodes)throw new t_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,r_.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=i_.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new t_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,r_.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)},h=n_[r.apiKey];if(!h){let f=r.apiKey,y=e.headers.get("zm-test-id")??"";h=new uO.BatchDispatch("amberflo-ingest-meter",10,async _=>{try{let I=r.url??"https://app.amberflo.io/ingest",O=await fetch(I,{method:"POST",body:JSON.stringify(_),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});O.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${O.status}: ${await O.text()}`)}catch(I){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${I.message}`),I}}),n_[f]=h}h.enqueue(p),t.waitUntil(h.waitUntilFlushed())}}),e}o(lO,"AmberfloMeteringInboundPolicy");Zn.AmberfloMeteringInboundPolicy=lO});var hh=b(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.sha256=void 0;async function dO(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("")}o(dO,"sha256");Ka.sha256=dO});var Wt=b(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.getPolicyCacheName=void 0;var pO=hh(),s_=new Map;async function hO(e,t){let r,n=s_.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,pO.sha256)(JSON.stringify({policyName:e,options:t}))}`,s_.set(e,r)),r}o(hO,"getPolicyCacheName");Ja.getPolicyCacheName=hO});var yh=b(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.ApiKeyInboundPolicy=void 0;var fO=Wt(),mO=er(),a_=Ki(),fh=k(),yO=Vt(),c_=Ze(),mh=oe(),gO=Cn(),u_="key-metadata-cache-type";function bO(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}o(bO,"getKeyValue");async function _O(e,t,r,n){if(!r.bucketName)if(a_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=a_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new fh.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 fh.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(I=>i.allowUnauthenticatedRequests?e:yO.HttpProblems.unauthorized(e,t,{detail:I}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=bO(a,i);if(!c||c==="")return s("No key present");let u=await EO(c),l=await(0,fO.getPolicyCacheName)(n,i),d=new mO.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!==u_&&c_.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:c},f=await(0,gO.fetchRetry)({retryDelayMs:5,retries:2,logger:c_.SystemLogMap.getLogger(t)},`${mh.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":mh.Environment.instance.deploymentName??"unknown","User-Agent":mh.Environment.instance.systemUserAgent},body:JSON.stringify(h)});if(f.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(f.status!==200){try{let I=await f.text(),O=JSON.parse(I);t.log.error("Unexpected response from key service",O)}catch{t.log.error("Invalid response from key service")}throw new fh.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${f.status}`)}let y=await f.json(),_={isValid:!0,typeId:u_,user:{sub:y.name,data:y.metadata}};return e.user=_.user,d.put(u,_,i.cacheTtlSeconds),e}o(_O,"ApiKeyInboundPolicy");za.ApiKeyInboundPolicy=_O;async function EO(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(EO,"hashValue")});var l_=b(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.ApiAuthKeyInboundPolicy=void 0;var wO=yh();Wa.ApiAuthKeyInboundPolicy=wO.ApiKeyInboundPolicy});var Qt=b(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.OpenIdJwtInboundPolicy=void 0;var bh=(Ys(),Po(Qs)),_h=k(),vO=pe(),gh={},TO=o(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new _h.ConfigurationError("Invalid State - jwkUrl not set");gh[t.jwkUrl]||(gh[t.jwkUrl]=(0,bh.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,bh.jwtVerify)(e,gh[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),SO=o(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 s=new TextEncoder().encode(t.secret);r=new Uint8Array(s)}else r=t.secret;let{payload:n}=await(0,bh.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),IO=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),s="bearer ",a=o(h=>vO.HttpProblems.unauthorized(e,t,{detail:h}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new _h.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new _h.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?TO:SO,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=i.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await c(h,r)}catch(f){let y=new URL(e.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${y.pathname} `,f):t.log.warn(`Invalid token on: ${e.method} ${y.pathname}`,f),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");Qa.OpenIdJwtInboundPolicy=IO});var d_=b(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.Auth0JwtInboundPolicy=void 0;var PO=Qt(),AO=o(async(e,t,r,n)=>(0,PO.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");Ya.Auth0JwtInboundPolicy=AO});var p_=b(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.BasicAuthInboundPolicy=void 0;var RO=pe(),OO=o(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",s=o(l=>RO.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(_=>_.username===h&&_.password===f);return y||await s("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");Za.BasicAuthInboundPolicy=OO});var h_=b(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.CachingInboundPolicy=void 0;var NO=Wt(),xO=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function CO(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(CO,"digestMessage");var DO=o(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 CO(JSON.stringify(n)),s=new URL(e.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function LO(e,t,r,n){let i=await(0,NO.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await DO(e,r),u=await s.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 h=r?.expirationSecondsTtl??60,f=new Response(p.body,p);xO.forEach(y=>f.headers.delete(y)),f.headers.set("cache-control",`s-maxage=${h}`),t.waitUntil(s.put(c,f))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}o(LO,"CachingInboundPolicy");Xa.CachingInboundPolicy=LO});var f_=b(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.ChangeMethodInboundPolicy=void 0;var MO=k(),UO=Be(),kO=o(async(e,t,r,n)=>{if(!r.method)throw new MO.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new UO.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");ec.ChangeMethodInboundPolicy=kO});var m_=b(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.ClearHeadersInboundPolicy=void 0;var FO=Be(),HO=o(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 FO.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");tc.ClearHeadersInboundPolicy=HO});var y_=b(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ClearHeadersOutboundPolicy=void 0;var qO=o(async(e,t,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&s.set(c,u)}),new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");rc.ClearHeadersOutboundPolicy=qO});var g_=b(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ClerkJwtInboundPolicy=void 0;var $O=Qt(),jO=o(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,$O.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");nc.ClerkJwtInboundPolicy=jO});var __=b(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.CognitoJwtInboundPolicy=void 0;var b_=k(),VO=Qt(),GO=o(async(e,t,r,n)=>{if(!r.userPoolId)throw new b_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new b_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,VO.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");ic.CognitoJwtInboundPolicy=GO});var w_=b(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.CompositeInboundPolicy=void 0;var BO=k(),KO=kr(),E_=mn(),JO=o(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new BO.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=KO.Gateway.instance,s=(0,E_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,E_.toStackedInboundHandler)(s)(e,t)},"CompositeInboundPolicy");oc.CompositeInboundPolicy=JO});var v_=b(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.CurityPhantomTokenInboundPolicy=void 0;var zO=Wt(),WO=er(),sc=pe(),QO=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return sc.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let s=YO(i);if(!s)return sc.HttpProblems.unauthorized(e,t,{detail:"Failed to parse token from Authorization header"});let a=await(0,zO.getPolicyCacheName)(n,r),c=new WO.MemoryZoneReadThroughCache(a,t),u=await c.get(s);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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(t.log.error(`Error introspecting token - ${l.status}: '${d}'`),sc.HttpProblems.internalServerError(e,t,{detail:"Problem encountered authorizing the HTTP request"})):sc.HttpProblems.unauthorized(e,t)}return e.headers.set("Authorization",`Bearer ${u}`),e},"CurityPhantomTokenInboundPolicy");ac.CurityPhantomTokenInboundPolicy=QO;function YO(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}o(YO,"getToken")});var T_=b(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.FirebaseJwtInboundPolicy=void 0;var ZO=Mt(),XO=Qt(),eN=o(async(e,t,r,n)=>((0,ZO.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,XO.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");cc.FirebaseJwtInboundPolicy=eN});var S_=b(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.FormDataToJsonInboundPolicy=void 0;var tN=Be(),rN=o(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=e.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))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 tN.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");uc.FormDataToJsonInboundPolicy=rN});var I_=b(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.GeoFilterInboundPolicy=void 0;var nN=k(),iN=pe(),Xn="__unknown__",oN=o(async(e,t,r,n)=>{let i={allow:{countries:ti(r.allow?.countries,"allow.countries",n),regionCodes:ti(r.allow?.regionCodes,"allow.regionCode",n),asns:ti(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ti(r.block?.countries,"block.countries",n),regionCodes:ti(r.block?.regionCodes,"block.regionCode",n),asns:ti(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=t.incomingRequestProperties.country?.toLowerCase()??Xn,a=t.incomingRequestProperties.regionCode?.toLowerCase()??Xn,c=t.incomingRequestProperties.asn?.toString()??Xn,u=i.ignoreUnknown&&s===Xn,l=i.ignoreUnknown&&a===Xn,d=i.ignoreUnknown&&c===Xn,p=i.allow.countries,h=i.allow.regionCodes,f=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||h.length>0&&!h.includes(a)&&!l||f.length>0&&!f.includes(c)&&!d)return ei(e,t,n,s,a,c);let y=i.block.countries,_=i.block.regionCodes,I=i.block.asns;return y.length>0&&y.includes(s)&&!u||_.length>0&&_.includes(a)&&!l||I.length>0&&I.includes(c)&&!d?ei(e,t,n,s,a,c):e},"GeoFilterInboundPolicy");lc.GeoFilterInboundPolicy=oN;function ei(e,t,r,n,i,s){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),iN.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:s}})}o(ei,"blockedResponse");function ti(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 nN.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}o(ti,"toLowerStringArray")});var P_=b(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.JWTScopeValidationInboundPolicy=void 0;var sN=o(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");dc.JWTScopeValidationInboundPolicy=sN});var R_=b(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.MockApiInboundPolicy=void 0;var aN=pe(),cN=o(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return Eh(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return Eh(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:c,contentName:l,exampleName:h,exampleValue:d[h]})})})}),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 A_(a[c])}else return a.length>0?A_(a[0]):Eh(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");pc.MockApiInboundPolicy=cN;function A_(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})}}o(A_,"generateResponse");var Eh=o((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return aN.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var D_=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.MoesifInboundPolicy=ri.setMoesifContext=void 0;var uN=k(),lN=Oe(),dN="Incoming",pN={logRequestBody:!0,logResponseBody:!0};function O_(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}o(O_,"headersToObject");function N_(){return new Date().toISOString()}o(N_,"timestamp");var wh=new WeakMap,hN={};function fN(e,t){let r=wh.get(e);r||(r=hN);let n=Object.assign({...r},t);wh.set(e,n)}o(fN,"setMoesifContext");ri.setMoesifContext=fN;async function x_(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}o(x_,"readBody");var mN={},vh;function C_(){if(!vh)throw new uN.RuntimeError("Invalid State - no _lastLogger");return vh}o(C_,"getLastLogger");function yN(e){let t=mN[e];return t||(t=new lN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);C_().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||C_().error({status:i.status,body:await i.text()})})),t}o(yN,"getDispatcher");async function gN(e,t,r,n){vh=t.log;let i=N_(),s=Object.assign(pN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await x_(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=yN(s.applicationId),d=e.headers.get("true-client-ip"),p=wh.get(t)??{},h={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:O_(e.headers)},f=s.logResponseBody?await x_(c,t):void 0,y={time:N_(),status:c.status,headers:O_(c.headers),body:f},_={request:h,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:dN};l.enqueue(_),t.waitUntil(l.waitUntilFlushed())}),e}o(gN,"MoesifInboundPolicy");ri.MoesifInboundPolicy=gN});var U_=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.consumeSubcriptionQuotas=ni.loadSubscription=void 0;var L_=Ze(),M_=oe();async function bN(e,t,r,n){let i=L_.SystemLogMap.getLogger(e),{authApiJWT:s,meteringServiceUrl:a}=M_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${t}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":e.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";e.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(bN,"loadSubscription");ni.loadSubscription=bN;async function _N(e,t,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=M_.Environment.instance,c=L_.SystemLogMap.getLogger(e);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${t}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":e.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";e.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){e.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(_N,"consumeSubcriptionQuotas");ni.consumeSubcriptionQuotas=_N});var k_=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.parseAllowedSubscriptionStatuses=ii.validateMeters=void 0;var Yr=k(),EN=sr(),wN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function vN(e,t){try{let r=[];for(let n in e)typeof e[n]!="number"&&!(Number.isInteger(e[n])&&/^-?\d+$/.test(e[n].toString()))&&r.push(n);if(r.length>0)throw new Yr.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof Yr.ConfigurationError?new Yr.ConfigurationError(`MonetizationInboundPolicy '${t}' - The property 'meters' is invalid. ${r.message}`):r}}o(vN,"validateMeters");ii.validateMeters=vN;function TN(e,t){if(e)try{if(e.length===0)throw new Yr.ConfigurationError("Must set valid subscription statuses");let r=(0,EN.parseValueToStringArray)(e),n=[];for(let i of r)wN.has(i)||n.push(i);if(n.length>0)throw new Yr.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return e}catch(r){throw r instanceof Yr.ConfigurationError?new Yr.ConfigurationError(`MonetizationInboundPolicy '${t}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(TN,"parseAllowedSubscriptionStatuses");ii.parseAllowedSubscriptionStatuses=TN});var H_=b(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.MonetizationInboundPolicy=void 0;var Zr=un(),Xr=cp(),hc=Ki(),Th=k(),SN=Pi(),en=pe(),IN=sr(),PN=Mt(),F_=U_(),fc=k_(),Sh=class extends SN.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(t){return Xr.ContextData.get(t,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(t,r){(0,fc.validateMeters)(r,"setMeters"),Xr.ContextData.set(t,Zr.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(t,r){if((0,PN.optionValidator)(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new Th.ConfigurationError(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let n=this.options.allowRequestsOverQuota??!1,i=Array.isArray(this.options.meterOnStatusCodes)?this.options.meterOnStatusCodes:(0,IN.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=Xr.ContextData.get(r,Zr.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,fc.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,fc.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(_,I,O)=>{let g=Xr.ContextData.get(O,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Th.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let R=Xr.ContextData.get(O,Zr.DYNAMIC_METERS_CONTEXT_DATA),K={...this.options.meters,...R};(0,fc.validateMeters)(K,this.policyName),i.includes(_.status)&&g&&K&&(O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(K)} on response status '${_.status}'`),await(0,F_.consumeSubcriptionQuotas)(O,g.id,this.policyName,this.options.bucketId,K))});let l=t.user;if(!l)return c?t:en.HttpProblems.unauthorized(t,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Th.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,F_.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?t:en.HttpProblems.unauthorized(t,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),en.HttpProblems.unauthorized(t,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),Xr.ContextData.set(r,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let h=Xr.ContextData.get(r,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!h)return c?t:(r.log.warn("Subscription is not available for user"),en.HttpProblems.paymentRequired(t,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return r.log.error(`Quota is not set up for subscription '${h.id}'`),en.HttpProblems.tooManyRequests(t,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(_=>!Object.keys(h.meters).includes(_));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),en.HttpProblems.tooManyRequests(t,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let _ of Object.keys(a))if(h.meters[_].consumed<=0&&!n)return en.HttpProblems.tooManyRequests(t,r,{detail:`Quota exceeded for meter '${_}'`,title:"Quota Exceeded"});return t}};mc.MonetizationInboundPolicy=Sh});var q_=b(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.OktaJwtInboundPolicy=void 0;var AN=Qt(),RN=o(async(e,t,r,n)=>(0,AN.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");yc.OktaJwtInboundPolicy=RN});var $_=b(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.PropelAuthJwtInboundPolicy=void 0;var ON=(Ys(),Po(Qs)),NN=Qt(),Ih,xN=o(async(e,t,r,n)=>{if(!Ih)try{Ih=await(0,ON.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,NN.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:Ih,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");gc.PropelAuthJwtInboundPolicy=xN});var j_=b(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var We=st(),ut=class extends Error{static{o(this,"ValidationError")}constructor(t){super(t)}};Z.ValidationError=ut;var Xi=class extends ut{static{o(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};Z.ArgumentUndefinedError=Xi;var eo=class extends ut{static{o(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};Z.ArgumentTypeError=eo;function CN(e,t){if((0,We.isUndefined)(e))throw new Xi(t)}o(CN,"throwIfUndefined");Z.throwIfUndefined=CN;function Ph(e,t){if((0,We.isUndefinedOrNull)(e))throw new Xi(t)}o(Ph,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=Ph;function DN(e,t){if(Ph(e,t),!(0,We.isString)(e))throw new eo(t,"string")}o(DN,"throwIfNotString");Z.throwIfNotString=DN;function LN(e,t){if(Ph(e,t),!(0,We.isNumber)(e))throw new eo(t,"number")}o(LN,"throwIfNotNumber");Z.throwIfNotNumber=LN;var to=class extends ut{static{o(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};Z.OptionUndefinedError=to;var oi=class extends ut{static{o(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=oi;function MN(e,t,r,n){if((0,We.isUndefined)(n))throw new to(e,t,r)}o(MN,"throwIfOptionUndefined");Z.throwIfOptionUndefined=MN;function bc(e,t,r,n){if((0,We.isUndefinedOrNull)(n))throw new to(e,t,r)}o(bc,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=bc;function UN(e,t,r,n){if(bc(e,t,r,n),!(0,We.isString)(n))throw new oi(e,t,r,"string")}o(UN,"throwIfOptionNotString");Z.throwIfOptionNotString=UN;function kN(e,t,r,n){if(bc(e,t,r,n),!(0,We.isNumber)(n))throw new oi(e,t,r,"number")}o(kN,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=kN;function FN(e,t,r,n){if(bc(e,t,r,n),!(0,We.isObject)(n))throw new oi(e,t,r,"object")}o(FN,"throwIfOptionNotObject");Z.throwIfOptionNotObject=FN;function HN(e,t){if((0,We.isUndefined)(e))throw new ut(t)}o(HN,"throwIfStateUndefined");Z.throwIfStateUndefined=HN;function _c(e,t){if((0,We.isUndefinedOrNull)(e))throw new ut(t)}o(_c,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=_c;function qN(e,t){if(_c(e,t),!(0,We.isString)(e))throw new ut(t);return!0}o(qN,"throwIfStateNotString");Z.throwIfStateNotString=qN;function $N(e,t){if(_c(e,t),!(0,We.isNumber)(e))throw new ut(t);return!0}o($N,"throwIfStateNotNumber");Z.throwIfStateNotNumber=$N;function jN(e,t){if(_c(e,t),!(0,We.isObject)(e))throw new ut(t);return!0}o(jN,"throwIfStateNotObject");Z.throwIfStateNotObject=jN});var V_=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.InMemoryRedisClient=si.StandardRedisClient=void 0;var Ah=k(),Ec=j_(),Rh=class e{static{o(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,Ec.throwIfNotString)(t,"redisClientUrl"),(0,Ec.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,Ec.throwIfNotString)(t,"url");let s=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=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Ah.SystemError("Redis client failed with 401: Unauthorized"):new Ah.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};si.StandardRedisClient=Rh;var Oh=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,Ec.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*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 Ah.SystemError("The in-memory redis client only supports /rate-limit calls")}};si.InMemoryRedisClient=Oh});var z_=b(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.RateLimitInboundPolicy=void 0;var VN=Ur(),GN=Wt(),BN=xo(),Ut=k(),KN=pe(),G_=Ze(),ro=oe(),B_=V_(),K_=st(),wc=(0,VN.debug)("zuplo:policies:RateLimitInboundPolicy"),JN="strict",zN=o(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"),WN=o(async e=>({key:`ip-${zN(e)}`}),"getIP"),QN=o(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),YN=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),vc;function ZN(e,t){let r;if(vc)return vc;if(ro.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new B_.InMemoryRedisClient,vc=r,r;let{authApiJWT:n,redisURL:i}=ro.Environment.instance;if(!(0,K_.isString)(i))throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,K_.isString)(n))throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=B_.StandardRedisClient.initialize(i,n,ro.Environment.instance.deploymentName??"unknown",ro.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return vc=r,r}o(ZN,"getRedisClient");async function J_(e,t,r,n,i){let s=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:e}),requestId:i})}o(J_,"getCountAndUpdateExpiry");function XN(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new Ut.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 Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Ut.RuntimeError(u)}return c},"outerFunction")}o(XN,"wrapUserFunction");var ex="Retry-After",tx=o(async(e,t,r,n)=>{let i=Date.now(),s=G_.SystemLogMap.getLogger(t),a=o((u,l)=>{if(r.throwOnFailure)throw new Ut.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[ex]=l.toString()),KN.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:XN(r,n),user:QN,ip:WN,all:YN}[r.rateLimitBy],d=await l(e,t,n),p=d.key,h=d.requestsAllowed??r.requestsAllowed,f=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",_=ZN(n,s),O=`bucket/${ro.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??JN)==="async"){let R=await(0,GN.getPolicyCacheName)(n,r),K=new BN.ZoneCache(R,{logger:G_.SystemLogMap.getLogger(t)}),w=J_(O,f,_,s,t.requestId),S=await K.get(O);if(S!==void 0&&S<=Date.now()){wc(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${O}' (async mode)`);let x=Math.round((S-Date.now())/1e3);return c(y,x)}return t.addEventListener("responseSending",x=>{try{let E=x,P=E.mutableResponse;E.mutableResponse=(async()=>{let C=await w;if(C.count>h){let H=Date.now()+C.ttlSeconds*1e3,D=K.put(O,H,C.ttlSeconds).catch(X=>{throw s.error(new Ut.SystemError("Error caching rate limit result.",{cause:X})),X});return t.waitUntil(D),wc(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${O}' (async mode)`),c(y,C.ttlSeconds)}return P})()}catch(E){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,E)}}),e}let v=await J_(O,f,_,s,t.requestId);return v.count>h?(wc(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${O}' (strict mode)`),c(y,v.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;wc(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Tc.RateLimitInboundPolicy=tx});var Z_=b(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.ReadmeMetricsInboundPolicy=void 0;var rx=Oe(),Nh=oe(),W_=sr(),xh;function Q_(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}o(Q_,"headersToNameValuePairs");function nx(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}o(nx,"queryToNameValueParis");function ix(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}o(ix,"parseIntOrUndefined");var Y_={};async function ox(e,t,r,n){let i=new Date,s=Date.now();return xh||(xh={name:"zuplo",version:Nh.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Nh.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,W_.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,W_.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Nh.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:xh,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:Q_(e.headers),queryString:nx(e.query)},response:{status:a.status,statusText:a.statusText,headers:Q_(a.headers),content:{size:ix(e.headers.get("content-length"))}}}]}}},d=Y_[r.apiKey];if(!d){let p=r.apiKey;d=new rx.BatchDispatch("readme-metering-inbound-policy",10,async h=>{try{let f=r.url??"https://metrics.readme.io/request",y=await fetch(f,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(f){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),Y_[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}o(ox,"ReadmeMetricsInboundPolicy");Sc.ReadmeMetricsInboundPolicy=ox});var X_=b(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.RemoveHeadersInboundPolicy=void 0;var sx=k(),ax=Be(),cx=o(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new sx.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(e.headers);return i.forEach(c=>{s.delete(c)}),new ax.ZuploRequest(e,{headers:s})},"RemoveHeadersInboundPolicy");Ic.RemoveHeadersInboundPolicy=cx});var eE=b(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.RemoveHeadersOutboundPolicy=void 0;var ux=k(),lx=o(async(e,t,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new ux.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return s.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Pc.RemoveHeadersOutboundPolicy=lx});var tE=b(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.RemoveQueryParamsInboundPolicy=void 0;var dx=k(),px=Be(),hx=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new dx.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(e.url);return i.forEach(c=>{s.searchParams.delete(c)}),new px.ZuploRequest(s.toString(),e)},"RemoveQueryParamsInboundPolicy");Ac.RemoveQueryParamsInboundPolicy=hx});var rE=b(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.ReplaceStringOutboundPolicy=void 0;var fx=o(async(e,t,r,n)=>{let i=await e.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Rc.ReplaceStringOutboundPolicy=fx});var iE=b(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.RequestSizeLimitInboundPolicy=void 0;var nE=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),mx=o(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?nE():s&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?nE():e},"RequestSizeLimitInboundPolicy");Oc.RequestSizeLimitInboundPolicy=mx});var Nc=b(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.sanitizedIdentifierName=lt.getIdForRefSchema=lt.getIdForRequestBodySchema=lt.getIdForParameterSchema=lt.getRawOperationDataIdentifierName=void 0;function yx(e,t,r){return`_${tn(e+"_"+t+"_"+r)}`}o(yx,"getRawOperationDataIdentifierName");lt.getRawOperationDataIdentifierName=yx;function gx(e,t,r,n){return`_${tn(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(gx,"getIdForParameterSchema");lt.getIdForParameterSchema=gx;function bx(e,t,r){return`_${tn(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${tn(r.toLowerCase())}`}o(bx,"getIdForRequestBodySchema");lt.getIdForRequestBodySchema=bx;function _x(e,t){return`_${tn(e)}__${tn(t)}`}o(_x,"getIdForRefSchema");lt.getIdForRefSchema=_x;function tn(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("")}o(tn,"sanitizedIdentifierName");lt.sanitizedIdentifierName=tn});var no=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.getErrorsFromValidator=qe.shouldReject=qe.shouldLog=qe.logErrors=qe.validateParameters=qe.getParametersForOperation=void 0;var Ex=kr(),wx=Nc(),vx=o(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");qe.getParametersForOperation=vx;var Tx=o((e,t,r,n,i)=>{let s=[],a=!0,c=[];return e.forEach(u=>{let l=u.required||i==="path";if(l&&!t[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!t[u.name])){let d=(0,wx.getIdForParameterSchema)(r,n,i,u.name),p=Ex.Gateway.instance.schemaValidator[d],h=p(t[u.name]),f=(0,qe.getErrorsFromValidator)(p.errors);h||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${f.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");qe.validateParameters=Tx;var Sx=o((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");qe.logErrors=Sx;var Ix=o(e=>e==="log-only"||e==="reject-and-log","shouldLog");qe.shouldLog=Ix;var Px=o(e=>e==="reject-only"||e==="reject-and-log","shouldReject");qe.shouldReject=Px;var Ax=o(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");qe.getErrorsFromValidator=Ax});var oE=b(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.handleBodyValidation=void 0;var Rx=kr(),xc=pe(),Ox=Nc(),et=no();async function Nx(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(f){let y=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,_=xc.HttpProblems.badRequest(t,e,{detail:`${y}, see errors property for more details`,errors:`${f}`});if((0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",y,[n],f),(0,et.shouldReject)(r.validateBody))return _}if(!t.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,y=xc.HttpProblems.badRequest(t,e,{detail:f});return(0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",f,[n],[f]),(0,et.shouldReject)(r.validateBody)?y:void 0}let i=t.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,Ox.getIdForRequestBodySchema)(e.route.path,t.method,i),c=Rx.Gateway.instance.schemaValidator[a];if(!c){let f=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,y=xc.HttpProblems.badRequest(t,e,{detail:f});return(0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",f,[n],[f]),(0,et.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,et.getErrorsFromValidator)(l),h=xc.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",d,[n],p),(0,et.shouldReject)(r.validateBody))return h}o(Nx,"handleBodyValidation");Cc.handleBodyValidation=Nx});var sE=b(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.handleHeadersValidation=void 0;var xx=pe(),io=no();function Cx(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,io.getParametersForOperation)(e),s=(0,io.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=xx.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,io.shouldLog)(r.validateHeaders)&&(0,io.logErrors)(e,r.logLevel??"info",a,s.invalidValues,s.errors),(0,io.shouldReject)(r.validateHeaders))return c}}o(Cx,"handleHeadersValidation");Dc.handleHeadersValidation=Cx});var aE=b(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.handlePathParameterValidation=void 0;var Dx=pe(),oo=no();function Lx(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,oo.getParametersForOperation)(e),i=(0,oo.validateParameters)(n.filter(s=>s.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=Dx.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,oo.shouldLog)(r.validatePathParameters)&&(0,oo.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,oo.shouldReject)(r.validatePathParameters))return a}}o(Lx,"handlePathParameterValidation");Lc.handlePathParameterValidation=Lx});var cE=b(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.handleQueryParameterValidation=void 0;var Mx=pe(),so=no();function Ux(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,so.getParametersForOperation)(e),i=(0,so.validateParameters)(n.filter(s=>s.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=Mx.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,so.shouldLog)(r.validateQueryParameters)&&(0,so.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,so.shouldReject)(r.validateQueryParameters))return a}}o(Ux,"handleQueryParameterValidation");Mc.handleQueryParameterValidation=Ux});var uE=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.SchemaBasedRequestValidation=rn.RequestValidationInboundPolicy=void 0;var kx=oE(),Fx=sE(),Hx=aE(),qx=cE(),$x=o(async(e,t,r)=>{let n=(0,qx.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,Hx.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,Fx.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,kx.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");rn.RequestValidationInboundPolicy=$x;rn.SchemaBasedRequestValidation=rn.RequestValidationInboundPolicy});var lE=b(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.RequireOriginInboundPolicy=void 0;var jx=k(),Vx=pe(),Gx=o(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new jx.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 s=e.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Vx.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");Uc.RequireOriginInboundPolicy=Gx});var dE=b(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.SetBodyInboundPolicy=void 0;var Bx=Be(),Kx=o(async(e,t,r)=>new Bx.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");kc.SetBodyInboundPolicy=Kx});var hE=b(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.SetHeadersInboundPolicy=void 0;var pE=k(),Jx=Be(),zx=o(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new pE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new pE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Jx.ZuploRequest(e,{headers:s})},"SetHeadersInboundPolicy");Fc.SetHeadersInboundPolicy=zx});var mE=b(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.SetHeadersOutboundPolicy=void 0;var fE=k(),Wx=o(async(e,t,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new fE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new fE.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");Hc.SetHeadersOutboundPolicy=Wx});var gE=b(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.SetQueryParamsInboundPolicy=void 0;var yE=k(),Qx=Be(),Yx=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new yE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new yE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new Qx.ZuploRequest(s.toString(),e)},"SetQueryParamsInboundPolicy");qc.SetQueryParamsInboundPolicy=Yx});var bE=b($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.SetStatusOutboundPolicy=void 0;var Zx=o(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");$c.SetStatusOutboundPolicy=Zx});var _E=b(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.SleepInboundPolicy=void 0;var Xx=k(),eC=o(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),tC=o(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Xx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await eC(r.sleepInMs),e},"SleepInboundPolicy");jc.SleepInboundPolicy=tC});var wE=b(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.SupabaseJwtInboundPolicy=void 0;var EE=k(),rC=pe(),nC=Be(),iC=Mt(),oC=Qt(),sC=o(async(e,t,r,n)=>{(0,iC.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,oC.OpenIdJwtInboundPolicy)(e,t,i,n);if(s instanceof Response)return s;if(!(s instanceof nC.ZuploRequest))throw new EE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=e.user?.data.app_metadata;if(!c)throw new EE.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?rC.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Vc.SupabaseJwtInboundPolicy=sC});var TE=b(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var aC=Wt(),cC=er(),vE=k(),uC=Cn(),lC=Mt(),dC=o(async(e,t,r,n)=>{(0,lC.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,aC.getPolicyCacheName)(n,r),s=new cC.MemoryZoneReadThroughCache(i,t),a=await s.get(n);if(!a){let c=await pC(r,t);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");Gc.UpstreamAzureAdServiceAuthInboundPolicy=dC;async function pC(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,uC.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 s=await n.text();t.log.error("Could not get token from Azure AD",s)}catch{}throw new vE.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 vE.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(pC,"getAccessToken")});var IE=b(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var hC=Wt(),fC=er(),mC=k(),Ch=Dn(),yC=Mt(),SE="https://accounts.google.com/o/oauth2/token",Dh,gC=o(async(e,t,r,n)=>{(0,yC.optionValidator)(r,n).required("serviceAccountJson","string"),Dh||(Dh=await Ch.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(" ")},s=await(0,hC.getPolicyCacheName)(n,r),a=new fC.MemoryZoneReadThroughCache(s,t),c=await a.get(n);if(!c){let u=await(0,Ch.getTokenFromGcpServiceAccount)({serviceAccount:Dh,audience:SE,payload:i}),l=await(0,Ch.exchangeGgpJwtForIdToken)(SE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new mC.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");Bc.UpstreamFirebaseAdminAuthInboundPolicy=gC});var PE=b(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var bC=Wt(),_C=er(),ai=k(),EC=hh(),Lh=Dn(),wC=sr(),vC=Mt(),TC="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",SC=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Mh,IC=o(async(e,t,r,n)=>{if((0,vC.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new ai.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(SC.indexOf(p)!==-1)throw new ai.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Mh||(Mh=await Lh.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!e.user)throw new ai.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new ai.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,wC.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new ai.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,bC.getPolicyCacheName)(n,r),c=new _C.MemoryZoneReadThroughCache(a,t),u={uid:s,claims:i},l=await(0,EC.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Lh.getTokenFromGcpServiceAccount)({serviceAccount:Mh,audience:TC,payload:u}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,f=await(0,Lh.exchangeFirebaseJwtForIdToken)(h,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!f.idToken)throw new ai.RuntimeError("Invalid token response from Firebase");d=f.idToken,c.put(l,d,(f.expiresIn?parseInt(f.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");Kc.UpstreamFirebaseUserAuthInboundPolicy=IC});var RE=b(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.UpstreamGcpJwtInboundPolicy=void 0;var AE=Dn(),PC=Mt(),Uh,AC=o(async(e,t,r,n)=>{(0,PC.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),Uh||(Uh=await AE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,AE.getTokenFromGcpServiceAccount)({serviceAccount:Uh,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");Jc.UpstreamGcpJwtInboundPolicy=AC});var NE=b(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.UpstreamGcpServiceAuthInboundPolicy=void 0;var RC=Wt(),OC=Vu(),NC=er(),ao=k(),kh=Dn(),xC=sr(),CC=Mt(),OE="https://www.googleapis.com/oauth2/v4/token",Fh,DC=o(async(e,t,r,n)=>{(0,CC.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Fh||(Fh=await kh.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new ao.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,xC.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof ao.ConfigurationError?new ao.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,RC.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new OC.MemoryCache(s):a=new NC.MemoryZoneReadThroughCache(s,t);let c=await a.get(n);if(!c){let u=await(0,kh.getTokenFromGcpServiceAccount)({serviceAccount:Fh,audience:OE,payload:i}),l=await(0,kh.exchangeGgpJwtForIdToken)(OE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new ao.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new ao.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamGcpServiceAuthInboundPolicy");zc.UpstreamGcpServiceAuthInboundPolicy=DC});var CE=b(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.ValidateJsonSchemaInbound=void 0;var LC=k(),xE=pe(),MC=o(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return xE.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 LC.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 xE.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");Wc.ValidateJsonSchemaInbound=MC});var LE=b((zK,DE)=>{"use strict";var UC=Object.defineProperty,J=o((e,t)=>UC(e,"name",{value:t,configurable:!0}),"u"),Rr=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"E"),kC=Rr(e=>{var t={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,i){return i},attributeValueProcessor:function(n,i){return i},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,i,s){return n}},r=J(function(n){return Object.assign({},t,n)},"buildOptions");e.buildOptions=r,e.defaultOptions=t}),Hh=Rr(e=>{"use strict";var t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+t+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=J(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let h=d.length;for(let f=0;f<h;f++)p.push(d[f]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=J(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let h=0;h<p;h++)l==="strict"?c[d[h]]=[u[d[h]]]:c[d[h]]=u[d[h]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=n}),FC=Rr((e,t)=>{"use strict";var r=class{static{o(this,"P")}static{J(this,"XmlNode")}constructor(n){this.tagname=n,this.child=[],this[":@"]={}}add(n,i){n==="__proto__"&&(n="#__proto__"),this.child.push({[n]:i})}addChild(n){n.tagname==="__proto__"&&(n.tagname="#__proto__"),n[":@"]&&Object.keys(n[":@"]).length>0?this.child.push({[n.tagname]:n.child,":@":n[":@"]}):this.child.push({[n.tagname]:n.child})}};t.exports=r}),HC=Rr((e,t)=>{var r=Hh();function n(p,h){let f={};if(p[h+3]==="O"&&p[h+4]==="C"&&p[h+5]==="T"&&p[h+6]==="Y"&&p[h+7]==="P"&&p[h+8]==="E"){h=h+9;let y=1,_=!1,I=!1,O="";for(;h<p.length;h++)if(p[h]==="<"&&!I){if(_&&a(p,h))h+=7,[entityName,val,h]=i(p,h+1),val.indexOf("&")===-1&&(f[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(_&&c(p,h))h+=8;else if(_&&u(p,h))h+=8;else if(_&&l(p,h))h+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");y++,O=""}else if(p[h]===">"){if(I?p[h-1]==="-"&&p[h-2]==="-"&&(I=!1,y--):y--,y===0)break}else p[h]==="["?_=!0:O+=p[h];if(y!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:f,i:h}}o(n,"ue"),J(n,"readDocType");function i(p,h){let f="";for(;h<p.length&&p[h]!=="'"&&p[h]!=='"';h++)f+=p[h];if(f=f.trim(),f.indexOf(" ")!==-1)throw new Error("External entites are not supported");let y=p[h++],_="";for(;h<p.length&&p[h]!==y;h++)_+=p[h];return[f,_,h]}o(i,"le"),J(i,"readEntityExp");function s(p,h){return p[h+1]==="!"&&p[h+2]==="-"&&p[h+3]==="-"}o(s,"ce"),J(s,"isComment");function a(p,h){return p[h+1]==="!"&&p[h+2]==="E"&&p[h+3]==="N"&&p[h+4]==="T"&&p[h+5]==="I"&&p[h+6]==="T"&&p[h+7]==="Y"}o(a,"de"),J(a,"isEntity");function c(p,h){return p[h+1]==="!"&&p[h+2]==="E"&&p[h+3]==="L"&&p[h+4]==="E"&&p[h+5]==="M"&&p[h+6]==="E"&&p[h+7]==="N"&&p[h+8]==="T"}o(c,"ge"),J(c,"isElement");function u(p,h){return p[h+1]==="!"&&p[h+2]==="A"&&p[h+3]==="T"&&p[h+4]==="T"&&p[h+5]==="L"&&p[h+6]==="I"&&p[h+7]==="S"&&p[h+8]==="T"}o(u,"ae"),J(u,"isAttlist");function l(p,h){return p[h+1]==="!"&&p[h+2]==="N"&&p[h+3]==="O"&&p[h+4]==="T"&&p[h+5]==="A"&&p[h+6]==="T"&&p[h+7]==="I"&&p[h+8]==="O"&&p[h+9]==="N"}o(l,"he"),J(l,"isNotation");function d(p){if(r.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}o(d,"pe"),J(d,"validateEntityName"),t.exports=n}),qC=Rr((e,t)=>{var r=/^[-+]?0x[a-fA-F0-9]+$/,n=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var i={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(c,u={}){if(u=Object.assign({},i,u),!c||typeof c!="string")return c;let l=c.trim();if(u.skipLike!==void 0&&u.skipLike.test(l))return c;if(u.hex&&r.test(l))return Number.parseInt(l,16);{let d=n.exec(l);if(d){let p=d[1],h=d[2],f=a(d[3]),y=d[4]||d[6];if(!u.leadingZeros&&h.length>0&&p&&l[2]!=="."||!u.leadingZeros&&h.length>0&&!p&&l[1]!==".")return c;{let _=Number(l),I=""+_;return I.search(/[eE]/)!==-1||y?u.eNotation?_:c:l.indexOf(".")!==-1?I==="0"&&f===""||I===f||p&&I==="-"+f?_:c:h?f===I||p+f===I?_:c:l===I||l===p+I?_:c}}else return c}}o(s,"Te"),J(s,"toNumber");function a(c){return c&&c.indexOf(".")!==-1&&(c=c.replace(/0+$/,""),c==="."?c="0":c[0]==="."?c="0"+c:c[c.length-1]==="."&&(c=c.substr(0,c.length-1))),c}o(a,"ye"),J(a,"trimZeros"),t.exports=s}),$C=Rr((e,t)=>{"use strict";var r=Hh(),n=FC(),i=HC(),s=qC(),a=class{static{o(this,"C")}static{J(this,"OrderedObjParser")}constructor(w){this.options=w,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"}},this.addExternalEntities=c,this.parseXml=h,this.parseTextData=u,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=y,this.readStopNodeData=R,this.saveTextToParentTag=_,this.addChild=f}};function c(w){let S=Object.keys(w);for(let x=0;x<S.length;x++){let E=S[x];this.lastEntities[E]={regex:new RegExp("&"+E+";","g"),val:w[E]}}}o(c,"Oe"),J(c,"addExternalEntities");function u(w,S,x,E,P,C,H){if(w!==void 0&&(this.options.trimValues&&!E&&(w=w.trim()),w.length>0)){H||(w=this.replaceEntitiesValue(w));let D=this.options.tagValueProcessor(S,w,x,P,C);return D==null?w:typeof D!=typeof w||D!==w?D:this.options.trimValues?K(w,this.options.parseTagValue,this.options.numberParseOptions):w.trim()===w?K(w,this.options.parseTagValue,this.options.numberParseOptions):w}}o(u,"Ae"),J(u,"parseTextData");function l(w){if(this.options.removeNSPrefix){let S=w.split(":"),x=w.charAt(0)==="/"?"/":"";if(S[0]==="xmlns")return"";S.length===2&&(w=x+S[1])}return w}o(l,"ve"),J(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(w,S,x){if(!this.options.ignoreAttributes&&typeof w=="string"){let E=r.getAllMatches(w,d),P=E.length,C={};for(let H=0;H<P;H++){let D=this.resolveNameSpace(E[H][1]),X=E[H][4],ie=this.options.attributeNamePrefix+D;if(D.length)if(this.options.transformAttributeName&&(ie=this.options.transformAttributeName(ie)),ie==="__proto__"&&(ie="#__proto__"),X!==void 0){this.options.trimValues&&(X=X.trim()),X=this.replaceEntitiesValue(X);let Ge=this.options.attributeValueProcessor(D,X,S);Ge==null?C[ie]=X:typeof Ge!=typeof X||Ge!==X?C[ie]=Ge:C[ie]=K(X,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(C[ie]=!0)}if(!Object.keys(C).length)return;if(this.options.attributesGroupName){let H={};return H[this.options.attributesGroupName]=C,H}return C}}o(p,"Ce"),J(p,"buildAttributesMap");var h=J(function(w){w=w.replace(/\r\n?/g,`
|
|
74
|
+
`+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Wr.StripeSignatureVerificationError(t,e,{message:"Timestamp outside the tolerance zone"});return!0}o(wR,"validateComputedSignature");function vR(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:[]})}o(vR,"parseHeader");function TR(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}o(TR,"secureCompare");async function Vb(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)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=Gp[s[c]];return a.join("")}o(Vb,"computeHMACSignatureAsync");Wn.computeHMACSignatureAsync=Vb;var Gp=new Array(256);for(let e=0;e<Gp.length;e++)Gp[e]=e.toString(16).padStart(2,"0")});var Mt=b(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.optionValidator=void 0;var Qn=k(),SR=st();function IR(e,t){if(!(0,SR.isObject)(e))throw new Qn.ConfigurationError(`Options on policy '${t}' is expected to be an object. Received the type '${typeof e}'.`);let r=o((s,a,c)=>{let u=e[s];if(!(c&&u===void 0)){if(u===void 0)throw new Qn.ConfigurationError(`Value of '${String(s)}' 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 Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Qn.ConfigurationError(`Value of '${String(s)}' 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 Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(IR,"optionValidator");ka.optionValidator=IR});var Kp=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.StripeWebhookVerificationInboundPolicy=void 0;var PR=Pi(),AR=pe(),RR=Gb(),OR=Mt(),Bp=class extends PR.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(t,r){(0,OR.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=t.headers.get("stripe-signature");try{let i=await t.clone().text();await(0,RR.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){return r.log.error("Error validating stripe webhook",i),AR.HttpProblems.badRequest(t,r,{title:"Webhook Error",detail:i.message})}return t}};Fa.StripeWebhookVerificationInboundPolicy=Bp});var Kb=b(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.isStripeWebhookEvent=void 0;var Bb=st();function NR(e){return e!==null&&typeof e=="object"&&"id"in e&&(0,Bb.isString)(e.id)&&"type"in e&&(0,Bb.isString)(e.type)}o(NR,"isStripeWebhookEvent");Ha.isStripeWebhookEvent=NR});var Jb=b(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.MeteringPlugin=void 0;var xR=It(),Jp=class extends xR.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};qa.MeteringPlugin=Jp});var Qp=b(Wp=>{"use strict";Object.defineProperty(Wp,"__esModule",{value:!0});var zp=k(),CR={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 s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new zp.RuntimeError(s)}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 s="Error retrieving customer from Stripe API.";throw r.error(s,i),new zp.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new zp.RuntimeError(s)}return i}};Wp.default=CR});var zb=b(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.deleteConsumer=Ir.createConsumerInvite=Ir.createConsumer=void 0;var Yp=k(),Zp=Ze(),Xp=oe(),eh=Cn(),th="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function DR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=Xp.Environment.instance,u=new URL(`/v1/buckets/${e}/consumers`,th);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,eh.fetchRetry)({retryDelayMs:5,retries:2,logger:Zp.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let f="Error creating API Key Consumer";throw a.log.error(f,h),new Yp.RuntimeError(f)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:t,stripeProductId:r}),l}o(DR,"createConsumer");Ir.createConsumer=DR;async function LR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=Xp.Environment.instance,c=new URL(`/v1/buckets/${e}/consumers`,th);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,eh.fetchRetry)({retryDelayMs:5,retries:2,logger:Zp.SystemLogMap.getLogger(s)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new Yp.RuntimeError(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:t,stripeProductId:r}),u}o(LR,"createConsumerInvite");Ir.createConsumerInvite=LR;async function MR({apiKeyBucketName:e,consumerId:t,context:r}){let{authApiJWT:n}=Xp.Environment.instance,i=new URL(`/v1/buckets/${e}/consumers/${t}`,th);i.searchParams.set("with-api-key","true");let s=await(0,eh.fetchRetry)({retryDelayMs:5,retries:2,logger:Zp.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error deleting API Key Consumer";throw r.log.error(c,a),new Yp.RuntimeError(c)}return r.log.info(`Successfully deleted API Key Consumer '${t}`),t}o(MR,"deleteConsumer");Ir.deleteConsumer=MR});var $a=b(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.getSubscription=Ar.updateSubscription=Ar.createSubscription=void 0;var Pr=k(),rh=Ze(),nh=oe(),ih=Cn(),oh=st();async function UR({context:e,stripeSubscriptionId:t,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c}){let u={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:t,planExternalIds:[r],customerKey:n,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=nh.Environment.instance;if(!(0,oh.isNonEmptyString)(l))throw new Pr.SystemError("No Zuplo JWT token set.");let p=await(0,ih.fetchRetry)({retryDelayMs:5,retries:2,logger:rh.SystemLogMap.getLogger(e)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"POST",body:JSON.stringify(u)});if(!p.ok){let h="Error creating metering subscription.",f;try{f=await p.json()}catch{f={status:p.status,statusText:p.statusText}}throw e.log.error(h,f),new Pr.RuntimeError(h)}e.log.info("Successfully created/updated metering subscription.",u)}o(UR,"createSubscription");Ar.createSubscription=UR;async function kR({context:e,meteringSubscriptionId:t,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=nh.Environment.instance;if(!(0,oh.isNonEmptyString)(i))throw new Pr.SystemError("No Zuplo JWT token set.");let a=await(0,ih.fetchRetry)({retryDelayMs:5,retries:2,logger:rh.SystemLogMap.getLogger(e)},`${s}/internal/v1/metering/${r}/subscriptions/${t}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating metering subscription to '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw e.log.error(c,u),new Pr.RuntimeError(c)}e.log.info(`Successfully update metering subscription to '${JSON.stringify(n)}'.`)}o(kR,"updateSubscription");Ar.updateSubscription=kR;async function FR({context:e,stripeSubscriptionId:t,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=nh.Environment.instance;if(!(0,oh.isNonEmptyString)(i))throw new Pr.SystemError("No Zuplo JWT token set.");let a=await(0,ih.fetchRetry)({retryDelayMs:5,retries:2,logger:rh.SystemLogMap.getLogger(e)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${t}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":e.requestId},method:"GET"});if(!a.ok){let u="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw e.log.error(u,l),new Pr.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw e.log.error(u),new Pr.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw e.log.error(u),new Pr.RuntimeError(u)}return c.data[0]}o(FR,"getSubscription");Ar.getSubscription=FR});var sh=b(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.stripeStatusToMeteringStatus=void 0;function HR(e){return e.replaceAll("_","-")}o(HR,"stripeStatusToMeteringStatus");ja.stripeStatusToMeteringStatus=HR});var Wb=b(Qi=>{"use strict";var qR=Qi&&Qi.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qi,"__esModule",{value:!0});var Qr=pe(),$R=qR(Qp()),ah=zb(),jR=$a(),VR=sh();async function GR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return t.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)u=await(0,ah.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:r.data.object.metadata.zuplo_created_by_email,managerSub:r.data.object.metadata.zuplo_created_by_sub,context:t});else{let l=await $R.default.getCustomer({logger:t.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!l.email)return t.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,ah.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l.email,context:t})}if(!u)return Qr.HttpProblems.internalServerError(e,t,{detail:"No consumer was created, skipping creation of subscription"});try{let l=(0,VR.stripeStatusToMeteringStatus)(r.data.object.status);await(0,jR.createSubscription)({context:t,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await(0,ah.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:t}),Qr.HttpProblems.internalServerError(e,t,{detail:l.message})}return Qr.HttpProblems.ok(e,t)}o(GR,"onCustomerSubscriptionCreated");Qi.default=GR});var Yb=b(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var ch=pe(),Qb=$a();async function BR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),ch.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),ch.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,Qb.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,Qb.updateSubscription)({context:t,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),ch.HttpProblems.ok(e,t)}o(BR,"onCustomerSubscriptionDeleted");uh.default=BR});var Zb=b(Zi=>{"use strict";var KR=Zi&&Zi.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Zi,"__esModule",{value:!0});var Yi=pe(),JR=KR(Qp()),Va=$a(),zR=sh();async function WR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),Yi.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Yi.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){t.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,Va.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,zR.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,Va.updateSubscription)({context:t,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),Yi.HttpProblems.ok(e,t)}if(a.plan&&a.plan.product!==r.data.object.plan.product){t.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,Va.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,l=await JR.default.getUpcomingInvoice({customerId:s,logger:t.log,stripeSecretKey:n.stripeSecretKey});t.log.debug(`upcoming invoice: ${JSON.stringify(l)}`);let d=l.lines.data.filter(h=>(t.log.debug(`line item from invoice: ${JSON.stringify(h)}`),h.proration&&h.price.product===u)),p=0;return d.length===0?t.log.warn(`Not able to calculate proration details on plan change for subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,Va.updateSubscription)({context:t,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),Yi.HttpProblems.ok(e,t)}}return t.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),Yi.HttpProblems.badRequest(e,t,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(WR,"onCustomerSubscriptionUpdated");Zi.default=WR});var e_=b(Yn=>{"use strict";var dh=Yn&&Yn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yn,"__esModule",{value:!0});Yn.StripeMeteringPlugin=void 0;var Ga=Ki(),Ba=k(),QR=jt(),YR=Kp(),Xb=pe(),ZR=ir(),XR=mn(),eO=hl(),tO=ft(),rO=oe(),nO=Kb(),iO=Jb(),oO=dh(Wb()),sO=dh(Yb()),aO=dh(Zb()),lh=class extends iO.MeteringPlugin{static{o(this,"StripeMeteringPlugin")}options;constructor(t){super(),this.options=t}registerRoutes(t,r){let n=o(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(!rO.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(!cO(p))throw new Ba.ConfigurationError(`StripeMeteringPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let h=await c.json();if(!(0,nO.isStripeWebhookEvent)(h))return Xb.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await(0,oO.default)(c,u,h,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,aO.default)(c,u,h,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,sO.default)(c,u,h,{meteringBucketId:l});default:return Xb.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=(0,XR.createInternalPolicyProcessor)({inboundPolicies:[new YR.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),s=new QR.Pipeline({processors:[ZR.metricsProcessor,i],handler:n,gateway:r}),a=new tO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:eO.SystemRouteName.StripePlugin});t.addRoute(a,s.execute)}};Yn.StripeMeteringPlugin=lh;function cO(e){return e!==null&&typeof e=="string"&&["us-central1","europe-west4"].includes(e)}o(cO,"isMetricsRegion")});var o_=b(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.AmberfloMeteringInboundPolicy=Zn.AmberfloMeteringPolicy=void 0;var t_=k(),uO=Oe(),r_=sr(),i_=new WeakMap,n_={},ph=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){i_.set(t,r)}};Zn.AmberfloMeteringPolicy=ph;async function lO(e,t,r,n){if(!r.statusCodes)throw new t_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,r_.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=i_.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new t_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,r_.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)},h=n_[r.apiKey];if(!h){let f=r.apiKey,y=e.headers.get("zm-test-id")??"";h=new uO.BatchDispatch("amberflo-ingest-meter",10,async _=>{try{let I=r.url??"https://app.amberflo.io/ingest",O=await fetch(I,{method:"POST",body:JSON.stringify(_),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});O.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${O.status}: ${await O.text()}`)}catch(I){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${I.message}`),I}}),n_[f]=h}h.enqueue(p),t.waitUntil(h.waitUntilFlushed())}}),e}o(lO,"AmberfloMeteringInboundPolicy");Zn.AmberfloMeteringInboundPolicy=lO});var hh=b(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.sha256=void 0;async function dO(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("")}o(dO,"sha256");Ka.sha256=dO});var Wt=b(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.getPolicyCacheName=void 0;var pO=hh(),s_=new Map;async function hO(e,t){let r,n=s_.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,pO.sha256)(JSON.stringify({policyName:e,options:t}))}`,s_.set(e,r)),r}o(hO,"getPolicyCacheName");Ja.getPolicyCacheName=hO});var yh=b(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.ApiKeyInboundPolicy=void 0;var fO=Wt(),mO=er(),a_=Ki(),fh=k(),yO=Vt(),c_=Ze(),mh=oe(),gO=Cn(),u_="key-metadata-cache-type";function bO(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}o(bO,"getKeyValue");async function _O(e,t,r,n){if(!r.bucketName)if(a_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=a_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new fh.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 fh.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(I=>i.allowUnauthenticatedRequests?e:yO.HttpProblems.unauthorized(e,t,{detail:I}),"unauthorizedResponse"),a=e.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=bO(a,i);if(!c||c==="")return s("No key present");let u=await EO(c),l=await(0,fO.getPolicyCacheName)(n,i),d=new mO.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!==u_&&c_.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:c},f=await(0,gO.fetchRetry)({retryDelayMs:5,retries:2,logger:c_.SystemLogMap.getLogger(t)},`${mh.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":mh.Environment.instance.deploymentName??"unknown","User-Agent":mh.Environment.instance.systemUserAgent},body:JSON.stringify(h)});if(f.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(f.status!==200){try{let I=await f.text(),O=JSON.parse(I);t.log.error("Unexpected response from key service",O)}catch{t.log.error("Invalid response from key service")}throw new fh.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${f.status}`)}let y=await f.json(),_={isValid:!0,typeId:u_,user:{sub:y.name,data:y.metadata}};return e.user=_.user,d.put(u,_,i.cacheTtlSeconds),e}o(_O,"ApiKeyInboundPolicy");za.ApiKeyInboundPolicy=_O;async function EO(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(EO,"hashValue")});var l_=b(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.ApiAuthKeyInboundPolicy=void 0;var wO=yh();Wa.ApiAuthKeyInboundPolicy=wO.ApiKeyInboundPolicy});var Qt=b(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.OpenIdJwtInboundPolicy=void 0;var bh=(Ys(),Po(Qs)),_h=k(),vO=pe(),gh={},TO=o(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new _h.ConfigurationError("Invalid State - jwkUrl not set");gh[t.jwkUrl]||(gh[t.jwkUrl]=(0,bh.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,bh.jwtVerify)(e,gh[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),SO=o(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 s=new TextEncoder().encode(t.secret);r=new Uint8Array(s)}else r=t.secret;let{payload:n}=await(0,bh.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),IO=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),s="bearer ",a=o(h=>vO.HttpProblems.unauthorized(e,t,{detail:h}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new _h.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new _h.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?TO:SO,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=i.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await c(h,r)}catch(f){let y=new URL(e.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${y.pathname} `,f):t.log.warn(`Invalid token on: ${e.method} ${y.pathname}`,f),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");Qa.OpenIdJwtInboundPolicy=IO});var d_=b(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.Auth0JwtInboundPolicy=void 0;var PO=Qt(),AO=o(async(e,t,r,n)=>(0,PO.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");Ya.Auth0JwtInboundPolicy=AO});var p_=b(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.BasicAuthInboundPolicy=void 0;var RO=pe(),OO=o(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",s=o(l=>RO.HttpProblems.unauthorized(e,t,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(_=>_.username===h&&_.password===f);return y||await s("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");Za.BasicAuthInboundPolicy=OO});var h_=b(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.CachingInboundPolicy=void 0;var NO=Wt(),xO=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function CO(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(CO,"digestMessage");var DO=o(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 CO(JSON.stringify(n)),s=new URL(e.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function LO(e,t,r,n){let i=await(0,NO.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await DO(e,r),u=await s.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 h=r?.expirationSecondsTtl??60,f=new Response(p.body,p);xO.forEach(y=>f.headers.delete(y)),f.headers.set("cache-control",`s-maxage=${h}`),t.waitUntil(s.put(c,f))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}o(LO,"CachingInboundPolicy");Xa.CachingInboundPolicy=LO});var f_=b(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.ChangeMethodInboundPolicy=void 0;var MO=k(),UO=Be(),kO=o(async(e,t,r,n)=>{if(!r.method)throw new MO.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new UO.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");ec.ChangeMethodInboundPolicy=kO});var m_=b(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.ClearHeadersInboundPolicy=void 0;var FO=Be(),HO=o(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 FO.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");tc.ClearHeadersInboundPolicy=HO});var y_=b(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ClearHeadersOutboundPolicy=void 0;var qO=o(async(e,t,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&s.set(c,u)}),new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");rc.ClearHeadersOutboundPolicy=qO});var g_=b(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ClerkJwtInboundPolicy=void 0;var $O=Qt(),jO=o(async(e,t,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,$O.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");nc.ClerkJwtInboundPolicy=jO});var __=b(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.CognitoJwtInboundPolicy=void 0;var b_=k(),VO=Qt(),GO=o(async(e,t,r,n)=>{if(!r.userPoolId)throw new b_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new b_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,VO.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");ic.CognitoJwtInboundPolicy=GO});var w_=b(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.CompositeInboundPolicy=void 0;var BO=k(),KO=kr(),E_=mn(),JO=o(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new BO.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=KO.Gateway.instance,s=(0,E_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,E_.toStackedInboundHandler)(s)(e,t)},"CompositeInboundPolicy");oc.CompositeInboundPolicy=JO});var v_=b(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.CurityPhantomTokenInboundPolicy=void 0;var zO=Wt(),WO=er(),sc=pe(),QO=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return sc.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let s=YO(i);if(!s)return sc.HttpProblems.unauthorized(e,t,{detail:"Failed to parse token from Authorization header"});let a=await(0,zO.getPolicyCacheName)(n,r),c=new WO.MemoryZoneReadThroughCache(a,t),u=await c.get(s);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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(t.log.error(`Error introspecting token - ${l.status}: '${d}'`),sc.HttpProblems.internalServerError(e,t,{detail:"Problem encountered authorizing the HTTP request"})):sc.HttpProblems.unauthorized(e,t)}return e.headers.set("Authorization",`Bearer ${u}`),e},"CurityPhantomTokenInboundPolicy");ac.CurityPhantomTokenInboundPolicy=QO;function YO(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}o(YO,"getToken")});var T_=b(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.FirebaseJwtInboundPolicy=void 0;var ZO=Mt(),XO=Qt(),eN=o(async(e,t,r,n)=>((0,ZO.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,XO.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");cc.FirebaseJwtInboundPolicy=eN});var S_=b(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.FormDataToJsonInboundPolicy=void 0;var tN=Be(),rN=o(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=e.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))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 tN.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");uc.FormDataToJsonInboundPolicy=rN});var I_=b(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.GeoFilterInboundPolicy=void 0;var nN=k(),iN=pe(),Xn="__unknown__",oN=o(async(e,t,r,n)=>{let i={allow:{countries:ti(r.allow?.countries,"allow.countries",n),regionCodes:ti(r.allow?.regionCodes,"allow.regionCode",n),asns:ti(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ti(r.block?.countries,"block.countries",n),regionCodes:ti(r.block?.regionCodes,"block.regionCode",n),asns:ti(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=t.incomingRequestProperties.country?.toLowerCase()??Xn,a=t.incomingRequestProperties.regionCode?.toLowerCase()??Xn,c=t.incomingRequestProperties.asn?.toString()??Xn,u=i.ignoreUnknown&&s===Xn,l=i.ignoreUnknown&&a===Xn,d=i.ignoreUnknown&&c===Xn,p=i.allow.countries,h=i.allow.regionCodes,f=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||h.length>0&&!h.includes(a)&&!l||f.length>0&&!f.includes(c)&&!d)return ei(e,t,n,s,a,c);let y=i.block.countries,_=i.block.regionCodes,I=i.block.asns;return y.length>0&&y.includes(s)&&!u||_.length>0&&_.includes(a)&&!l||I.length>0&&I.includes(c)&&!d?ei(e,t,n,s,a,c):e},"GeoFilterInboundPolicy");lc.GeoFilterInboundPolicy=oN;function ei(e,t,r,n,i,s){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),iN.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:s}})}o(ei,"blockedResponse");function ti(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 nN.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}o(ti,"toLowerStringArray")});var P_=b(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.JWTScopeValidationInboundPolicy=void 0;var sN=o(async(e,t,r)=>{let n=e.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return e},"JWTScopeValidationInboundPolicy");dc.JWTScopeValidationInboundPolicy=sN});var R_=b(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.MockApiInboundPolicy=void 0;var aN=pe(),cN=o(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return Eh(n,e,t,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return Eh(n,e,t,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:c,contentName:l,exampleName:h,exampleValue:d[h]})})})}),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 A_(a[c])}else return a.length>0?A_(a[0]):Eh(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");pc.MockApiInboundPolicy=cN;function A_(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})}}o(A_,"generateResponse");var Eh=o((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return aN.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var D_=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.MoesifInboundPolicy=ri.setMoesifContext=void 0;var uN=k(),lN=Oe(),dN="Incoming",pN={logRequestBody:!0,logResponseBody:!0};function O_(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}o(O_,"headersToObject");function N_(){return new Date().toISOString()}o(N_,"timestamp");var wh=new WeakMap,hN={};function fN(e,t){let r=wh.get(e);r||(r=hN);let n=Object.assign({...r},t);wh.set(e,n)}o(fN,"setMoesifContext");ri.setMoesifContext=fN;async function x_(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}o(x_,"readBody");var mN={},vh;function C_(){if(!vh)throw new uN.RuntimeError("Invalid State - no _lastLogger");return vh}o(C_,"getLastLogger");function yN(e){let t=mN[e];return t||(t=new lN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);C_().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||C_().error({status:i.status,body:await i.text()})})),t}o(yN,"getDispatcher");async function gN(e,t,r,n){vh=t.log;let i=N_(),s=Object.assign(pN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await x_(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=yN(s.applicationId),d=e.headers.get("true-client-ip"),p=wh.get(t)??{},h={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:O_(e.headers)},f=s.logResponseBody?await x_(c,t):void 0,y={time:N_(),status:c.status,headers:O_(c.headers),body:f},_={request:h,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:dN};l.enqueue(_),t.waitUntil(l.waitUntilFlushed())}),e}o(gN,"MoesifInboundPolicy");ri.MoesifInboundPolicy=gN});var U_=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.consumeSubcriptionQuotas=ni.loadSubscription=void 0;var L_=Ze(),M_=oe();async function bN(e,t,r,n){let i=L_.SystemLogMap.getLogger(e),{authApiJWT:s,meteringServiceUrl:a}=M_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${t}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":e.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";e.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(bN,"loadSubscription");ni.loadSubscription=bN;async function _N(e,t,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=M_.Environment.instance,c=L_.SystemLogMap.getLogger(e);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${t}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":e.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";e.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){e.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(_N,"consumeSubcriptionQuotas");ni.consumeSubcriptionQuotas=_N});var k_=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.parseAllowedSubscriptionStatuses=ii.validateMeters=void 0;var Yr=k(),EN=sr(),wN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function vN(e,t){try{let r=[];for(let n in e)typeof e[n]!="number"&&!(Number.isInteger(e[n])&&/^-?\d+$/.test(e[n].toString()))&&r.push(n);if(r.length>0)throw new Yr.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof Yr.ConfigurationError?new Yr.ConfigurationError(`MonetizationInboundPolicy '${t}' - The property 'meters' is invalid. ${r.message}`):r}}o(vN,"validateMeters");ii.validateMeters=vN;function TN(e,t){if(e)try{if(e.length===0)throw new Yr.ConfigurationError("Must set valid subscription statuses");let r=(0,EN.parseValueToStringArray)(e),n=[];for(let i of r)wN.has(i)||n.push(i);if(n.length>0)throw new Yr.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return e}catch(r){throw r instanceof Yr.ConfigurationError?new Yr.ConfigurationError(`MonetizationInboundPolicy '${t}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(TN,"parseAllowedSubscriptionStatuses");ii.parseAllowedSubscriptionStatuses=TN});var H_=b(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.MonetizationInboundPolicy=void 0;var Zr=un(),Xr=cp(),hc=Ki(),Th=k(),SN=Pi(),en=pe(),IN=sr(),PN=Mt(),F_=U_(),fc=k_(),Sh=class extends SN.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(t){return Xr.ContextData.get(t,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(t,r){(0,fc.validateMeters)(r,"setMeters"),Xr.ContextData.set(t,Zr.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(t,r){if((0,PN.optionValidator)(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new Th.ConfigurationError(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let n=this.options.allowRequestsOverQuota??!1,i=Array.isArray(this.options.meterOnStatusCodes)?this.options.meterOnStatusCodes:(0,IN.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=Xr.ContextData.get(r,Zr.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,fc.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,fc.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(_,I,O)=>{let g=Xr.ContextData.get(O,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Th.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let R=Xr.ContextData.get(O,Zr.DYNAMIC_METERS_CONTEXT_DATA),K={...this.options.meters,...R};(0,fc.validateMeters)(K,this.policyName),i.includes(_.status)&&g&&K&&(O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(K)} on response status '${_.status}'`),await(0,F_.consumeSubcriptionQuotas)(O,g.id,this.policyName,this.options.bucketId,K))});let l=t.user;if(!l)return c?t:en.HttpProblems.unauthorized(t,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=hc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Th.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,F_.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?t:en.HttpProblems.unauthorized(t,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),en.HttpProblems.unauthorized(t,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),Xr.ContextData.set(r,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let h=Xr.ContextData.get(r,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!h)return c?t:(r.log.warn("Subscription is not available for user"),en.HttpProblems.paymentRequired(t,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return r.log.error(`Quota is not set up for subscription '${h.id}'`),en.HttpProblems.tooManyRequests(t,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(_=>!Object.keys(h.meters).includes(_));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),en.HttpProblems.tooManyRequests(t,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let _ of Object.keys(a))if(h.meters[_].consumed<=0&&!n)return en.HttpProblems.tooManyRequests(t,r,{detail:`Quota exceeded for meter '${_}'`,title:"Quota Exceeded"});return t}};mc.MonetizationInboundPolicy=Sh});var q_=b(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.OktaJwtInboundPolicy=void 0;var AN=Qt(),RN=o(async(e,t,r,n)=>(0,AN.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");yc.OktaJwtInboundPolicy=RN});var $_=b(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.PropelAuthJwtInboundPolicy=void 0;var ON=(Ys(),Po(Qs)),NN=Qt(),Ih,xN=o(async(e,t,r,n)=>{if(!Ih)try{Ih=await(0,ON.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,NN.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:Ih,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");gc.PropelAuthJwtInboundPolicy=xN});var j_=b(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var We=st(),ut=class extends Error{static{o(this,"ValidationError")}constructor(t){super(t)}};Z.ValidationError=ut;var Xi=class extends ut{static{o(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};Z.ArgumentUndefinedError=Xi;var eo=class extends ut{static{o(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};Z.ArgumentTypeError=eo;function CN(e,t){if((0,We.isUndefined)(e))throw new Xi(t)}o(CN,"throwIfUndefined");Z.throwIfUndefined=CN;function Ph(e,t){if((0,We.isUndefinedOrNull)(e))throw new Xi(t)}o(Ph,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=Ph;function DN(e,t){if(Ph(e,t),!(0,We.isString)(e))throw new eo(t,"string")}o(DN,"throwIfNotString");Z.throwIfNotString=DN;function LN(e,t){if(Ph(e,t),!(0,We.isNumber)(e))throw new eo(t,"number")}o(LN,"throwIfNotNumber");Z.throwIfNotNumber=LN;var to=class extends ut{static{o(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};Z.OptionUndefinedError=to;var oi=class extends ut{static{o(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=oi;function MN(e,t,r,n){if((0,We.isUndefined)(n))throw new to(e,t,r)}o(MN,"throwIfOptionUndefined");Z.throwIfOptionUndefined=MN;function bc(e,t,r,n){if((0,We.isUndefinedOrNull)(n))throw new to(e,t,r)}o(bc,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=bc;function UN(e,t,r,n){if(bc(e,t,r,n),!(0,We.isString)(n))throw new oi(e,t,r,"string")}o(UN,"throwIfOptionNotString");Z.throwIfOptionNotString=UN;function kN(e,t,r,n){if(bc(e,t,r,n),!(0,We.isNumber)(n))throw new oi(e,t,r,"number")}o(kN,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=kN;function FN(e,t,r,n){if(bc(e,t,r,n),!(0,We.isObject)(n))throw new oi(e,t,r,"object")}o(FN,"throwIfOptionNotObject");Z.throwIfOptionNotObject=FN;function HN(e,t){if((0,We.isUndefined)(e))throw new ut(t)}o(HN,"throwIfStateUndefined");Z.throwIfStateUndefined=HN;function _c(e,t){if((0,We.isUndefinedOrNull)(e))throw new ut(t)}o(_c,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=_c;function qN(e,t){if(_c(e,t),!(0,We.isString)(e))throw new ut(t);return!0}o(qN,"throwIfStateNotString");Z.throwIfStateNotString=qN;function $N(e,t){if(_c(e,t),!(0,We.isNumber)(e))throw new ut(t);return!0}o($N,"throwIfStateNotNumber");Z.throwIfStateNotNumber=$N;function jN(e,t){if(_c(e,t),!(0,We.isObject)(e))throw new ut(t);return!0}o(jN,"throwIfStateNotObject");Z.throwIfStateNotObject=jN});var V_=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.InMemoryRedisClient=si.StandardRedisClient=void 0;var Ah=k(),Ec=j_(),Rh=class e{static{o(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,Ec.throwIfNotString)(t,"redisClientUrl"),(0,Ec.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,Ec.throwIfNotString)(t,"url");let s=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=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Ah.SystemError("Redis client failed with 401: Unauthorized"):new Ah.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};si.StandardRedisClient=Rh;var Oh=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,Ec.throwIfNotString)(t,"url"),n==="POST"&&t==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*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 Ah.SystemError("The in-memory redis client only supports /rate-limit calls")}};si.InMemoryRedisClient=Oh});var z_=b(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.RateLimitInboundPolicy=void 0;var VN=Ur(),GN=Wt(),BN=xo(),Ut=k(),KN=pe(),G_=Ze(),ro=oe(),B_=V_(),K_=st(),wc=(0,VN.debug)("zuplo:policies:RateLimitInboundPolicy"),JN="strict",zN=o(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"),WN=o(async e=>({key:`ip-${zN(e)}`}),"getIP"),QN=o(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),YN=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),vc;function ZN(e,t){let r;if(vc)return vc;if(ro.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new B_.InMemoryRedisClient,vc=r,r;let{authApiJWT:n,redisURL:i}=ro.Environment.instance;if(!(0,K_.isString)(i))throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,K_.isString)(n))throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=B_.StandardRedisClient.initialize(i,n,ro.Environment.instance.deploymentName??"unknown",ro.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return vc=r,r}o(ZN,"getRedisClient");async function J_(e,t,r,n,i){let s=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:e}),requestId:i})}o(J_,"getCountAndUpdateExpiry");function XN(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new Ut.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 Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Ut.RuntimeError(u)}return c},"outerFunction")}o(XN,"wrapUserFunction");var ex="Retry-After",tx=o(async(e,t,r,n)=>{let i=Date.now(),s=G_.SystemLogMap.getLogger(t),a=o((u,l)=>{if(r.throwOnFailure)throw new Ut.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[ex]=l.toString()),KN.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:XN(r,n),user:QN,ip:WN,all:YN}[r.rateLimitBy],d=await l(e,t,n),p=d.key,h=d.requestsAllowed??r.requestsAllowed,f=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",_=ZN(n,s),O=`bucket/${ro.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??JN)==="async"){let R=await(0,GN.getPolicyCacheName)(n,r),K=new BN.ZoneCache(R,{logger:G_.SystemLogMap.getLogger(t)}),w=J_(O,f,_,s,t.requestId),S=await K.get(O);if(S!==void 0&&S<=Date.now()){wc(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${O}' (async mode)`);let x=Math.round((S-Date.now())/1e3);return c(y,x)}return t.addEventListener("responseSending",x=>{try{let E=x,P=E.mutableResponse;E.mutableResponse=(async()=>{let C=await w;if(C.count>h){let H=Date.now()+C.ttlSeconds*1e3,D=K.put(O,H,C.ttlSeconds).catch(X=>{throw s.error(new Ut.SystemError("Error caching rate limit result.",{cause:X})),X});return t.waitUntil(D),wc(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${O}' (async mode)`),c(y,C.ttlSeconds)}return P})()}catch(E){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,E)}}),e}let v=await J_(O,f,_,s,t.requestId);return v.count>h?(wc(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${O}' (strict mode)`),c(y,v.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;wc(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Tc.RateLimitInboundPolicy=tx});var Z_=b(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.ReadmeMetricsInboundPolicy=void 0;var rx=Oe(),Nh=oe(),W_=sr(),xh;function Q_(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}o(Q_,"headersToNameValuePairs");function nx(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}o(nx,"queryToNameValueParis");function ix(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}o(ix,"parseIntOrUndefined");var Y_={};async function ox(e,t,r,n){let i=new Date,s=Date.now();return xh||(xh={name:"zuplo",version:Nh.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Nh.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,W_.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,W_.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Nh.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:xh,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:Q_(e.headers),queryString:nx(e.query)},response:{status:a.status,statusText:a.statusText,headers:Q_(a.headers),content:{size:ix(e.headers.get("content-length"))}}}]}}},d=Y_[r.apiKey];if(!d){let p=r.apiKey;d=new rx.BatchDispatch("readme-metering-inbound-policy",10,async h=>{try{let f=r.url??"https://metrics.readme.io/request",y=await fetch(f,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(f){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),Y_[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}o(ox,"ReadmeMetricsInboundPolicy");Sc.ReadmeMetricsInboundPolicy=ox});var X_=b(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.RemoveHeadersInboundPolicy=void 0;var sx=k(),ax=Be(),cx=o(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new sx.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(e.headers);return i.forEach(c=>{s.delete(c)}),new ax.ZuploRequest(e,{headers:s})},"RemoveHeadersInboundPolicy");Ic.RemoveHeadersInboundPolicy=cx});var eE=b(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.RemoveHeadersOutboundPolicy=void 0;var ux=k(),lx=o(async(e,t,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new ux.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return s.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Pc.RemoveHeadersOutboundPolicy=lx});var tE=b(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.RemoveQueryParamsInboundPolicy=void 0;var dx=k(),px=Be(),hx=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new dx.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(e.url);return i.forEach(c=>{s.searchParams.delete(c)}),new px.ZuploRequest(s.toString(),e)},"RemoveQueryParamsInboundPolicy");Ac.RemoveQueryParamsInboundPolicy=hx});var rE=b(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.ReplaceStringOutboundPolicy=void 0;var fx=o(async(e,t,r,n)=>{let i=await e.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Rc.ReplaceStringOutboundPolicy=fx});var iE=b(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.RequestSizeLimitInboundPolicy=void 0;var nE=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),mx=o(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?nE():s&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?nE():e},"RequestSizeLimitInboundPolicy");Oc.RequestSizeLimitInboundPolicy=mx});var Nc=b(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.sanitizedIdentifierName=lt.getIdForRefSchema=lt.getIdForRequestBodySchema=lt.getIdForParameterSchema=lt.getRawOperationDataIdentifierName=void 0;function yx(e,t,r){return`_${tn(e+"_"+t+"_"+r)}`}o(yx,"getRawOperationDataIdentifierName");lt.getRawOperationDataIdentifierName=yx;function gx(e,t,r,n){return`_${tn(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(gx,"getIdForParameterSchema");lt.getIdForParameterSchema=gx;function bx(e,t,r){return`_${tn(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${tn(r.toLowerCase())}`}o(bx,"getIdForRequestBodySchema");lt.getIdForRequestBodySchema=bx;function _x(e,t){return`_${tn(e)}__${tn(t)}`}o(_x,"getIdForRefSchema");lt.getIdForRefSchema=_x;function tn(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("")}o(tn,"sanitizedIdentifierName");lt.sanitizedIdentifierName=tn});var no=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.getErrorsFromValidator=qe.shouldReject=qe.shouldLog=qe.logErrors=qe.validateParameters=qe.getParametersForOperation=void 0;var Ex=kr(),wx=Nc(),vx=o(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");qe.getParametersForOperation=vx;var Tx=o((e,t,r,n,i)=>{let s=[],a=!0,c=[];return e.forEach(u=>{let l=u.required||i==="path";if(l&&!t[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!t[u.name])){let d=(0,wx.getIdForParameterSchema)(r,n,i,u.name),p=Ex.Gateway.instance.schemaValidator[d],h=p(t[u.name]),f=(0,qe.getErrorsFromValidator)(p.errors);h||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${f.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");qe.validateParameters=Tx;var Sx=o((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");qe.logErrors=Sx;var Ix=o(e=>e==="log-only"||e==="reject-and-log","shouldLog");qe.shouldLog=Ix;var Px=o(e=>e==="reject-only"||e==="reject-and-log","shouldReject");qe.shouldReject=Px;var Ax=o(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");qe.getErrorsFromValidator=Ax});var oE=b(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.handleBodyValidation=void 0;var Rx=kr(),xc=pe(),Ox=Nc(),et=no();async function Nx(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(f){let y=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,_=xc.HttpProblems.badRequest(t,e,{detail:`${y}, see errors property for more details`,errors:`${f}`});if((0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",y,[n],f),(0,et.shouldReject)(r.validateBody))return _}if(!t.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,y=xc.HttpProblems.badRequest(t,e,{detail:f});return(0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",f,[n],[f]),(0,et.shouldReject)(r.validateBody)?y:void 0}let i=t.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,Ox.getIdForRequestBodySchema)(e.route.path,t.method,i),c=Rx.Gateway.instance.schemaValidator[a];if(!c){let f=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,y=xc.HttpProblems.badRequest(t,e,{detail:f});return(0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",f,[n],[f]),(0,et.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,et.getErrorsFromValidator)(l),h=xc.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",d,[n],p),(0,et.shouldReject)(r.validateBody))return h}o(Nx,"handleBodyValidation");Cc.handleBodyValidation=Nx});var sE=b(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.handleHeadersValidation=void 0;var xx=pe(),io=no();function Cx(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,io.getParametersForOperation)(e),s=(0,io.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=xx.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,io.shouldLog)(r.validateHeaders)&&(0,io.logErrors)(e,r.logLevel??"info",a,s.invalidValues,s.errors),(0,io.shouldReject)(r.validateHeaders))return c}}o(Cx,"handleHeadersValidation");Dc.handleHeadersValidation=Cx});var aE=b(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.handlePathParameterValidation=void 0;var Dx=pe(),oo=no();function Lx(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,oo.getParametersForOperation)(e),i=(0,oo.validateParameters)(n.filter(s=>s.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=Dx.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,oo.shouldLog)(r.validatePathParameters)&&(0,oo.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,oo.shouldReject)(r.validatePathParameters))return a}}o(Lx,"handlePathParameterValidation");Lc.handlePathParameterValidation=Lx});var cE=b(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.handleQueryParameterValidation=void 0;var Mx=pe(),so=no();function Ux(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,so.getParametersForOperation)(e),i=(0,so.validateParameters)(n.filter(s=>s.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=Mx.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,so.shouldLog)(r.validateQueryParameters)&&(0,so.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,so.shouldReject)(r.validateQueryParameters))return a}}o(Ux,"handleQueryParameterValidation");Mc.handleQueryParameterValidation=Ux});var uE=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.SchemaBasedRequestValidation=rn.RequestValidationInboundPolicy=void 0;var kx=oE(),Fx=sE(),Hx=aE(),qx=cE(),$x=o(async(e,t,r)=>{let n=(0,qx.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,Hx.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,Fx.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,kx.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");rn.RequestValidationInboundPolicy=$x;rn.SchemaBasedRequestValidation=rn.RequestValidationInboundPolicy});var lE=b(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.RequireOriginInboundPolicy=void 0;var jx=k(),Vx=pe(),Gx=o(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new jx.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 s=e.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Vx.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");Uc.RequireOriginInboundPolicy=Gx});var dE=b(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.SetBodyInboundPolicy=void 0;var Bx=Be(),Kx=o(async(e,t,r)=>new Bx.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");kc.SetBodyInboundPolicy=Kx});var hE=b(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.SetHeadersInboundPolicy=void 0;var pE=k(),Jx=Be(),zx=o(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new pE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new pE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Jx.ZuploRequest(e,{headers:s})},"SetHeadersInboundPolicy");Fc.SetHeadersInboundPolicy=zx});var mE=b(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.SetHeadersOutboundPolicy=void 0;var fE=k(),Wx=o(async(e,t,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new fE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new fE.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");Hc.SetHeadersOutboundPolicy=Wx});var gE=b(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.SetQueryParamsInboundPolicy=void 0;var yE=k(),Qx=Be(),Yx=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new yE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new yE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new Qx.ZuploRequest(s.toString(),e)},"SetQueryParamsInboundPolicy");qc.SetQueryParamsInboundPolicy=Yx});var bE=b($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.SetStatusOutboundPolicy=void 0;var Zx=o(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");$c.SetStatusOutboundPolicy=Zx});var _E=b(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.SleepInboundPolicy=void 0;var Xx=k(),eC=o(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),tC=o(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Xx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await eC(r.sleepInMs),e},"SleepInboundPolicy");jc.SleepInboundPolicy=tC});var wE=b(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.SupabaseJwtInboundPolicy=void 0;var EE=k(),rC=pe(),nC=Be(),iC=Mt(),oC=Qt(),sC=o(async(e,t,r,n)=>{(0,iC.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,oC.OpenIdJwtInboundPolicy)(e,t,i,n);if(s instanceof Response)return s;if(!(s instanceof nC.ZuploRequest))throw new EE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=e.user?.data.app_metadata;if(!c)throw new EE.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?rC.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Vc.SupabaseJwtInboundPolicy=sC});var TE=b(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var aC=Wt(),cC=er(),vE=k(),uC=Cn(),lC=Mt(),dC=o(async(e,t,r,n)=>{(0,lC.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,aC.getPolicyCacheName)(n,r),s=new cC.MemoryZoneReadThroughCache(i,t),a=await s.get(n);if(!a){let c=await pC(r,t);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");Gc.UpstreamAzureAdServiceAuthInboundPolicy=dC;async function pC(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,uC.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 s=await n.text();t.log.error("Could not get token from Azure AD",s)}catch{}throw new vE.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 vE.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(pC,"getAccessToken")});var IE=b(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var hC=Wt(),fC=er(),mC=k(),Ch=Dn(),yC=Mt(),SE="https://accounts.google.com/o/oauth2/token",Dh,gC=o(async(e,t,r,n)=>{(0,yC.optionValidator)(r,n).required("serviceAccountJson","string"),Dh||(Dh=await Ch.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(" ")},s=await(0,hC.getPolicyCacheName)(n,r),a=new fC.MemoryZoneReadThroughCache(s,t),c=await a.get(n);if(!c){let u=await(0,Ch.getTokenFromGcpServiceAccount)({serviceAccount:Dh,audience:SE,payload:i}),l=await(0,Ch.exchangeGgpJwtForIdToken)(SE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new mC.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");Bc.UpstreamFirebaseAdminAuthInboundPolicy=gC});var PE=b(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var bC=Wt(),_C=er(),ai=k(),EC=hh(),Lh=Dn(),wC=sr(),vC=Mt(),TC="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",SC=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Mh,IC=o(async(e,t,r,n)=>{if((0,vC.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new ai.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(SC.indexOf(p)!==-1)throw new ai.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Mh||(Mh=await Lh.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!e.user)throw new ai.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new ai.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,wC.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new ai.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,bC.getPolicyCacheName)(n,r),c=new _C.MemoryZoneReadThroughCache(a,t),u={uid:s,claims:i},l=await(0,EC.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Lh.getTokenFromGcpServiceAccount)({serviceAccount:Mh,audience:TC,payload:u}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,f=await(0,Lh.exchangeFirebaseJwtForIdToken)(h,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!f.idToken)throw new ai.RuntimeError("Invalid token response from Firebase");d=f.idToken,c.put(l,d,(f.expiresIn?parseInt(f.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");Kc.UpstreamFirebaseUserAuthInboundPolicy=IC});var RE=b(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.UpstreamGcpJwtInboundPolicy=void 0;var AE=Dn(),PC=Mt(),Uh,AC=o(async(e,t,r,n)=>{(0,PC.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),Uh||(Uh=await AE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,AE.getTokenFromGcpServiceAccount)({serviceAccount:Uh,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");Jc.UpstreamGcpJwtInboundPolicy=AC});var NE=b(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.UpstreamGcpServiceAuthInboundPolicy=void 0;var RC=Wt(),OC=Vu(),NC=er(),ao=k(),kh=Dn(),xC=sr(),CC=Mt(),OE="https://www.googleapis.com/oauth2/v4/token",Fh,DC=o(async(e,t,r,n)=>{(0,CC.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Fh||(Fh=await kh.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new ao.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,xC.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof ao.ConfigurationError?new ao.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,RC.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new OC.MemoryCache(s):a=new NC.MemoryZoneReadThroughCache(s,t);let c=await a.get(n);if(!c){let u=await(0,kh.getTokenFromGcpServiceAccount)({serviceAccount:Fh,audience:OE,payload:i}),l=await(0,kh.exchangeGgpJwtForIdToken)(OE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new ao.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new ao.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamGcpServiceAuthInboundPolicy");zc.UpstreamGcpServiceAuthInboundPolicy=DC});var CE=b(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.ValidateJsonSchemaInbound=void 0;var LC=k(),xE=pe(),MC=o(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return xE.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 LC.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 xE.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");Wc.ValidateJsonSchemaInbound=MC});var LE=b((zK,DE)=>{"use strict";var UC=Object.defineProperty,J=o((e,t)=>UC(e,"name",{value:t,configurable:!0}),"u"),Rr=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"E"),kC=Rr(e=>{var t={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,i){return i},attributeValueProcessor:function(n,i){return i},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,i,s){return n}},r=J(function(n){return Object.assign({},t,n)},"buildOptions");e.buildOptions=r,e.defaultOptions=t}),Hh=Rr(e=>{"use strict";var t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+t+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=J(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let h=d.length;for(let f=0;f<h;f++)p.push(d[f]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=J(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let h=0;h<p;h++)l==="strict"?c[d[h]]=[u[d[h]]]:c[d[h]]=u[d[h]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=n}),FC=Rr((e,t)=>{"use strict";var r=class{static{o(this,"P")}static{J(this,"XmlNode")}constructor(n){this.tagname=n,this.child=[],this[":@"]={}}add(n,i){n==="__proto__"&&(n="#__proto__"),this.child.push({[n]:i})}addChild(n){n.tagname==="__proto__"&&(n.tagname="#__proto__"),n[":@"]&&Object.keys(n[":@"]).length>0?this.child.push({[n.tagname]:n.child,":@":n[":@"]}):this.child.push({[n.tagname]:n.child})}};t.exports=r}),HC=Rr((e,t)=>{var r=Hh();function n(p,h){let f={};if(p[h+3]==="O"&&p[h+4]==="C"&&p[h+5]==="T"&&p[h+6]==="Y"&&p[h+7]==="P"&&p[h+8]==="E"){h=h+9;let y=1,_=!1,I=!1,O="";for(;h<p.length;h++)if(p[h]==="<"&&!I){if(_&&a(p,h))h+=7,[entityName,val,h]=i(p,h+1),val.indexOf("&")===-1&&(f[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(_&&c(p,h))h+=8;else if(_&&u(p,h))h+=8;else if(_&&l(p,h))h+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");y++,O=""}else if(p[h]===">"){if(I?p[h-1]==="-"&&p[h-2]==="-"&&(I=!1,y--):y--,y===0)break}else p[h]==="["?_=!0:O+=p[h];if(y!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:f,i:h}}o(n,"ue"),J(n,"readDocType");function i(p,h){let f="";for(;h<p.length&&p[h]!=="'"&&p[h]!=='"';h++)f+=p[h];if(f=f.trim(),f.indexOf(" ")!==-1)throw new Error("External entites are not supported");let y=p[h++],_="";for(;h<p.length&&p[h]!==y;h++)_+=p[h];return[f,_,h]}o(i,"le"),J(i,"readEntityExp");function s(p,h){return p[h+1]==="!"&&p[h+2]==="-"&&p[h+3]==="-"}o(s,"ce"),J(s,"isComment");function a(p,h){return p[h+1]==="!"&&p[h+2]==="E"&&p[h+3]==="N"&&p[h+4]==="T"&&p[h+5]==="I"&&p[h+6]==="T"&&p[h+7]==="Y"}o(a,"de"),J(a,"isEntity");function c(p,h){return p[h+1]==="!"&&p[h+2]==="E"&&p[h+3]==="L"&&p[h+4]==="E"&&p[h+5]==="M"&&p[h+6]==="E"&&p[h+7]==="N"&&p[h+8]==="T"}o(c,"ge"),J(c,"isElement");function u(p,h){return p[h+1]==="!"&&p[h+2]==="A"&&p[h+3]==="T"&&p[h+4]==="T"&&p[h+5]==="L"&&p[h+6]==="I"&&p[h+7]==="S"&&p[h+8]==="T"}o(u,"ae"),J(u,"isAttlist");function l(p,h){return p[h+1]==="!"&&p[h+2]==="N"&&p[h+3]==="O"&&p[h+4]==="T"&&p[h+5]==="A"&&p[h+6]==="T"&&p[h+7]==="I"&&p[h+8]==="O"&&p[h+9]==="N"}o(l,"he"),J(l,"isNotation");function d(p){if(r.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}o(d,"pe"),J(d,"validateEntityName"),t.exports=n}),qC=Rr((e,t)=>{var r=/^[-+]?0x[a-fA-F0-9]+$/,n=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var i={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(c,u={}){if(u=Object.assign({},i,u),!c||typeof c!="string")return c;let l=c.trim();if(u.skipLike!==void 0&&u.skipLike.test(l))return c;if(u.hex&&r.test(l))return Number.parseInt(l,16);{let d=n.exec(l);if(d){let p=d[1],h=d[2],f=a(d[3]),y=d[4]||d[6];if(!u.leadingZeros&&h.length>0&&p&&l[2]!=="."||!u.leadingZeros&&h.length>0&&!p&&l[1]!==".")return c;{let _=Number(l),I=""+_;return I.search(/[eE]/)!==-1||y?u.eNotation?_:c:l.indexOf(".")!==-1?I==="0"&&f===""||I===f||p&&I==="-"+f?_:c:h?f===I||p+f===I?_:c:l===I||l===p+I?_:c}}else return c}}o(s,"Te"),J(s,"toNumber");function a(c){return c&&c.indexOf(".")!==-1&&(c=c.replace(/0+$/,""),c==="."?c="0":c[0]==="."?c="0"+c:c[c.length-1]==="."&&(c=c.substr(0,c.length-1))),c}o(a,"ye"),J(a,"trimZeros"),t.exports=s}),$C=Rr((e,t)=>{"use strict";var r=Hh(),n=FC(),i=HC(),s=qC(),a=class{static{o(this,"C")}static{J(this,"OrderedObjParser")}constructor(w){this.options=w,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"}},this.addExternalEntities=c,this.parseXml=h,this.parseTextData=u,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=y,this.readStopNodeData=R,this.saveTextToParentTag=_,this.addChild=f}};function c(w){let S=Object.keys(w);for(let x=0;x<S.length;x++){let E=S[x];this.lastEntities[E]={regex:new RegExp("&"+E+";","g"),val:w[E]}}}o(c,"Oe"),J(c,"addExternalEntities");function u(w,S,x,E,P,C,H){if(w!==void 0&&(this.options.trimValues&&!E&&(w=w.trim()),w.length>0)){H||(w=this.replaceEntitiesValue(w));let D=this.options.tagValueProcessor(S,w,x,P,C);return D==null?w:typeof D!=typeof w||D!==w?D:this.options.trimValues?K(w,this.options.parseTagValue,this.options.numberParseOptions):w.trim()===w?K(w,this.options.parseTagValue,this.options.numberParseOptions):w}}o(u,"Ae"),J(u,"parseTextData");function l(w){if(this.options.removeNSPrefix){let S=w.split(":"),x=w.charAt(0)==="/"?"/":"";if(S[0]==="xmlns")return"";S.length===2&&(w=x+S[1])}return w}o(l,"ve"),J(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(w,S,x){if(!this.options.ignoreAttributes&&typeof w=="string"){let E=r.getAllMatches(w,d),P=E.length,C={};for(let H=0;H<P;H++){let D=this.resolveNameSpace(E[H][1]),X=E[H][4],ie=this.options.attributeNamePrefix+D;if(D.length)if(this.options.transformAttributeName&&(ie=this.options.transformAttributeName(ie)),ie==="__proto__"&&(ie="#__proto__"),X!==void 0){this.options.trimValues&&(X=X.trim()),X=this.replaceEntitiesValue(X);let Ge=this.options.attributeValueProcessor(D,X,S);Ge==null?C[ie]=X:typeof Ge!=typeof X||Ge!==X?C[ie]=Ge:C[ie]=K(X,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(C[ie]=!0)}if(!Object.keys(C).length)return;if(this.options.attributesGroupName){let H={};return H[this.options.attributesGroupName]=C,H}return C}}o(p,"Ce"),J(p,"buildAttributesMap");var h=J(function(w){w=w.replace(/\r\n?/g,`
|
|
75
75
|
`);let S=new n("!xml"),x=S,E="",P="";for(let C=0;C<w.length;C++)if(w[C]==="<")if(w[C+1]==="/"){let H=g(w,">",C,"Closing Tag is not closed."),D=w.substring(C+2,H).trim();if(this.options.removeNSPrefix){let Ge=D.indexOf(":");Ge!==-1&&(D=D.substr(Ge+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),x&&(E=this.saveTextToParentTag(E,x,P));let X=P.substring(P.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ie=0;X&&this.options.unpairedTags.indexOf(X)!==-1?(ie=P.lastIndexOf(".",P.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=P.lastIndexOf("."),P=P.substring(0,ie),x=this.tagsNodeStack.pop(),E="",C=H}else if(w[C+1]==="?"){let H=v(w,C,!1,"?>");if(!H)throw new Error("Pi Tag is not closed.");if(E=this.saveTextToParentTag(E,x,P),!(this.options.ignoreDeclaration&&H.tagName==="?xml"||this.options.ignorePiTags)){let D=new n(H.tagName);D.add(this.options.textNodeName,""),H.tagName!==H.tagExp&&H.attrExpPresent&&(D[":@"]=this.buildAttributesMap(H.tagExp,P,H.tagName)),this.addChild(x,D,P)}C=H.closeIndex+1}else if(w.substr(C+1,3)==="!--"){let H=g(w,"-->",C+4,"Comment is not closed.");if(this.options.commentPropName){let D=w.substring(C+4,H-2);E=this.saveTextToParentTag(E,x,P),x.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}C=H}else if(w.substr(C+1,2)==="!D"){let H=i(w,C);this.docTypeEntities=H.entities,C=H.i}else if(w.substr(C+1,2)==="!["){let H=g(w,"]]>",C,"CDATA is not closed.")-2,D=w.substring(C+9,H);E=this.saveTextToParentTag(E,x,P);let X=this.parseTextData(D,x.tagname,P,!0,!1,!0,!0);X==null&&(X=""),this.options.cdataPropName?x.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):x.add(this.options.textNodeName,X),C=H+2}else{let H=v(w,C,this.options.removeNSPrefix),D=H.tagName,X=H.rawTagName,ie=H.tagExp,Ge=H.attrExpPresent,cn=H.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),x&&E&&x.tagname!=="!xml"&&(E=this.saveTextToParentTag(E,x,P,!1));let bf=x;if(bf&&this.options.unpairedTags.indexOf(bf.tagname)!==-1&&(x=this.tagsNodeStack.pop(),P=P.substring(0,P.lastIndexOf("."))),D!==S.tagname&&(P+=P?"."+D:D),this.isItStopNode(this.options.stopNodes,P,D)){let ot="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)C=H.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)C=H.closeIndex;else{let Uu=this.readStopNodeData(w,X,cn+1);if(!Uu)throw new Error(`Unexpected end of ${X}`);C=Uu.i,ot=Uu.tagContent}let Mu=new n(D);D!==ie&&Ge&&(Mu[":@"]=this.buildAttributesMap(ie,P,D)),ot&&(ot=this.parseTextData(ot,D,P,!0,Ge,!0,!0)),P=P.substr(0,P.lastIndexOf(".")),Mu.add(this.options.textNodeName,ot),this.addChild(x,Mu,P)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),P=P.substr(0,P.length-1),ie=D):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let ot=new n(D);D!==ie&&Ge&&(ot[":@"]=this.buildAttributesMap(ie,P,D)),this.addChild(x,ot,P),P=P.substr(0,P.lastIndexOf("."))}else{let ot=new n(D);this.tagsNodeStack.push(x),D!==ie&&Ge&&(ot[":@"]=this.buildAttributesMap(ie,P,D)),this.addChild(x,ot,P),x=ot}E="",C=cn}}else E+=w[C];return S.child},"parseXml");function f(w,S,x){let E=this.options.updateTag(S.tagname,x,S[":@"]);E===!1||(typeof E=="string"&&(S.tagname=E),w.addChild(S))}o(f,"Fe"),J(f,"addChild");var y=J(function(w){if(this.options.processEntities){for(let S in this.docTypeEntities){let x=this.docTypeEntities[S];w=w.replace(x.regx,x.val)}for(let S in this.lastEntities){let x=this.lastEntities[S];w=w.replace(x.regex,x.val)}if(this.options.htmlEntities)for(let S in this.htmlEntities){let x=this.htmlEntities[S];w=w.replace(x.regex,x.val)}w=w.replace(this.ampEntity.regex,this.ampEntity.val)}return w},"replaceEntitiesValue");function _(w,S,x,E){return w&&(E===void 0&&(E=Object.keys(S.child).length===0),w=this.parseTextData(w,S.tagname,x,!1,S[":@"]?Object.keys(S[":@"]).length!==0:!1,E),w!==void 0&&w!==""&&S.add(this.options.textNodeName,w),w=""),w}o(_,"_e"),J(_,"saveTextToParentTag");function I(w,S,x){let E="*."+x;for(let P in w){let C=w[P];if(E===C||S===C)return!0}return!1}o(I,"Ve"),J(I,"isItStopNode");function O(w,S,x=">"){let E,P="";for(let C=S;C<w.length;C++){let H=w[C];if(E)H===E&&(E="");else if(H==='"'||H==="'")E=H;else if(H===x[0])if(x[1]){if(w[C+1]===x[1])return{data:P,index:C}}else return{data:P,index:C};else H===" "&&(H=" ");P+=H}}o(O,"me"),J(O,"tagExpWithClosingIndex");function g(w,S,x,E){let P=w.indexOf(S,x);if(P===-1)throw new Error(E);return P+S.length-1}o(g,"T"),J(g,"findClosingIndex");function v(w,S,x,E=">"){let P=O(w,S+1,E);if(!P)return;let C=P.data,H=P.index,D=C.search(/\s/),X=C,ie=!0;D!==-1&&(X=C.substring(0,D),C=C.substring(D+1).trimStart());let Ge=X;if(x){let cn=X.indexOf(":");cn!==-1&&(X=X.substr(cn+1),ie=X!==P.data.substr(cn+1))}return{tagName:X,tagExp:C,closeIndex:H,attrExpPresent:ie,rawTagName:Ge}}o(v,"k"),J(v,"readTagExp");function R(w,S,x){let E=x,P=1;for(;x<w.length;x++)if(w[x]==="<")if(w[x+1]==="/"){let C=g(w,">",x,`${S} is not closed`);if(w.substring(x+2,C).trim()===S&&(P--,P===0))return{tagContent:w.substring(E,x),i:C};x=C}else if(w[x+1]==="?")x=g(w,"?>",x+1,"StopNode is not closed.");else if(w.substr(x+1,3)==="!--")x=g(w,"-->",x+3,"StopNode is not closed.");else if(w.substr(x+1,2)==="![")x=g(w,"]]>",x,"StopNode is not closed.")-2;else{let C=v(w,x,">");C&&((C&&C.tagName)===S&&C.tagExp[C.tagExp.length-1]!=="/"&&P++,x=C.closeIndex)}}o(R,"je"),J(R,"readStopNodeData");function K(w,S,x){if(S&&typeof w=="string"){let E=w.trim();return E==="true"?!0:E==="false"?!1:s(w,x)}else return r.isExist(w)?w:""}o(K,"F"),J(K,"parseValue"),t.exports=a}),jC=Rr(e=>{"use strict";function t(a,c){return r(a,c)}o(t,"qe"),J(t,"prettify");function r(a,c,u){let l,d={};for(let p=0;p<a.length;p++){let h=a[p],f=n(h),y="";if(u===void 0?y=f:y=u+"."+f,f===c.textNodeName)l===void 0?l=h[f]:l+=""+h[f];else{if(f===void 0)continue;if(h[f]){let _=r(h[f],c,y),I=s(_,c);h[":@"]?i(_,h[":@"],y,c):Object.keys(_).length===1&&_[c.textNodeName]!==void 0&&!c.alwaysCreateTextNode?_=_[c.textNodeName]:Object.keys(_).length===0&&(c.alwaysCreateTextNode?_[c.textNodeName]="":_=""),d[f]!==void 0&&d.hasOwnProperty(f)?(Array.isArray(d[f])||(d[f]=[d[f]]),d[f].push(_)):c.isArray(f,y,I)?d[f]=[_]:d[f]=_}}}return typeof l=="string"?l.length>0&&(d[c.textNodeName]=l):l!==void 0&&(d[c.textNodeName]=l),d}o(r,"G"),J(r,"compress");function n(a){let c=Object.keys(a);for(let u=0;u<c.length;u++){let l=c[u];if(l!==":@")return l}}o(n,"Re"),J(n,"propName");function i(a,c,u,l){if(c){let d=Object.keys(c),p=d.length;for(let h=0;h<p;h++){let f=d[h];l.isArray(f,u+"."+f,!0,!0)?a[f]=[c[f]]:a[f]=c[f]}}}o(i,"$e"),J(i,"assignAttributes");function s(a,c){let{textNodeName:u}=c,l=Object.keys(a).length;return!!(l===0||l===1&&(a[u]||typeof a[u]=="boolean"||a[u]===0))}o(s,"Be"),J(s,"isLeafTag"),e.prettify=t}),VC=Rr(e=>{"use strict";var t=Hh(),r={allowBooleanAttributes:!1,unpairedTags:[]};e.validate=function(g,v){v=Object.assign({},r,v);let R=[],K=!1,w=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let S=0;S<g.length;S++)if(g[S]==="<"&&g[S+1]==="?"){if(S+=2,S=i(g,S),S.err)return S}else if(g[S]==="<"){let x=S;if(S++,g[S]==="!"){S=s(g,S);continue}else{let E=!1;g[S]==="/"&&(E=!0,S++);let P="";for(;S<g.length&&g[S]!==">"&&g[S]!==" "&&g[S]!==" "&&g[S]!==`
|
|
76
76
|
`&&g[S]!=="\r";S++)P+=g[S];if(P=P.trim(),P[P.length-1]==="/"&&(P=P.substring(0,P.length-1),S--),!_(P)){let D;return P.trim().length===0?D="Invalid space after '<'.":D="Tag '"+P+"' is an invalid name.",f("InvalidTag",D,I(g,S))}let C=u(g,S);if(C===!1)return f("InvalidAttr","Attributes for '"+P+"' have open quote.",I(g,S));let H=C.value;if(S=C.index,H[H.length-1]==="/"){let D=S-H.length;H=H.substring(0,H.length-1);let X=d(H,v);if(X===!0)K=!0;else return f(X.err.code,X.err.msg,I(g,D+X.err.line))}else if(E)if(C.tagClosed){if(H.trim().length>0)return f("InvalidTag","Closing tag '"+P+"' can't have attributes or invalid starting.",I(g,x));{let D=R.pop();if(P!==D.tagName){let X=I(g,D.tagStartPos);return f("InvalidTag","Expected closing tag '"+D.tagName+"' (opened in line "+X.line+", col "+X.col+") instead of closing tag '"+P+"'.",I(g,x))}R.length==0&&(w=!0)}}else return f("InvalidTag","Closing tag '"+P+"' doesn't have proper closing.",I(g,S));else{let D=d(H,v);if(D!==!0)return f(D.err.code,D.err.msg,I(g,S-H.length+D.err.line));if(w===!0)return f("InvalidXml","Multiple possible root nodes found.",I(g,S));v.unpairedTags.indexOf(P)!==-1||R.push({tagName:P,tagStartPos:x}),K=!0}for(S++;S<g.length;S++)if(g[S]==="<")if(g[S+1]==="!"){S++,S=s(g,S);continue}else if(g[S+1]==="?"){if(S=i(g,++S),S.err)return S}else break;else if(g[S]==="&"){let D=h(g,S);if(D==-1)return f("InvalidChar","char '&' is not expected.",I(g,S));S=D}else if(w===!0&&!n(g[S]))return f("InvalidXml","Extra text at the end",I(g,S));g[S]==="<"&&S--}}else{if(n(g[S]))continue;return f("InvalidChar","char '"+g[S]+"' is not expected.",I(g,S))}if(K){if(R.length==1)return f("InvalidTag","Unclosed tag '"+R[0].tagName+"'.",I(g,R[0].tagStartPos));if(R.length>0)return f("InvalidXml","Invalid '"+JSON.stringify(R.map(S=>S.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return f("InvalidXml","Start tag expected.",1);return!0};function n(g){return g===" "||g===" "||g===`
|
|
77
77
|
`||g==="\r"}o(n,"W"),J(n,"isWhiteSpace");function i(g,v){let R=v;for(;v<g.length;v++)if(g[v]=="?"||g[v]==" "){let K=g.substr(R,v-R);if(v>5&&K==="xml")return f("InvalidXml","XML declaration allowed only at the start of the document.",I(g,v));if(g[v]=="?"&&g[v+1]==">"){v++;break}else continue}return v}o(i,"z"),J(i,"readPI");function s(g,v){if(g.length>v+5&&g[v+1]==="-"&&g[v+2]==="-"){for(v+=3;v<g.length;v++)if(g[v]==="-"&&g[v+1]==="-"&&g[v+2]===">"){v+=2;break}}else if(g.length>v+8&&g[v+1]==="D"&&g[v+2]==="O"&&g[v+3]==="C"&&g[v+4]==="T"&&g[v+5]==="Y"&&g[v+6]==="P"&&g[v+7]==="E"){let R=1;for(v+=8;v<g.length;v++)if(g[v]==="<")R++;else if(g[v]===">"&&(R--,R===0))break}else if(g.length>v+9&&g[v+1]==="["&&g[v+2]==="C"&&g[v+3]==="D"&&g[v+4]==="A"&&g[v+5]==="T"&&g[v+6]==="A"&&g[v+7]==="["){for(v+=8;v<g.length;v++)if(g[v]==="]"&&g[v+1]==="]"&&g[v+2]===">"){v+=2;break}}return v}o(s,"K"),J(s,"readCommentAndCDATA");var a='"',c="'";function u(g,v){let R="",K="",w=!1;for(;v<g.length;v++){if(g[v]===a||g[v]===c)K===""?K=g[v]:K!==g[v]||(K="");else if(g[v]===">"&&K===""){w=!0;break}R+=g[v]}return K!==""?!1:{value:R,index:v,tagClosed:w}}o(u,"Le"),J(u,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(g,v){let R=t.getAllMatches(g,l),K={};for(let w=0;w<R.length;w++){if(R[w][1].length===0)return f("InvalidAttr","Attribute '"+R[w][2]+"' has no space in starting.",O(R[w]));if(R[w][3]!==void 0&&R[w][4]===void 0)return f("InvalidAttr","Attribute '"+R[w][2]+"' is without value.",O(R[w]));if(R[w][3]===void 0&&!v.allowBooleanAttributes)return f("InvalidAttr","boolean attribute '"+R[w][2]+"' is not allowed.",O(R[w]));let S=R[w][2];if(!y(S))return f("InvalidAttr","Attribute '"+S+"' is an invalid name.",O(R[w]));if(!K.hasOwnProperty(S))K[S]=1;else return f("InvalidAttr","Attribute '"+S+"' is repeated.",O(R[w]))}return!0}o(d,"H"),J(d,"validateAttributeString");function p(g,v){let R=/\d/;for(g[v]==="x"&&(v++,R=/[\da-fA-F]/);v<g.length;v++){if(g[v]===";")return v;if(!g[v].match(R))break}return-1}o(p,"Ue"),J(p,"validateNumberAmpersand");function h(g,v){if(v++,g[v]===";")return-1;if(g[v]==="#")return v++,p(g,v);let R=0;for(;v<g.length;v++,R++)if(!(g[v].match(/\w/)&&R<20)){if(g[v]===";")break;return-1}return v}o(h,"xe"),J(h,"validateAmpersand");function f(g,v,R){return{err:{code:g,msg:v,line:R.line||R,col:R.col}}}o(f,"a"),J(f,"getErrorObject");function y(g){return t.isName(g)}o(y,"Ge"),J(y,"validateAttrName");function _(g){return t.isName(g)}o(_,"Je"),J(_,"validateTagName");function I(g,v){let R=g.substring(0,v).split(/\r?\n/);return{line:R.length,col:R[R.length-1].length+1}}o(I,"h"),J(I,"getLineNumberForPosition");function O(g){return g.startIndex+g[1].length}o(O,"I"),J(O,"getPositionFromMatch")}),{buildOptions:GC}=kC(),BC=$C(),{prettify:KC}=jC(),JC=VC(),zC=class{static{o(this,"_")}static{J(this,"XMLParser")}constructor(e){this.externalEntities={},this.options=GC(e)}parse(e,t){if(typeof e!="string")if(e.toString)e=e.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(t){t===!0&&(t={});let i=JC.validate(e,t);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}let r=new BC(this.options);r.addExternalEntities(this.externalEntities);let n=r.parseXml(e);return this.options.preserveOrder||n===void 0?n:KC(n,this.options)}addEntity(e,t){if(t.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(e.indexOf("&")!==-1||e.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(t==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}};DE.exports=zC;});var ME=b(ci=>{"use strict";var WC=ci&&ci.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ci,"__esModule",{value:!0});ci.XmlToJsonOutboundPolicy=void 0;var QC=k(),YC=WC(LE()),ZC=o(async(e,t,r,n,i)=>{let s;try{let u=await e.text();s=new YC.default().parse(u)}catch(u){let l=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${i}'.`;throw r.log.error(l,u),new QC.RuntimeError(l)}let a=new Headers(e.headers);return a.set("content-type","application/json"),new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:a})},"XmlToJsonOutboundPolicy");ci.XmlToJsonOutboundPolicy=ZC});var UE=b(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.ServiceProviderImpl=void 0;var XC=k(),qh=class{static{o(this,"ServiceProviderImpl")}services=new Map;addService(t,r){if(this.services.get(t))throw new XC.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)}};Qc.ServiceProviderImpl=qh});var WE=b(m=>{"use strict";var eD=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]}),$h=m&&m.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&eD(t,e,r)},tD=m&&m.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(m,"__esModule",{value:!0});m.OpenIdJwtInboundPolicy=m.OktaJwtInboundPolicy=m.MonetizationInboundPolicy=m.setMoesifContext=m.MoesifInboundPolicy=m.MockApiInboundPolicy=m.JWTScopeValidationInboundPolicy=m.GeoFilterInboundPolicy=m.FormDataToJsonInboundPolicy=m.FirebaseJwtInboundPolicy=m.CurityPhantomTokenInboundPolicy=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.OutboundPolicy=m.InboundPolicy=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.RuntimeError=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.XmlToJsonOutboundPolicy=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=m.RateLimitInboundPolicy=m.BasicRateLimitInboundPolicy=m.PropelAuthJwtInboundPolicy=void 0;Sf();var rD=er();Object.defineProperty(m,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return rD.MemoryZoneReadThroughCache}});var nD=xo();Object.defineProperty(m,"ZoneCache",{enumerable:!0,get:function(){return nD.ZoneCache}});var kE=Fr();Object.defineProperty(m,"ResponseSendingEvent",{enumerable:!0,get:function(){return kE.ResponseSendingEvent}});Object.defineProperty(m,"ResponseSentEvent",{enumerable:!0,get:function(){return kE.ResponseSentEvent}});var iD=cp();Object.defineProperty(m,"ContextData",{enumerable:!0,get:function(){return iD.ContextData}});var jh=Ki();Object.defineProperty(m,"environment",{enumerable:!0,get:function(){return jh.environment}});Object.defineProperty(m,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return jh.isRestrictedEnvVariableName}});Object.defineProperty(m,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return jh.isZuploReadableEnvVariableName}});var FE=k();Object.defineProperty(m,"ConfigurationError",{enumerable:!0,get:function(){return FE.ConfigurationError}});Object.defineProperty(m,"RuntimeError",{enumerable:!0,get:function(){return FE.RuntimeError}});var oD=lp();Object.defineProperty(m,"originalFetch",{enumerable:!0,get:function(){return oD.originalFetch}});var HE=Zg();Object.defineProperty(m,"Handler",{enumerable:!0,get:function(){return HE.Handler}});Object.defineProperty(m,"purgeGatewayCache",{enumerable:!0,get:function(){return HE.purgeGatewayCache}});var qE=mb();Object.defineProperty(m,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return qE.AwsLambdaHandlerExtensions}});Object.defineProperty(m,"awsLambdaHandler",{enumerable:!0,get:function(){return qE.awsLambdaHandler}});var sD=gb();Object.defineProperty(m,"openApiSpecHandler",{enumerable:!0,get:function(){return sD.openApiSpecHandler}});var aD=bb();Object.defineProperty(m,"redirectHandler",{enumerable:!0,get:function(){return aD.redirectHandler}});var cD=Eb();Object.defineProperty(m,"urlForwardHandler",{enumerable:!0,get:function(){return cD.urlForwardHandler}});var uD=vb();Object.defineProperty(m,"urlRewriteHandler",{enumerable:!0,get:function(){return uD.urlRewriteHandler}});var lD=Sb();Object.defineProperty(m,"webSocketHandler",{enumerable:!0,get:function(){return lD.webSocketHandler}});var dD=Ab();Object.defineProperty(m,"webSocketPipelineHandler",{enumerable:!0,get:function(){return dD.webSocketPipelineHandler}});var pD=fl();Object.defineProperty(m,"HttpStatusCode",{enumerable:!0,get:function(){return pD.HttpStatusCode}});$h(Mb(),m);$h(Fb(),m);var hD=Hb();Object.defineProperty(m,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return hD.AuditLogDataStaxProvider}});var fD=$b();Object.defineProperty(m,"AuditLogPlugin",{enumerable:!0,get:function(){return fD.AuditLogPlugin}});$h(e_(),m);var $E=Pi();Object.defineProperty(m,"InboundPolicy",{enumerable:!0,get:function(){return $E.InboundPolicy}});Object.defineProperty(m,"OutboundPolicy",{enumerable:!0,get:function(){return $E.OutboundPolicy}});var jE=o_();Object.defineProperty(m,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return jE.AmberfloMeteringInboundPolicy}});Object.defineProperty(m,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return jE.AmberfloMeteringPolicy}});var mD=l_();Object.defineProperty(m,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return mD.ApiAuthKeyInboundPolicy}});var yD=yh();Object.defineProperty(m,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return yD.ApiKeyInboundPolicy}});var gD=d_();Object.defineProperty(m,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return gD.Auth0JwtInboundPolicy}});var bD=p_();Object.defineProperty(m,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return bD.BasicAuthInboundPolicy}});var _D=h_();Object.defineProperty(m,"CachingInboundPolicy",{enumerable:!0,get:function(){return _D.CachingInboundPolicy}});var ED=f_();Object.defineProperty(m,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return ED.ChangeMethodInboundPolicy}});var wD=m_();Object.defineProperty(m,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return wD.ClearHeadersInboundPolicy}});var vD=y_();Object.defineProperty(m,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return vD.ClearHeadersOutboundPolicy}});var TD=g_();Object.defineProperty(m,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return TD.ClerkJwtInboundPolicy}});var SD=__();Object.defineProperty(m,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return SD.CognitoJwtInboundPolicy}});var ID=w_();Object.defineProperty(m,"CompositeInboundPolicy",{enumerable:!0,get:function(){return ID.CompositeInboundPolicy}});var PD=v_();Object.defineProperty(m,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return PD.CurityPhantomTokenInboundPolicy}});var AD=T_();Object.defineProperty(m,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return AD.FirebaseJwtInboundPolicy}});var RD=S_();Object.defineProperty(m,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return RD.FormDataToJsonInboundPolicy}});var OD=I_();Object.defineProperty(m,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return OD.GeoFilterInboundPolicy}});var ND=P_();Object.defineProperty(m,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return ND.JWTScopeValidationInboundPolicy}});var xD=R_();Object.defineProperty(m,"MockApiInboundPolicy",{enumerable:!0,get:function(){return xD.MockApiInboundPolicy}});var VE=D_();Object.defineProperty(m,"MoesifInboundPolicy",{enumerable:!0,get:function(){return VE.MoesifInboundPolicy}});Object.defineProperty(m,"setMoesifContext",{enumerable:!0,get:function(){return VE.setMoesifContext}});var CD=H_();Object.defineProperty(m,"MonetizationInboundPolicy",{enumerable:!0,get:function(){return CD.MonetizationInboundPolicy}});var DD=q_();Object.defineProperty(m,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return DD.OktaJwtInboundPolicy}});var LD=Qt();Object.defineProperty(m,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return LD.OpenIdJwtInboundPolicy}});var MD=$_();Object.defineProperty(m,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return MD.PropelAuthJwtInboundPolicy}});var GE=z_();Object.defineProperty(m,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return GE.RateLimitInboundPolicy}});Object.defineProperty(m,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return GE.RateLimitInboundPolicy}});var UD=Z_();Object.defineProperty(m,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return UD.ReadmeMetricsInboundPolicy}});var kD=X_();Object.defineProperty(m,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return kD.RemoveHeadersInboundPolicy}});var FD=eE();Object.defineProperty(m,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return FD.RemoveHeadersOutboundPolicy}});var HD=tE();Object.defineProperty(m,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return HD.RemoveQueryParamsInboundPolicy}});var qD=rE();Object.defineProperty(m,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return qD.ReplaceStringOutboundPolicy}});var $D=iE();Object.defineProperty(m,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return $D.RequestSizeLimitInboundPolicy}});var BE=uE();Object.defineProperty(m,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return BE.RequestValidationInboundPolicy}});Object.defineProperty(m,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return BE.SchemaBasedRequestValidation}});var jD=lE();Object.defineProperty(m,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return jD.RequireOriginInboundPolicy}});var VD=dE();Object.defineProperty(m,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return VD.SetBodyInboundPolicy}});var GD=hE();Object.defineProperty(m,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return GD.SetHeadersInboundPolicy}});var BD=mE();Object.defineProperty(m,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return BD.SetHeadersOutboundPolicy}});var KD=gE();Object.defineProperty(m,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return KD.SetQueryParamsInboundPolicy}});var JD=bE();Object.defineProperty(m,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return JD.SetStatusOutboundPolicy}});var zD=_E();Object.defineProperty(m,"SleepInboundPolicy",{enumerable:!0,get:function(){return zD.SleepInboundPolicy}});var WD=Kp();Object.defineProperty(m,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return WD.StripeWebhookVerificationInboundPolicy}});var QD=wE();Object.defineProperty(m,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return QD.SupabaseJwtInboundPolicy}});var YD=TE();Object.defineProperty(m,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return YD.UpstreamAzureAdServiceAuthInboundPolicy}});var ZD=IE();Object.defineProperty(m,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return ZD.UpstreamFirebaseAdminAuthInboundPolicy}});var XD=PE();Object.defineProperty(m,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return XD.UpstreamFirebaseUserAuthInboundPolicy}});var eL=RE();Object.defineProperty(m,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return eL.UpstreamGcpJwtInboundPolicy}});var tL=NE();Object.defineProperty(m,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return tL.UpstreamGcpServiceAuthInboundPolicy}});var rL=CE();Object.defineProperty(m,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return rL.ValidateJsonSchemaInbound}});var nL=ME();Object.defineProperty(m,"XmlToJsonOutboundPolicy",{enumerable:!0,get:function(){return nL.XmlToJsonOutboundPolicy}});var iL=pe();Object.defineProperty(m,"HttpProblems",{enumerable:!0,get:function(){return iL.HttpProblems}});var oL=qo();Object.defineProperty(m,"ProblemResponseFormatter",{enumerable:!0,get:function(){return oL.ProblemResponseFormatter}});var sL=Be();Object.defineProperty(m,"ZuploRequest",{enumerable:!0,get:function(){return sL.ZuploRequest}});var aL=qr();Object.defineProperty(m,"SystemRouteName",{enumerable:!0,get:function(){return aL.SystemRouteName}});var KE=Xd();Object.defineProperty(m,"LookupResult",{enumerable:!0,get:function(){return KE.LookupResult}});Object.defineProperty(m,"Router",{enumerable:!0,get:function(){return KE.Router}});var JE=il();Object.defineProperty(m,"ContentTypes",{enumerable:!0,get:function(){return JE.ContentTypes}});Object.defineProperty(m,"serialize",{enumerable:!0,get:function(){return JE.serialize}});var cL=UE();Object.defineProperty(m,"ServiceProviderImpl",{enumerable:!0,get:function(){return cL.ServiceProviderImpl}});var zE=Dl();Object.defineProperty(m,"API_KEY",{enumerable:!0,get:function(){return zE.API_KEY}});Object.defineProperty(m,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return zE.SYSTEM_LOGGER}});var uL=yl();Object.defineProperty(m,"httpStatuses",{enumerable:!0,get:function(){return tD(uL).default}});var lL=Ze();Object.defineProperty(m,"SystemLogMap",{enumerable:!0,get:function(){return lL.SystemLogMap}});var co=Nc();Object.defineProperty(m,"getIdForParameterSchema",{enumerable:!0,get:function(){return co.getIdForParameterSchema}});Object.defineProperty(m,"getIdForRefSchema",{enumerable:!0,get:function(){return co.getIdForRefSchema}});Object.defineProperty(m,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return co.getIdForRequestBodySchema}});Object.defineProperty(m,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return co.getRawOperationDataIdentifierName}});Object.defineProperty(m,"sanitizedIdentifierName",{enumerable:!0,get:function(){return co.sanitizedIdentifierName}})});var QE=b(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.BaseCryptoBeta=ui.supportedDigests=void 0;ui.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var Vh=class{static{o(this,"BaseCryptoBeta")}};ui.BaseCryptoBeta=Vh});var YE=b(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.WorkerCryptoBeta=void 0;var Gh=QE(),dL=k(),Bh=class extends Gh.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(t,r){if(!Gh.supportedDigests.includes(t.toLowerCase()))throw new dL.RuntimeError(`Algorithm ${t} is not supported. Try using ${Gh.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("")}};Yc.WorkerCryptoBeta=Bh});var ZE=b(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.BaseKeyValueStore=void 0;var Kh=class{static{o(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};Zc.BaseKeyValueStore=Kh});var ew=b(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.WorkerKeyValueStore=void 0;var XE=k(),pL=ZE(),Jh=class extends pL.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new XE.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 XE.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)}};Xc.WorkerKeyValueStore=Jh});var Vt=b(_t=>{"use strict";var hL=_t&&_t.__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]}),fL=_t&&_t.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&hL(t,e,r)};Object.defineProperty(_t,"__esModule",{value:!0});_t.KeyValueStore=_t.CryptoBeta=void 0;fL(WE(),_t);var mL=YE();Object.defineProperty(_t,"CryptoBeta",{enumerable:!0,get:function(){return mL.WorkerCryptoBeta}});var yL=ew();Object.defineProperty(_t,"KeyValueStore",{enumerable:!0,get:function(){return yL.WorkerKeyValueStore}})});var T1={};Io(T1,{GraphQLComplexityLimitInboundPolicy:()=>Cw,GraphQLDisableIntrospectionInboundPolicy:()=>Lw});module.exports=Po(T1);var wi=Ef(Vt());function ee(e,t){if(!!!e)throw new Error(t)}o(ee,"devAssert");function Ae(e){return typeof e=="object"&&e!==null}o(Ae,"isObjectLike");function kt(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}o(kt,"invariant");var gL=/\r\n|[\n\r]/g;function li(e,t){let r=0,n=1;for(let i of e.body.matchAll(gL)){if(typeof i.index=="number"||kt(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}o(li,"getLocation");function zh(e){return eu(e.source,li(e.source,e.start))}o(zh,"printLocation");function eu(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,s=e.locationOffset.line-1,a=t.line+s,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
|